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.

68293 lines
2.2MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. ==============================================================================
  20. This header contains the entire Juce source tree, and can be #included in
  21. all your source files.
  22. As well as including this in your files, you should also add juce_inline.cpp
  23. to your project (or juce_inline.mm on the Mac).
  24. ==============================================================================
  25. */
  26. #ifndef __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  27. #define __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  28. #define DONT_AUTOLINK_TO_JUCE_LIBRARY 1
  29. /*** Start of inlined file: juce.h ***/
  30. #ifndef __JUCE_JUCEHEADER__
  31. #define __JUCE_JUCEHEADER__
  32. /*
  33. This is the main JUCE header file that applications need to include.
  34. */
  35. /* This line is here just to help catch syntax errors caused by mistakes in other header
  36. files that are included before juce.h. If you hit an error at this line, it must be some
  37. kind of syntax problem in whatever code immediately precedes this header.
  38. This also acts as a sanity-check in case you're trying to build with a C or obj-C compiler
  39. rather than a proper C++ one.
  40. */
  41. namespace JuceDummyNamespace {}
  42. #define JUCE_PUBLIC_INCLUDES 1
  43. // (this includes things that need defining outside of the JUCE namespace)
  44. /*** Start of inlined file: juce_StandardHeader.h ***/
  45. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  46. #define __JUCE_STANDARDHEADER_JUCEHEADER__
  47. /** Current Juce version number.
  48. See also SystemStats::getJUCEVersion() for a string version.
  49. */
  50. #define JUCE_MAJOR_VERSION 1
  51. #define JUCE_MINOR_VERSION 53
  52. #define JUCE_BUILDNUMBER 76
  53. /** Current Juce version number.
  54. Bits 16 to 32 = major version.
  55. Bits 8 to 16 = minor version.
  56. Bits 0 to 8 = point release (not currently used).
  57. See also SystemStats::getJUCEVersion() for a string version.
  58. */
  59. #define JUCE_VERSION ((JUCE_MAJOR_VERSION << 16) + (JUCE_MINOR_VERSION << 8) + JUCE_BUILDNUMBER)
  60. /*** Start of inlined file: juce_TargetPlatform.h ***/
  61. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  62. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  63. /* This file figures out which platform is being built, and defines some macros
  64. that the rest of the code can use for OS-specific compilation.
  65. Macros that will be set here are:
  66. - One of JUCE_WINDOWS, JUCE_MAC JUCE_LINUX, JUCE_IOS, JUCE_ANDROID, etc.
  67. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  68. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  69. - Either JUCE_INTEL or JUCE_PPC
  70. - Either JUCE_GCC or JUCE_MSVC
  71. */
  72. #if (defined (_WIN32) || defined (_WIN64))
  73. #define JUCE_WIN32 1
  74. #define JUCE_WINDOWS 1
  75. #elif defined (JUCE_ANDROID)
  76. #undef JUCE_ANDROID
  77. #define JUCE_ANDROID 1
  78. #elif defined (LINUX) || defined (__linux__)
  79. #define JUCE_LINUX 1
  80. #elif defined (__APPLE_CPP__) || defined(__APPLE_CC__)
  81. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  82. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  83. #define JUCE_IPHONE 1
  84. #define JUCE_IOS 1
  85. #else
  86. #define JUCE_MAC 1
  87. #endif
  88. #else
  89. #error "Unknown platform!"
  90. #endif
  91. #if JUCE_WINDOWS
  92. #ifdef _MSC_VER
  93. #ifdef _WIN64
  94. #define JUCE_64BIT 1
  95. #else
  96. #define JUCE_32BIT 1
  97. #endif
  98. #endif
  99. #ifdef _DEBUG
  100. #define JUCE_DEBUG 1
  101. #endif
  102. #ifdef __MINGW32__
  103. #define JUCE_MINGW 1
  104. #endif
  105. /** If defined, this indicates that the processor is little-endian. */
  106. #define JUCE_LITTLE_ENDIAN 1
  107. #define JUCE_INTEL 1
  108. #endif
  109. #if JUCE_MAC || JUCE_IOS
  110. #if defined (DEBUG) || defined (_DEBUG) || ! (defined (NDEBUG) || defined (_NDEBUG))
  111. #define JUCE_DEBUG 1
  112. #endif
  113. #if ! (defined (DEBUG) || defined (_DEBUG) || defined (NDEBUG) || defined (_NDEBUG))
  114. #warning "Neither NDEBUG or DEBUG has been defined - you should set one of these to make it clear whether this is a release build,"
  115. #endif
  116. #ifdef __LITTLE_ENDIAN__
  117. #define JUCE_LITTLE_ENDIAN 1
  118. #else
  119. #define JUCE_BIG_ENDIAN 1
  120. #endif
  121. #endif
  122. #if JUCE_MAC
  123. #if defined (__ppc__) || defined (__ppc64__)
  124. #define JUCE_PPC 1
  125. #else
  126. #define JUCE_INTEL 1
  127. #endif
  128. #ifdef __LP64__
  129. #define JUCE_64BIT 1
  130. #else
  131. #define JUCE_32BIT 1
  132. #endif
  133. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  134. #error "Building for OSX 10.3 is no longer supported!"
  135. #endif
  136. #ifndef MAC_OS_X_VERSION_10_5
  137. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  138. #endif
  139. #endif
  140. #if JUCE_LINUX || JUCE_ANDROID
  141. #ifdef _DEBUG
  142. #define JUCE_DEBUG 1
  143. #endif
  144. // Allow override for big-endian Linux platforms
  145. #if defined (__LITTLE_ENDIAN__) || ! defined (JUCE_BIG_ENDIAN)
  146. #define JUCE_LITTLE_ENDIAN 1
  147. #undef JUCE_BIG_ENDIAN
  148. #else
  149. #undef JUCE_LITTLE_ENDIAN
  150. #define JUCE_BIG_ENDIAN 1
  151. #endif
  152. #if defined (__LP64__) || defined (_LP64)
  153. #define JUCE_64BIT 1
  154. #else
  155. #define JUCE_32BIT 1
  156. #endif
  157. #if __MMX__ || __SSE__ || __amd64__
  158. #define JUCE_INTEL 1
  159. #endif
  160. #endif
  161. // Compiler type macros.
  162. #ifdef __GNUC__
  163. #define JUCE_GCC 1
  164. #elif defined (_MSC_VER)
  165. #define JUCE_MSVC 1
  166. #if _MSC_VER < 1500
  167. #define JUCE_VC8_OR_EARLIER 1
  168. #if _MSC_VER < 1400
  169. #define JUCE_VC7_OR_EARLIER 1
  170. #if _MSC_VER < 1300
  171. #define JUCE_VC6 1
  172. #endif
  173. #endif
  174. #endif
  175. #if ! JUCE_VC7_OR_EARLIER
  176. #define JUCE_USE_INTRINSICS 1
  177. #endif
  178. #else
  179. #error unknown compiler
  180. #endif
  181. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  182. /*** End of inlined file: juce_TargetPlatform.h ***/
  183. // (sets up the various JUCE_WINDOWS, JUCE_MAC, etc flags)
  184. /*** Start of inlined file: juce_Config.h ***/
  185. #ifndef __JUCE_CONFIG_JUCEHEADER__
  186. #define __JUCE_CONFIG_JUCEHEADER__
  187. /*
  188. This file contains macros that enable/disable various JUCE features.
  189. */
  190. /** The name of the namespace that all Juce classes and functions will be
  191. put inside. If this is not defined, no namespace will be used.
  192. */
  193. #ifndef JUCE_NAMESPACE
  194. #define JUCE_NAMESPACE juce
  195. #endif
  196. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  197. project settings, but if you define this value, you can override this to force
  198. it to be true or false.
  199. */
  200. #ifndef JUCE_FORCE_DEBUG
  201. //#define JUCE_FORCE_DEBUG 0
  202. #endif
  203. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  204. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  205. Enabling it will also leave this turned on in release builds. When it's disabled,
  206. however, the jassert and jassertfalse macros will not be compiled in a
  207. release build.
  208. @see jassert, jassertfalse, Logger
  209. */
  210. #ifndef JUCE_LOG_ASSERTIONS
  211. #define JUCE_LOG_ASSERTIONS 0
  212. #endif
  213. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  214. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  215. on your Windows build machine.
  216. See the comments in the ASIOAudioIODevice class's header file for more
  217. info about this.
  218. */
  219. #ifndef JUCE_ASIO
  220. #define JUCE_ASIO 0
  221. #endif
  222. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  223. */
  224. #ifndef JUCE_WASAPI
  225. #define JUCE_WASAPI 0
  226. #endif
  227. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  228. */
  229. #ifndef JUCE_DIRECTSOUND
  230. #define JUCE_DIRECTSOUND 1
  231. #endif
  232. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  233. #ifndef JUCE_ALSA
  234. #define JUCE_ALSA 1
  235. #endif
  236. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  237. #ifndef JUCE_JACK
  238. #define JUCE_JACK 0
  239. #endif
  240. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  241. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  242. installed, and its header files will need to be on your include path.
  243. */
  244. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || JUCE_ANDROID || (JUCE_WINDOWS && ! JUCE_MSVC))
  245. #define JUCE_QUICKTIME 0
  246. #endif
  247. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  248. #undef JUCE_QUICKTIME
  249. #endif
  250. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  251. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  252. */
  253. #if ! (defined (JUCE_OPENGL) || JUCE_ANDROID)
  254. #define JUCE_OPENGL 1
  255. #endif
  256. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  257. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  258. */
  259. #ifndef JUCE_DIRECT2D
  260. #define JUCE_DIRECT2D 0
  261. #endif
  262. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  263. If your app doesn't need to read FLAC files, you might want to disable this to
  264. reduce the size of your codebase and build time.
  265. */
  266. #ifndef JUCE_USE_FLAC
  267. #define JUCE_USE_FLAC 1
  268. #endif
  269. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  270. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  271. reduce the size of your codebase and build time.
  272. */
  273. #ifndef JUCE_USE_OGGVORBIS
  274. #define JUCE_USE_OGGVORBIS 1
  275. #endif
  276. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  277. Unless you're using CD-burning, you should probably turn this flag off to
  278. reduce code size.
  279. */
  280. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  281. #define JUCE_USE_CDBURNER 1
  282. #endif
  283. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  284. Unless you're using CD-reading, you should probably turn this flag off to
  285. reduce code size.
  286. */
  287. #ifndef JUCE_USE_CDREADER
  288. #define JUCE_USE_CDREADER 1
  289. #endif
  290. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  291. */
  292. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  293. #define JUCE_USE_CAMERA 0
  294. #endif
  295. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  296. gets repainted will flash in a random colour, so that you can check exactly how much and how
  297. often your components are being drawn.
  298. */
  299. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  300. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  301. #endif
  302. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  303. Unless you specifically want to disable this, it's best to leave this option turned on.
  304. */
  305. #ifndef JUCE_USE_XINERAMA
  306. #define JUCE_USE_XINERAMA 1
  307. #endif
  308. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  309. turned on unless you have a good reason to disable it.
  310. */
  311. #ifndef JUCE_USE_XSHM
  312. #define JUCE_USE_XSHM 1
  313. #endif
  314. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  315. */
  316. #ifndef JUCE_USE_XRENDER
  317. #define JUCE_USE_XRENDER 0
  318. #endif
  319. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  320. unless you have a good reason to disable it.
  321. */
  322. #ifndef JUCE_USE_XCURSOR
  323. #define JUCE_USE_XCURSOR 1
  324. #endif
  325. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  326. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  327. you're building a plugin hosting app.
  328. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  329. */
  330. #ifndef JUCE_PLUGINHOST_VST
  331. #define JUCE_PLUGINHOST_VST 0
  332. #endif
  333. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  334. of course, and should only be enabled if you're building a plugin hosting app.
  335. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  336. */
  337. #ifndef JUCE_PLUGINHOST_AU
  338. #define JUCE_PLUGINHOST_AU 0
  339. #endif
  340. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  341. This should be enabled if you're writing a console application.
  342. */
  343. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  344. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  345. #endif
  346. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  347. If you're not using any embedded web-pages, turning this off may reduce your code size.
  348. */
  349. #ifndef JUCE_WEB_BROWSER
  350. #define JUCE_WEB_BROWSER 1
  351. #endif
  352. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  353. Carbon isn't required for a normal app, but may be needed by specialised classes like
  354. plugin-hosts, which support older APIs.
  355. */
  356. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  357. #define JUCE_SUPPORT_CARBON 1
  358. #endif
  359. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  360. You might need to tweak this if you're linking to an external zlib library in your app,
  361. but for normal apps, this option should be left alone.
  362. */
  363. #ifndef JUCE_INCLUDE_ZLIB_CODE
  364. #define JUCE_INCLUDE_ZLIB_CODE 1
  365. #endif
  366. #ifndef JUCE_INCLUDE_FLAC_CODE
  367. #define JUCE_INCLUDE_FLAC_CODE 1
  368. #endif
  369. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  370. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  371. #endif
  372. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  373. #define JUCE_INCLUDE_PNGLIB_CODE 1
  374. #endif
  375. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  376. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  377. #endif
  378. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check for certain objects when
  379. the app terminates. See the LeakedObjectDetector class and the JUCE_LEAK_DETECTOR
  380. macro for more details about enabling leak checking for specific classes.
  381. */
  382. #if JUCE_DEBUG && ! defined (JUCE_CHECK_MEMORY_LEAKS)
  383. #define JUCE_CHECK_MEMORY_LEAKS 1
  384. #endif
  385. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  386. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  387. are passed to the JUCEApplication::unhandledException() callback for logging.
  388. */
  389. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  390. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  391. #endif
  392. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  393. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  394. #undef JUCE_QUICKTIME
  395. #define JUCE_QUICKTIME 0
  396. #undef JUCE_OPENGL
  397. #define JUCE_OPENGL 0
  398. #undef JUCE_USE_CDBURNER
  399. #define JUCE_USE_CDBURNER 0
  400. #undef JUCE_USE_CDREADER
  401. #define JUCE_USE_CDREADER 0
  402. #undef JUCE_WEB_BROWSER
  403. #define JUCE_WEB_BROWSER 0
  404. #undef JUCE_PLUGINHOST_AU
  405. #define JUCE_PLUGINHOST_AU 0
  406. #undef JUCE_PLUGINHOST_VST
  407. #define JUCE_PLUGINHOST_VST 0
  408. #endif
  409. #endif
  410. /*** End of inlined file: juce_Config.h ***/
  411. #ifdef JUCE_NAMESPACE
  412. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  413. #define END_JUCE_NAMESPACE }
  414. #else
  415. #define BEGIN_JUCE_NAMESPACE
  416. #define END_JUCE_NAMESPACE
  417. #endif
  418. /*** Start of inlined file: juce_PlatformDefs.h ***/
  419. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  420. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  421. /* This file defines miscellaneous macros for debugging, assertions, etc.
  422. */
  423. #ifdef JUCE_FORCE_DEBUG
  424. #undef JUCE_DEBUG
  425. #if JUCE_FORCE_DEBUG
  426. #define JUCE_DEBUG 1
  427. #endif
  428. #endif
  429. /** This macro defines the C calling convention used as the standard for Juce calls. */
  430. #if JUCE_MSVC
  431. #define JUCE_CALLTYPE __stdcall
  432. #define JUCE_CDECL __cdecl
  433. #else
  434. #define JUCE_CALLTYPE
  435. #define JUCE_CDECL
  436. #endif
  437. // Debugging and assertion macros
  438. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  439. #if JUCE_LOG_ASSERTIONS
  440. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  441. #elif JUCE_DEBUG
  442. #define juce_LogCurrentAssertion std::cerr << "JUCE Assertion failure in " << __FILE__ << ", line " << __LINE__ << std::endl;
  443. #else
  444. #define juce_LogCurrentAssertion
  445. #endif
  446. #if JUCE_MAC || DOXYGEN
  447. /** This will try to break into the debugger if the app is currently being debugged.
  448. If called by an app that's not being debugged, the behaiour isn't defined - it may crash or not, depending
  449. on the platform.
  450. @see jassert()
  451. */
  452. #define juce_breakDebugger { Debugger(); }
  453. #elif JUCE_IOS || JUCE_LINUX || JUCE_ANDROID
  454. #define juce_breakDebugger { kill (0, SIGTRAP); }
  455. #elif JUCE_USE_INTRINSICS
  456. #pragma intrinsic (__debugbreak)
  457. #define juce_breakDebugger { __debugbreak(); }
  458. #elif JUCE_GCC
  459. #define juce_breakDebugger { asm("int $3"); }
  460. #else
  461. #define juce_breakDebugger { __asm int 3 }
  462. #endif
  463. #if JUCE_DEBUG || DOXYGEN
  464. /** Writes a string to the standard error stream.
  465. This is only compiled in a debug build.
  466. @see Logger::outputDebugString
  467. */
  468. #define DBG(dbgtext) { JUCE_NAMESPACE::String tempDbgBuf; tempDbgBuf << dbgtext; JUCE_NAMESPACE::Logger::outputDebugString (tempDbgBuf); }
  469. /** This will always cause an assertion failure.
  470. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled for your build).
  471. @see jassert
  472. */
  473. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  474. /** Platform-independent assertion macro.
  475. This macro gets turned into a no-op when you're building with debugging turned off, so be
  476. careful that the expression you pass to it doesn't perform any actions that are vital for the
  477. correct behaviour of your program!
  478. @see jassertfalse
  479. */
  480. #define jassert(expression) { if (! (expression)) jassertfalse; }
  481. #else
  482. // If debugging is disabled, these dummy debug and assertion macros are used..
  483. #define DBG(dbgtext)
  484. #define jassertfalse { juce_LogCurrentAssertion }
  485. #if JUCE_LOG_ASSERTIONS
  486. #define jassert(expression) { if (! (expression)) jassertfalse; }
  487. #else
  488. #define jassert(a) {}
  489. #endif
  490. #endif
  491. #ifndef DOXYGEN
  492. BEGIN_JUCE_NAMESPACE
  493. template <bool b> struct JuceStaticAssert;
  494. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  495. END_JUCE_NAMESPACE
  496. #endif
  497. /** A compile-time assertion macro.
  498. If the expression parameter is false, the macro will cause a compile error. (The actual error
  499. message that the compiler generates may be completely bizarre and seem to have no relation to
  500. the place where you put the static_assert though!)
  501. */
  502. #define static_jassert(expression) JUCE_NAMESPACE::JuceStaticAssert<expression>::dummy();
  503. /** This is a shorthand macro for declaring stubs for a class's copy constructor and operator=.
  504. For example, instead of
  505. @code
  506. class MyClass
  507. {
  508. etc..
  509. private:
  510. MyClass (const MyClass&);
  511. MyClass& operator= (const MyClass&);
  512. };@endcode
  513. ..you can just write:
  514. @code
  515. class MyClass
  516. {
  517. etc..
  518. private:
  519. JUCE_DECLARE_NON_COPYABLE (MyClass);
  520. };@endcode
  521. */
  522. #define JUCE_DECLARE_NON_COPYABLE(className) \
  523. className (const className&);\
  524. className& operator= (const className&)
  525. /** This is a shorthand way of writing both a JUCE_DECLARE_NON_COPYABLE and
  526. JUCE_LEAK_DETECTOR macro for a class.
  527. */
  528. #define JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(className) \
  529. JUCE_DECLARE_NON_COPYABLE(className);\
  530. JUCE_LEAK_DETECTOR(className)
  531. #if ! DOXYGEN
  532. #define JUCE_JOIN_MACRO_HELPER(a, b) a ## b
  533. #endif
  534. /** A good old-fashioned C macro concatenation helper.
  535. This combines two items (which may themselves be macros) into a single string,
  536. avoiding the pitfalls of the ## macro operator.
  537. */
  538. #define JUCE_JOIN_MACRO(a, b) JUCE_JOIN_MACRO_HELPER (a, b)
  539. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  540. #define JUCE_TRY try
  541. #define JUCE_CATCH_ALL catch (...) {}
  542. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse; }
  543. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  544. #define JUCE_CATCH_EXCEPTION JUCE_CATCH_ALL
  545. #else
  546. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  547. object so they can be logged by the application if it wants to.
  548. */
  549. #define JUCE_CATCH_EXCEPTION \
  550. catch (const std::exception& e) \
  551. { \
  552. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  553. } \
  554. catch (...) \
  555. { \
  556. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  557. }
  558. #endif
  559. #else
  560. #define JUCE_TRY
  561. #define JUCE_CATCH_EXCEPTION
  562. #define JUCE_CATCH_ALL
  563. #define JUCE_CATCH_ALL_ASSERT
  564. #endif
  565. #if JUCE_DEBUG || DOXYGEN
  566. /** A platform-independent way of forcing an inline function.
  567. Use the syntax: @code
  568. forcedinline void myfunction (int x)
  569. @endcode
  570. */
  571. #define forcedinline inline
  572. #else
  573. #if JUCE_MSVC
  574. #define forcedinline __forceinline
  575. #else
  576. #define forcedinline inline __attribute__((always_inline))
  577. #endif
  578. #endif
  579. #if JUCE_MSVC || DOXYGEN
  580. /** This can be placed before a stack or member variable declaration to tell the compiler
  581. to align it to the specified number of bytes. */
  582. #define JUCE_ALIGN(bytes) __declspec (align (bytes))
  583. #else
  584. #define JUCE_ALIGN(bytes) __attribute__ ((aligned (bytes)))
  585. #endif
  586. // Cross-compiler deprecation macros..
  587. #if DOXYGEN || (JUCE_MSVC && ! JUCE_NO_DEPRECATION_WARNINGS)
  588. /** This can be used to wrap a function which has been deprecated. */
  589. #define JUCE_DEPRECATED(functionDef) __declspec(deprecated) functionDef
  590. #elif JUCE_GCC && ! JUCE_NO_DEPRECATION_WARNINGS
  591. #define JUCE_DEPRECATED(functionDef) functionDef __attribute__ ((deprecated))
  592. #else
  593. #define JUCE_DEPRECATED(functionDef) functionDef
  594. #endif
  595. #if JUCE_ANDROID && ! DOXYGEN
  596. #define JUCE_MODAL_LOOPS_PERMITTED 0
  597. #else
  598. /** Some operating environments don't provide a modal loop mechanism, so this flag can be
  599. used to disable any functions that try to run a modal loop. */
  600. #define JUCE_MODAL_LOOPS_PERMITTED 1
  601. #endif
  602. // Here, we'll check for C++2011 compiler support, and if it's not available, define
  603. // a few workarounds, so that we can still use a few of the newer language features.
  604. #if defined (__GXX_EXPERIMENTAL_CXX0X__) && defined (__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
  605. #define JUCE_COMPILER_SUPPORTS_CXX2011 1
  606. #endif
  607. #if defined (__clang__) && defined (__has_feature)
  608. #if __has_feature (cxx_noexcept) // (NB: do not add this test to the previous line)
  609. #define JUCE_COMPILER_SUPPORTS_CXX2011 1
  610. #endif
  611. #endif
  612. #if defined (_MSC_VER) && _MSC_VER >= 1600
  613. //#define JUCE_COMPILER_SUPPORTS_CXX2011 1
  614. #endif
  615. #if ! (DOXYGEN || JUCE_COMPILER_SUPPORTS_CXX2011)
  616. #define noexcept throw() // for c++98 compilers, we can fake these newer language features.
  617. #define nullptr (0)
  618. #endif
  619. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  620. /*** End of inlined file: juce_PlatformDefs.h ***/
  621. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  622. #if JUCE_MSVC
  623. #if JUCE_VC6
  624. #pragma warning (disable: 4284 4786) // (spurious VC6 warnings)
  625. namespace std // VC6 doesn't have sqrt/sin/cos/tan/abs in std, so declare them here:
  626. {
  627. template <typename Type> Type abs (Type a) { if (a < 0) return -a; return a; }
  628. template <typename Type> Type tan (Type a) { return static_cast<Type> (::tan (static_cast<double> (a))); }
  629. template <typename Type> Type sin (Type a) { return static_cast<Type> (::sin (static_cast<double> (a))); }
  630. template <typename Type> Type cos (Type a) { return static_cast<Type> (::cos (static_cast<double> (a))); }
  631. template <typename Type> Type sqrt (Type a) { return static_cast<Type> (::sqrt (static_cast<double> (a))); }
  632. template <typename Type> Type floor (Type a) { return static_cast<Type> (::floor (static_cast<double> (a))); }
  633. template <typename Type> Type ceil (Type a) { return static_cast<Type> (::ceil (static_cast<double> (a))); }
  634. template <typename Type> Type atan2 (Type a, Type b) { return static_cast<Type> (::atan2 (static_cast<double> (a), static_cast<double> (b))); }
  635. }
  636. #endif
  637. #pragma warning (push)
  638. #pragma warning (disable: 4514 4245 4100)
  639. #endif
  640. #include <cstdlib>
  641. #include <cstdarg>
  642. #include <climits>
  643. #include <limits>
  644. #include <cmath>
  645. #include <cwchar>
  646. #include <stdexcept>
  647. #include <typeinfo>
  648. #include <cstring>
  649. #include <cstdio>
  650. #include <iostream>
  651. #include <vector>
  652. #if JUCE_USE_INTRINSICS
  653. #include <intrin.h>
  654. #endif
  655. #if JUCE_MAC || JUCE_IOS
  656. #include <libkern/OSAtomic.h>
  657. #endif
  658. #if JUCE_LINUX
  659. #include <signal.h>
  660. #if __INTEL_COMPILER
  661. #if __ia64__
  662. #include <ia64intrin.h>
  663. #else
  664. #include <ia32intrin.h>
  665. #endif
  666. #endif
  667. #endif
  668. #if JUCE_MSVC && JUCE_DEBUG
  669. #include <crtdbg.h>
  670. #endif
  671. #if JUCE_MSVC
  672. #include <malloc.h>
  673. #pragma warning (pop)
  674. #if ! JUCE_PUBLIC_INCLUDES
  675. #pragma warning (4: 4511 4512 4100) // (enable some warnings that are turned off in VC8)
  676. #endif
  677. #endif
  678. #if JUCE_ANDROID
  679. #include <sys/atomics.h>
  680. #include <byteswap.h>
  681. #endif
  682. // DLL building settings on Win32
  683. #if JUCE_MSVC
  684. #ifdef JUCE_DLL_BUILD
  685. #define JUCE_API __declspec (dllexport)
  686. #pragma warning (disable: 4251)
  687. #elif defined (JUCE_DLL)
  688. #define JUCE_API __declspec (dllimport)
  689. #pragma warning (disable: 4251)
  690. #endif
  691. #ifdef __INTEL_COMPILER
  692. #pragma warning (disable: 1125) // (virtual override warning)
  693. #endif
  694. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  695. #ifdef JUCE_DLL_BUILD
  696. #define JUCE_API __attribute__ ((visibility("default")))
  697. #endif
  698. #endif
  699. #ifndef JUCE_API
  700. /** This macro is added to all juce public class declarations. */
  701. #define JUCE_API
  702. #endif
  703. /** This macro is added to all juce public function declarations. */
  704. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  705. /** This turns on some non-essential bits of code that should prevent old code from compiling
  706. in cases where method signatures have changed, etc.
  707. */
  708. #if (! defined (JUCE_CATCH_DEPRECATED_CODE_MISUSE)) && JUCE_DEBUG && ! DOXYGEN
  709. #define JUCE_CATCH_DEPRECATED_CODE_MISUSE 1
  710. #endif
  711. // Now include some basics that are needed by most of the Juce classes...
  712. BEGIN_JUCE_NAMESPACE
  713. extern JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger();
  714. #if JUCE_LOG_ASSERTIONS
  715. extern JUCE_API void juce_LogAssertion (const char* filename, int lineNum) noexcept;
  716. #endif
  717. /*** Start of inlined file: juce_Memory.h ***/
  718. #ifndef __JUCE_MEMORY_JUCEHEADER__
  719. #define __JUCE_MEMORY_JUCEHEADER__
  720. /*
  721. This file defines the various juce_malloc(), juce_free() macros that can be used in
  722. preference to the standard calls.
  723. None of this stuff is actually used in the library itself, and will probably be
  724. deprecated at some point in the future, to force everyone to use HeapBlock and other
  725. safer allocation methods.
  726. */
  727. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS && ! DOXYGEN
  728. #ifndef JUCE_DLL
  729. // Win32 debug non-DLL versions..
  730. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  731. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  732. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  733. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  734. #else
  735. // Win32 debug DLL versions..
  736. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  737. // way all juce calls in the DLL and in the host API will all use the same allocator.
  738. extern JUCE_API void* juce_DebugMalloc (int size, const char* file, int line);
  739. extern JUCE_API void* juce_DebugCalloc (int size, const char* file, int line);
  740. extern JUCE_API void* juce_DebugRealloc (void* block, int size, const char* file, int line);
  741. extern JUCE_API void juce_DebugFree (void* block);
  742. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  743. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  744. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  745. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  746. #define JUCE_LEAK_DETECTOR(OwnerClass) public:\
  747. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  748. static void* operator new (size_t, void* p) { return p; } \
  749. static void operator delete (void* p) { juce_free (p); } \
  750. static void operator delete (void*, void*) {}
  751. #endif
  752. #elif defined (JUCE_DLL) && ! DOXYGEN
  753. // Win32 DLL (release) versions..
  754. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  755. // way all juce calls in the DLL and in the host API will all use the same allocator.
  756. extern JUCE_API void* juce_Malloc (int size);
  757. extern JUCE_API void* juce_Calloc (int size);
  758. extern JUCE_API void* juce_Realloc (void* block, int size);
  759. extern JUCE_API void juce_Free (void* block);
  760. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  761. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  762. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  763. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  764. #define JUCE_LEAK_DETECTOR(OwnerClass) public:\
  765. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  766. static void* operator new (size_t, void* p) { return p; } \
  767. static void operator delete (void* p) { juce_free (p); } \
  768. static void operator delete (void*, void*) {}
  769. #else
  770. // Mac, Linux and Win32 (release) versions..
  771. /** This can be used instead of calling malloc directly.
  772. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  773. */
  774. #define juce_malloc(numBytes) malloc (numBytes)
  775. /** This can be used instead of calling calloc directly.
  776. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  777. */
  778. #define juce_calloc(numBytes) calloc (1, numBytes)
  779. /** This can be used instead of calling realloc directly.
  780. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  781. */
  782. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  783. /** This can be used instead of calling free directly.
  784. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  785. */
  786. #define juce_free(location) free (location)
  787. #endif
  788. /** (Deprecated) This was a win32-specific way of checking for object leaks - now please
  789. use the JUCE_LEAK_DETECTOR instead.
  790. */
  791. #ifndef juce_UseDebuggingNewOperator
  792. #define juce_UseDebuggingNewOperator
  793. #endif
  794. #if JUCE_MSVC || DOXYGEN
  795. /** This is a compiler-independent way of declaring a variable as being thread-local.
  796. E.g.
  797. @code
  798. juce_ThreadLocal int myVariable;
  799. @endcode
  800. */
  801. #define juce_ThreadLocal __declspec(thread)
  802. #else
  803. #define juce_ThreadLocal __thread
  804. #endif
  805. #if JUCE_MINGW
  806. /** This allocator is not defined in mingw gcc. */
  807. #define alloca __builtin_alloca
  808. #endif
  809. /** Fills a block of memory with zeros. */
  810. inline void zeromem (void* memory, size_t numBytes) noexcept { memset (memory, 0, numBytes); }
  811. /** Overwrites a structure or object with zeros. */
  812. template <typename Type>
  813. inline void zerostruct (Type& structure) noexcept { memset (&structure, 0, sizeof (structure)); }
  814. /** Delete an object pointer, and sets the pointer to null.
  815. Remember that it's not good c++ practice to use delete directly - always try to use a ScopedPointer
  816. or other automatic lieftime-management system rather than resorting to deleting raw pointers!
  817. */
  818. template <typename Type>
  819. inline void deleteAndZero (Type& pointer) { delete pointer; pointer = nullptr; }
  820. /** A handy function which adds a number of bytes to any type of pointer and returns the result.
  821. This can be useful to avoid casting pointers to a char* and back when you want to move them by
  822. a specific number of bytes,
  823. */
  824. template <typename Type>
  825. inline Type* addBytesToPointer (Type* pointer, int bytes) noexcept { return (Type*) (((char*) pointer) + bytes); }
  826. #endif // __JUCE_MEMORY_JUCEHEADER__
  827. /*** End of inlined file: juce_Memory.h ***/
  828. /*** Start of inlined file: juce_MathsFunctions.h ***/
  829. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  830. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  831. /*
  832. This file sets up some handy mathematical typdefs and functions.
  833. */
  834. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  835. /** A platform-independent 8-bit signed integer type. */
  836. typedef signed char int8;
  837. /** A platform-independent 8-bit unsigned integer type. */
  838. typedef unsigned char uint8;
  839. /** A platform-independent 16-bit signed integer type. */
  840. typedef signed short int16;
  841. /** A platform-independent 16-bit unsigned integer type. */
  842. typedef unsigned short uint16;
  843. /** A platform-independent 32-bit signed integer type. */
  844. typedef signed int int32;
  845. /** A platform-independent 32-bit unsigned integer type. */
  846. typedef unsigned int uint32;
  847. #if JUCE_MSVC
  848. /** A platform-independent 64-bit integer type. */
  849. typedef __int64 int64;
  850. /** A platform-independent 64-bit unsigned integer type. */
  851. typedef unsigned __int64 uint64;
  852. /** A platform-independent macro for writing 64-bit literals, needed because
  853. different compilers have different syntaxes for this.
  854. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  855. GCC, or 0x1000000000 for MSVC.
  856. */
  857. #define literal64bit(longLiteral) ((__int64) longLiteral)
  858. #else
  859. /** A platform-independent 64-bit integer type. */
  860. typedef long long int64;
  861. /** A platform-independent 64-bit unsigned integer type. */
  862. typedef unsigned long long uint64;
  863. /** A platform-independent macro for writing 64-bit literals, needed because
  864. different compilers have different syntaxes for this.
  865. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  866. GCC, or 0x1000000000 for MSVC.
  867. */
  868. #define literal64bit(longLiteral) (longLiteral##LL)
  869. #endif
  870. #if JUCE_64BIT
  871. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  872. typedef int64 pointer_sized_int;
  873. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  874. typedef uint64 pointer_sized_uint;
  875. #elif JUCE_MSVC && ! JUCE_VC6
  876. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  877. typedef _W64 int pointer_sized_int;
  878. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  879. typedef _W64 unsigned int pointer_sized_uint;
  880. #else
  881. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  882. typedef int pointer_sized_int;
  883. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  884. typedef unsigned int pointer_sized_uint;
  885. #endif
  886. // Some indispensible min/max functions
  887. /** Returns the larger of two values. */
  888. template <typename Type>
  889. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  890. /** Returns the larger of three values. */
  891. template <typename Type>
  892. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  893. /** Returns the larger of four values. */
  894. template <typename Type>
  895. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  896. /** Returns the smaller of two values. */
  897. template <typename Type>
  898. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  899. /** Returns the smaller of three values. */
  900. template <typename Type>
  901. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  902. /** Returns the smaller of four values. */
  903. template <typename Type>
  904. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  905. /** Scans an array of values, returning the minimum value that it contains. */
  906. template <typename Type>
  907. const Type findMinimum (const Type* data, int numValues)
  908. {
  909. if (numValues <= 0)
  910. return Type();
  911. Type result (*data++);
  912. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  913. {
  914. const Type& v = *data++;
  915. if (v < result) result = v;
  916. }
  917. return result;
  918. }
  919. /** Scans an array of values, returning the minimum value that it contains. */
  920. template <typename Type>
  921. const Type findMaximum (const Type* values, int numValues)
  922. {
  923. if (numValues <= 0)
  924. return Type();
  925. Type result (*values++);
  926. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  927. {
  928. const Type& v = *values++;
  929. if (result > v) result = v;
  930. }
  931. return result;
  932. }
  933. /** Scans an array of values, returning the minimum and maximum values that it contains. */
  934. template <typename Type>
  935. void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
  936. {
  937. if (numValues <= 0)
  938. {
  939. lowest = Type();
  940. highest = Type();
  941. }
  942. else
  943. {
  944. Type mn (*values++);
  945. Type mx (mn);
  946. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  947. {
  948. const Type& v = *values++;
  949. if (mx < v) mx = v;
  950. if (v < mn) mn = v;
  951. }
  952. lowest = mn;
  953. highest = mx;
  954. }
  955. }
  956. /** Constrains a value to keep it within a given range.
  957. This will check that the specified value lies between the lower and upper bounds
  958. specified, and if not, will return the nearest value that would be in-range. Effectively,
  959. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  960. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  961. the results will be unpredictable.
  962. @param lowerLimit the minimum value to return
  963. @param upperLimit the maximum value to return
  964. @param valueToConstrain the value to try to return
  965. @returns the closest value to valueToConstrain which lies between lowerLimit
  966. and upperLimit (inclusive)
  967. @see jlimit0To, jmin, jmax
  968. */
  969. template <typename Type>
  970. inline Type jlimit (const Type lowerLimit,
  971. const Type upperLimit,
  972. const Type valueToConstrain) noexcept
  973. {
  974. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  975. return (valueToConstrain < lowerLimit) ? lowerLimit
  976. : ((upperLimit < valueToConstrain) ? upperLimit
  977. : valueToConstrain);
  978. }
  979. /** Returns true if a value is at least zero, and also below a specified upper limit.
  980. This is basically a quicker way to write:
  981. @code valueToTest >= 0 && valueToTest < upperLimit
  982. @endcode
  983. */
  984. template <typename Type>
  985. inline bool isPositiveAndBelow (Type valueToTest, Type upperLimit) noexcept
  986. {
  987. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  988. return Type() <= valueToTest && valueToTest < upperLimit;
  989. }
  990. #if ! JUCE_VC6
  991. template <>
  992. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) noexcept
  993. {
  994. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  995. return static_cast <unsigned int> (valueToTest) < static_cast <unsigned int> (upperLimit);
  996. }
  997. #endif
  998. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  999. This is basically a quicker way to write:
  1000. @code valueToTest >= 0 && valueToTest <= upperLimit
  1001. @endcode
  1002. */
  1003. template <typename Type>
  1004. inline bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) noexcept
  1005. {
  1006. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  1007. return Type() <= valueToTest && valueToTest <= upperLimit;
  1008. }
  1009. #if ! JUCE_VC6
  1010. template <>
  1011. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) noexcept
  1012. {
  1013. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  1014. return static_cast <unsigned int> (valueToTest) <= static_cast <unsigned int> (upperLimit);
  1015. }
  1016. #endif
  1017. /** Handy function to swap two values. */
  1018. template <typename Type>
  1019. inline void swapVariables (Type& variable1, Type& variable2)
  1020. {
  1021. std::swap (variable1, variable2);
  1022. }
  1023. #if JUCE_VC6
  1024. #define numElementsInArray(X) (sizeof((X)) / sizeof(0[X]))
  1025. #else
  1026. /** Handy function for getting the number of elements in a simple const C array.
  1027. E.g.
  1028. @code
  1029. static int myArray[] = { 1, 2, 3 };
  1030. int numElements = numElementsInArray (myArray) // returns 3
  1031. @endcode
  1032. */
  1033. template <typename Type, int N>
  1034. inline int numElementsInArray (Type (&array)[N])
  1035. {
  1036. (void) array; // (required to avoid a spurious warning in MS compilers)
  1037. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  1038. return N;
  1039. }
  1040. #endif
  1041. // Some useful maths functions that aren't always present with all compilers and build settings.
  1042. /** Using juce_hypot is easier than dealing with the different types of hypot function
  1043. that are provided by the various platforms and compilers. */
  1044. template <typename Type>
  1045. inline Type juce_hypot (Type a, Type b) noexcept
  1046. {
  1047. #if JUCE_WINDOWS
  1048. return static_cast <Type> (_hypot (a, b));
  1049. #else
  1050. return static_cast <Type> (hypot (a, b));
  1051. #endif
  1052. }
  1053. /** 64-bit abs function. */
  1054. inline int64 abs64 (const int64 n) noexcept
  1055. {
  1056. return (n >= 0) ? n : -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) noexcept
  1061. {
  1062. return sizeof (Type) == 1 ? (Type) -(signed char) n
  1063. : (sizeof (Type) == 2 ? (Type) -(short) n
  1064. : (sizeof (Type) == 4 ? (Type) -(int) n
  1065. : ((Type) -(int64) n)));
  1066. }
  1067. /** This templated negate function will negate pointers as well as integers */
  1068. template <typename Type>
  1069. inline Type* juce_negate (Type* n) noexcept
  1070. {
  1071. return (Type*) -(pointer_sized_int) n;
  1072. }
  1073. /** A predefined value for Pi, at double-precision.
  1074. @see float_Pi
  1075. */
  1076. const double double_Pi = 3.1415926535897932384626433832795;
  1077. /** A predefined value for Pi, at sngle-precision.
  1078. @see double_Pi
  1079. */
  1080. const float float_Pi = 3.14159265358979323846f;
  1081. /** The isfinite() method seems to vary between platforms, so this is a
  1082. platform-independent function for it.
  1083. */
  1084. template <typename FloatingPointType>
  1085. inline bool juce_isfinite (FloatingPointType value)
  1086. {
  1087. #if JUCE_WINDOWS
  1088. return _finite (value);
  1089. #elif JUCE_ANDROID
  1090. return isfinite (value);
  1091. #else
  1092. return std::isfinite (value);
  1093. #endif
  1094. }
  1095. /** Fast floating-point-to-integer conversion.
  1096. This is faster than using the normal c++ cast to convert a float to an int, and
  1097. it will round the value to the nearest integer, rather than rounding it down
  1098. like the normal cast does.
  1099. Note that this routine gets its speed at the expense of some accuracy, and when
  1100. rounding values whose floating point component is exactly 0.5, odd numbers and
  1101. even numbers will be rounded up or down differently.
  1102. */
  1103. template <typename FloatType>
  1104. inline int roundToInt (const FloatType value) noexcept
  1105. {
  1106. union { int asInt[2]; double asDouble; } n;
  1107. n.asDouble = ((double) value) + 6755399441055744.0;
  1108. #if JUCE_BIG_ENDIAN
  1109. return n.asInt [1];
  1110. #else
  1111. return n.asInt [0];
  1112. #endif
  1113. }
  1114. /** Fast floating-point-to-integer conversion.
  1115. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  1116. fine for values above zero, but negative numbers are rounded the wrong way.
  1117. */
  1118. inline int roundToIntAccurate (const double value) noexcept
  1119. {
  1120. return roundToInt (value + 1.5e-8);
  1121. }
  1122. /** Fast floating-point-to-integer conversion.
  1123. This is faster than using the normal c++ cast to convert a double to an int, and
  1124. it will round the value to the nearest integer, rather than rounding it down
  1125. like the normal cast does.
  1126. Note that this routine gets its speed at the expense of some accuracy, and when
  1127. rounding values whose floating point component is exactly 0.5, odd numbers and
  1128. even numbers will be rounded up or down differently. For a more accurate conversion,
  1129. see roundDoubleToIntAccurate().
  1130. */
  1131. inline int roundDoubleToInt (const double value) noexcept
  1132. {
  1133. return roundToInt (value);
  1134. }
  1135. /** Fast floating-point-to-integer conversion.
  1136. This is faster than using the normal c++ cast to convert a float to an int, and
  1137. it will round the value to the nearest integer, rather than rounding it down
  1138. like the normal cast does.
  1139. Note that this routine gets its speed at the expense of some accuracy, and when
  1140. rounding values whose floating point component is exactly 0.5, odd numbers and
  1141. even numbers will be rounded up or down differently.
  1142. */
  1143. inline int roundFloatToInt (const float value) noexcept
  1144. {
  1145. return roundToInt (value);
  1146. }
  1147. /** This namespace contains a few template classes for helping work out class type variations.
  1148. */
  1149. namespace TypeHelpers
  1150. {
  1151. #if JUCE_VC8_OR_EARLIER
  1152. #define PARAMETER_TYPE(type) const type&
  1153. #else
  1154. /** The ParameterType struct is used to find the best type to use when passing some kind
  1155. of object as a parameter.
  1156. Of course, this is only likely to be useful in certain esoteric template situations.
  1157. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  1158. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  1159. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  1160. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  1161. pass-by-value, but passing objects as a const reference, to avoid copying.
  1162. */
  1163. template <typename Type> struct ParameterType { typedef const Type& type; };
  1164. #if ! DOXYGEN
  1165. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  1166. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  1167. template <> struct ParameterType <char> { typedef char type; };
  1168. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  1169. template <> struct ParameterType <short> { typedef short type; };
  1170. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  1171. template <> struct ParameterType <int> { typedef int type; };
  1172. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  1173. template <> struct ParameterType <long> { typedef long type; };
  1174. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  1175. template <> struct ParameterType <int64> { typedef int64 type; };
  1176. template <> struct ParameterType <uint64> { typedef uint64 type; };
  1177. template <> struct ParameterType <bool> { typedef bool type; };
  1178. template <> struct ParameterType <float> { typedef float type; };
  1179. template <> struct ParameterType <double> { typedef double type; };
  1180. #endif
  1181. /** A helpful macro to simplify the use of the ParameterType template.
  1182. @see ParameterType
  1183. */
  1184. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  1185. #endif
  1186. }
  1187. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1188. /*** End of inlined file: juce_MathsFunctions.h ***/
  1189. /*** Start of inlined file: juce_ByteOrder.h ***/
  1190. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  1191. #define __JUCE_BYTEORDER_JUCEHEADER__
  1192. /** Contains static methods for converting the byte order between different
  1193. endiannesses.
  1194. */
  1195. class JUCE_API ByteOrder
  1196. {
  1197. public:
  1198. /** Swaps the upper and lower bytes of a 16-bit integer. */
  1199. static uint16 swap (uint16 value);
  1200. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  1201. static uint32 swap (uint32 value);
  1202. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  1203. static uint64 swap (uint64 value);
  1204. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  1205. static uint16 swapIfBigEndian (uint16 value);
  1206. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  1207. static uint32 swapIfBigEndian (uint32 value);
  1208. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  1209. static uint64 swapIfBigEndian (uint64 value);
  1210. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  1211. static uint16 swapIfLittleEndian (uint16 value);
  1212. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1213. static uint32 swapIfLittleEndian (uint32 value);
  1214. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1215. static uint64 swapIfLittleEndian (uint64 value);
  1216. /** Turns 4 bytes into a little-endian integer. */
  1217. static uint32 littleEndianInt (const void* bytes);
  1218. /** Turns 2 bytes into a little-endian integer. */
  1219. static uint16 littleEndianShort (const void* bytes);
  1220. /** Turns 4 bytes into a big-endian integer. */
  1221. static uint32 bigEndianInt (const void* bytes);
  1222. /** Turns 2 bytes into a big-endian integer. */
  1223. static uint16 bigEndianShort (const void* bytes);
  1224. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1225. static int littleEndian24Bit (const char* bytes);
  1226. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1227. static int bigEndian24Bit (const char* bytes);
  1228. /** Copies a 24-bit number to 3 little-endian bytes. */
  1229. static void littleEndian24BitToChars (int value, char* destBytes);
  1230. /** Copies a 24-bit number to 3 big-endian bytes. */
  1231. static void bigEndian24BitToChars (int value, char* destBytes);
  1232. /** Returns true if the current CPU is big-endian. */
  1233. static bool isBigEndian();
  1234. private:
  1235. ByteOrder();
  1236. JUCE_DECLARE_NON_COPYABLE (ByteOrder);
  1237. };
  1238. #if JUCE_USE_INTRINSICS
  1239. #pragma intrinsic (_byteswap_ulong)
  1240. #endif
  1241. inline uint16 ByteOrder::swap (uint16 n)
  1242. {
  1243. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1244. return static_cast <uint16> (_byteswap_ushort (n));
  1245. #else
  1246. return static_cast <uint16> ((n << 8) | (n >> 8));
  1247. #endif
  1248. }
  1249. inline uint32 ByteOrder::swap (uint32 n)
  1250. {
  1251. #if JUCE_MAC || JUCE_IOS
  1252. return OSSwapInt32 (n);
  1253. #elif JUCE_GCC && JUCE_INTEL
  1254. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1255. return n;
  1256. #elif JUCE_USE_INTRINSICS
  1257. return _byteswap_ulong (n);
  1258. #elif JUCE_MSVC
  1259. __asm {
  1260. mov eax, n
  1261. bswap eax
  1262. mov n, eax
  1263. }
  1264. return n;
  1265. #elif JUCE_ANDROID
  1266. return bswap_32 (n);
  1267. #else
  1268. return (n << 24) | (n >> 24) | ((n & 0xff00) << 8) | ((n & 0xff0000) >> 8);
  1269. #endif
  1270. }
  1271. inline uint64 ByteOrder::swap (uint64 value)
  1272. {
  1273. #if JUCE_MAC || JUCE_IOS
  1274. return OSSwapInt64 (value);
  1275. #elif JUCE_USE_INTRINSICS
  1276. return _byteswap_uint64 (value);
  1277. #else
  1278. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1279. #endif
  1280. }
  1281. #if JUCE_LITTLE_ENDIAN
  1282. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1283. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1284. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1285. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1286. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1287. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1288. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1289. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1290. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1291. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1292. inline bool ByteOrder::isBigEndian() { return false; }
  1293. #else
  1294. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1295. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1296. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1297. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1298. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1299. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1300. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1301. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1302. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1303. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1304. inline bool ByteOrder::isBigEndian() { return true; }
  1305. #endif
  1306. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1307. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1308. 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); }
  1309. 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); }
  1310. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1311. /*** End of inlined file: juce_ByteOrder.h ***/
  1312. /*** Start of inlined file: juce_Logger.h ***/
  1313. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1314. #define __JUCE_LOGGER_JUCEHEADER__
  1315. /*** Start of inlined file: juce_String.h ***/
  1316. #ifndef __JUCE_STRING_JUCEHEADER__
  1317. #define __JUCE_STRING_JUCEHEADER__
  1318. /*** Start of inlined file: juce_CharacterFunctions.h ***/
  1319. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1320. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1321. #if JUCE_WINDOWS && ! DOXYGEN
  1322. #define JUCE_NATIVE_WCHAR_IS_UTF8 0
  1323. #define JUCE_NATIVE_WCHAR_IS_UTF16 1
  1324. #define JUCE_NATIVE_WCHAR_IS_UTF32 0
  1325. #else
  1326. /** This macro will be set to 1 if the compiler's native wchar_t is an 8-bit type. */
  1327. #define JUCE_NATIVE_WCHAR_IS_UTF8 0
  1328. /** This macro will be set to 1 if the compiler's native wchar_t is a 16-bit type. */
  1329. #define JUCE_NATIVE_WCHAR_IS_UTF16 0
  1330. /** This macro will be set to 1 if the compiler's native wchar_t is a 32-bit type. */
  1331. #define JUCE_NATIVE_WCHAR_IS_UTF32 1
  1332. #endif
  1333. #if JUCE_NATIVE_WCHAR_IS_UTF32 || DOXYGEN
  1334. /** A platform-independent 32-bit unicode character type. */
  1335. typedef wchar_t juce_wchar;
  1336. #else
  1337. typedef uint32 juce_wchar;
  1338. #endif
  1339. /** This macro is deprecated, but preserved for compatibility with old code.*/
  1340. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1341. #if ! JUCE_DONT_DEFINE_MACROS
  1342. /** The 'T' macro is an alternative for using the "L" prefix in front of a string literal.
  1343. This macro is deprectated, but kept here for compatibility with old code. The best (i.e.
  1344. most portable) way to encode your string literals is just as standard 8-bit strings, but
  1345. using escaped utf-8 character codes for extended characters.
  1346. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1347. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1348. the juce/src directory) to avoid defining this macro. See the comments in
  1349. juce_withoutMacros.h for more info.
  1350. */
  1351. #define T(stringLiteral) JUCE_T(stringLiteral)
  1352. #endif
  1353. #undef max
  1354. #undef min
  1355. /**
  1356. A set of methods for manipulating characters and character strings.
  1357. These are defined as wrappers around the basic C string handlers, to provide
  1358. a clean, cross-platform layer, (because various platforms differ in the
  1359. range of C library calls that they provide).
  1360. @see String
  1361. */
  1362. class JUCE_API CharacterFunctions
  1363. {
  1364. public:
  1365. static juce_wchar toUpperCase (juce_wchar character) noexcept;
  1366. static juce_wchar toLowerCase (juce_wchar character) noexcept;
  1367. static bool isUpperCase (juce_wchar character) noexcept;
  1368. static bool isLowerCase (juce_wchar character) noexcept;
  1369. static bool isWhitespace (char character) noexcept;
  1370. static bool isWhitespace (juce_wchar character) noexcept;
  1371. static bool isDigit (char character) noexcept;
  1372. static bool isDigit (juce_wchar character) noexcept;
  1373. static bool isLetter (char character) noexcept;
  1374. static bool isLetter (juce_wchar character) noexcept;
  1375. static bool isLetterOrDigit (char character) noexcept;
  1376. static bool isLetterOrDigit (juce_wchar character) noexcept;
  1377. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legal hex digit. */
  1378. static int getHexDigitValue (juce_wchar digit) noexcept;
  1379. template <typename CharPointerType>
  1380. static double readDoubleValue (CharPointerType& text) noexcept
  1381. {
  1382. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  1383. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  1384. int exponent = 0, decPointIndex = 0, digit = 0;
  1385. int lastDigit = 0, numSignificantDigits = 0;
  1386. bool isNegative = false, digitsFound = false;
  1387. const int maxSignificantDigits = 15 + 2;
  1388. text = text.findEndOfWhitespace();
  1389. juce_wchar c = *text;
  1390. switch (c)
  1391. {
  1392. case '-': isNegative = true; // fall-through..
  1393. case '+': c = *++text;
  1394. }
  1395. switch (c)
  1396. {
  1397. case 'n':
  1398. case 'N':
  1399. if ((text[1] == 'a' || text[1] == 'A') && (text[2] == 'n' || text[2] == 'N'))
  1400. return std::numeric_limits<double>::quiet_NaN();
  1401. break;
  1402. case 'i':
  1403. case 'I':
  1404. if ((text[1] == 'n' || text[1] == 'N') && (text[2] == 'f' || text[2] == 'F'))
  1405. return std::numeric_limits<double>::infinity();
  1406. break;
  1407. }
  1408. for (;;)
  1409. {
  1410. if (text.isDigit())
  1411. {
  1412. lastDigit = digit;
  1413. digit = text.getAndAdvance() - '0';
  1414. digitsFound = true;
  1415. if (decPointIndex != 0)
  1416. exponentAdjustment[1]++;
  1417. if (numSignificantDigits == 0 && digit == 0)
  1418. continue;
  1419. if (++numSignificantDigits > maxSignificantDigits)
  1420. {
  1421. if (digit > 5)
  1422. ++accumulator [decPointIndex];
  1423. else if (digit == 5 && (lastDigit & 1) != 0)
  1424. ++accumulator [decPointIndex];
  1425. if (decPointIndex > 0)
  1426. exponentAdjustment[1]--;
  1427. else
  1428. exponentAdjustment[0]++;
  1429. while (text.isDigit())
  1430. {
  1431. ++text;
  1432. if (decPointIndex == 0)
  1433. exponentAdjustment[0]++;
  1434. }
  1435. }
  1436. else
  1437. {
  1438. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  1439. if (accumulator [decPointIndex] > maxAccumulatorValue)
  1440. {
  1441. result [decPointIndex] = mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  1442. + accumulator [decPointIndex];
  1443. accumulator [decPointIndex] = 0;
  1444. exponentAccumulator [decPointIndex] = 0;
  1445. }
  1446. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  1447. exponentAccumulator [decPointIndex]++;
  1448. }
  1449. }
  1450. else if (decPointIndex == 0 && *text == '.')
  1451. {
  1452. ++text;
  1453. decPointIndex = 1;
  1454. if (numSignificantDigits > maxSignificantDigits)
  1455. {
  1456. while (text.isDigit())
  1457. ++text;
  1458. break;
  1459. }
  1460. }
  1461. else
  1462. {
  1463. break;
  1464. }
  1465. }
  1466. result[0] = mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  1467. if (decPointIndex != 0)
  1468. result[1] = mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  1469. c = *text;
  1470. if ((c == 'e' || c == 'E') && digitsFound)
  1471. {
  1472. bool negativeExponent = false;
  1473. switch (*++text)
  1474. {
  1475. case '-': negativeExponent = true; // fall-through..
  1476. case '+': ++text;
  1477. }
  1478. while (text.isDigit())
  1479. exponent = (exponent * 10) + (text.getAndAdvance() - '0');
  1480. if (negativeExponent)
  1481. exponent = -exponent;
  1482. }
  1483. double r = mulexp10 (result[0], exponent + exponentAdjustment[0]);
  1484. if (decPointIndex != 0)
  1485. r += mulexp10 (result[1], exponent - exponentAdjustment[1]);
  1486. return isNegative ? -r : r;
  1487. }
  1488. template <typename CharPointerType>
  1489. static double getDoubleValue (const CharPointerType& text) noexcept
  1490. {
  1491. CharPointerType t (text);
  1492. return readDoubleValue (t);
  1493. }
  1494. template <typename IntType, typename CharPointerType>
  1495. static IntType getIntValue (const CharPointerType& text) noexcept
  1496. {
  1497. IntType v = 0;
  1498. CharPointerType s (text.findEndOfWhitespace());
  1499. const bool isNeg = *s == '-';
  1500. if (isNeg)
  1501. ++s;
  1502. for (;;)
  1503. {
  1504. const juce_wchar c = s.getAndAdvance();
  1505. if (c >= '0' && c <= '9')
  1506. v = v * 10 + (IntType) (c - '0');
  1507. else
  1508. break;
  1509. }
  1510. return isNeg ? -v : v;
  1511. }
  1512. template <typename CharPointerType>
  1513. static size_t lengthUpTo (CharPointerType text, const size_t maxCharsToCount) noexcept
  1514. {
  1515. size_t len = 0;
  1516. while (len < maxCharsToCount && text.getAndAdvance() != 0)
  1517. ++len;
  1518. return len;
  1519. }
  1520. template <typename CharPointerType>
  1521. static size_t lengthUpTo (CharPointerType start, const CharPointerType& end) noexcept
  1522. {
  1523. size_t len = 0;
  1524. while (start < end && start.getAndAdvance() != 0)
  1525. ++len;
  1526. return len;
  1527. }
  1528. template <typename DestCharPointerType, typename SrcCharPointerType>
  1529. static void copyAll (DestCharPointerType& dest, SrcCharPointerType src) noexcept
  1530. {
  1531. for (;;)
  1532. {
  1533. const juce_wchar c = src.getAndAdvance();
  1534. if (c == 0)
  1535. break;
  1536. dest.write (c);
  1537. }
  1538. dest.writeNull();
  1539. }
  1540. template <typename DestCharPointerType, typename SrcCharPointerType>
  1541. static int copyWithDestByteLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxBytes) noexcept
  1542. {
  1543. int numBytesDone = 0;
  1544. maxBytes -= sizeof (typename DestCharPointerType::CharType); // (allow for a terminating null)
  1545. for (;;)
  1546. {
  1547. const juce_wchar c = src.getAndAdvance();
  1548. const int bytesNeeded = (int) DestCharPointerType::getBytesRequiredFor (c);
  1549. maxBytes -= bytesNeeded;
  1550. if (c == 0 || maxBytes < 0)
  1551. break;
  1552. numBytesDone += bytesNeeded;
  1553. dest.write (c);
  1554. }
  1555. dest.writeNull();
  1556. return numBytesDone;
  1557. }
  1558. template <typename DestCharPointerType, typename SrcCharPointerType>
  1559. static void copyWithCharLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxChars) noexcept
  1560. {
  1561. while (--maxChars > 0)
  1562. {
  1563. const juce_wchar c = src.getAndAdvance();
  1564. if (c == 0)
  1565. break;
  1566. dest.write (c);
  1567. }
  1568. dest.writeNull();
  1569. }
  1570. template <typename CharPointerType1, typename CharPointerType2>
  1571. static int compare (CharPointerType1 s1, CharPointerType2 s2) noexcept
  1572. {
  1573. for (;;)
  1574. {
  1575. const int c1 = (int) s1.getAndAdvance();
  1576. const int c2 = (int) s2.getAndAdvance();
  1577. const int diff = c1 - c2;
  1578. if (diff != 0)
  1579. return diff < 0 ? -1 : 1;
  1580. else if (c1 == 0)
  1581. break;
  1582. }
  1583. return 0;
  1584. }
  1585. template <typename CharPointerType1, typename CharPointerType2>
  1586. static int compareUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) noexcept
  1587. {
  1588. while (--maxChars >= 0)
  1589. {
  1590. const int c1 = (int) s1.getAndAdvance();
  1591. const int c2 = (int) s2.getAndAdvance();
  1592. const int diff = c1 - c2;
  1593. if (diff != 0)
  1594. return diff < 0 ? -1 : 1;
  1595. else if (c1 == 0)
  1596. break;
  1597. }
  1598. return 0;
  1599. }
  1600. template <typename CharPointerType1, typename CharPointerType2>
  1601. static int compareIgnoreCase (CharPointerType1 s1, CharPointerType2 s2) noexcept
  1602. {
  1603. for (;;)
  1604. {
  1605. int c1 = s1.toUpperCase();
  1606. int c2 = s2.toUpperCase();
  1607. ++s1;
  1608. ++s2;
  1609. const int diff = c1 - c2;
  1610. if (diff != 0)
  1611. return diff < 0 ? -1 : 1;
  1612. else if (c1 == 0)
  1613. break;
  1614. }
  1615. return 0;
  1616. }
  1617. template <typename CharPointerType1, typename CharPointerType2>
  1618. static int compareIgnoreCaseUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) noexcept
  1619. {
  1620. while (--maxChars >= 0)
  1621. {
  1622. int c1 = s1.toUpperCase();
  1623. int c2 = s2.toUpperCase();
  1624. ++s1;
  1625. ++s2;
  1626. const int diff = c1 - c2;
  1627. if (diff != 0)
  1628. return diff < 0 ? -1 : 1;
  1629. else if (c1 == 0)
  1630. break;
  1631. }
  1632. return 0;
  1633. }
  1634. template <typename CharPointerType1, typename CharPointerType2>
  1635. static int indexOf (CharPointerType1 haystack, const CharPointerType2& needle) noexcept
  1636. {
  1637. int index = 0;
  1638. const int needleLength = (int) needle.length();
  1639. for (;;)
  1640. {
  1641. if (haystack.compareUpTo (needle, needleLength) == 0)
  1642. return index;
  1643. if (haystack.getAndAdvance() == 0)
  1644. return -1;
  1645. ++index;
  1646. }
  1647. }
  1648. template <typename CharPointerType1, typename CharPointerType2>
  1649. static int indexOfIgnoreCase (CharPointerType1 haystack, const CharPointerType2& needle) noexcept
  1650. {
  1651. int index = 0;
  1652. const int needleLength = (int) needle.length();
  1653. for (;;)
  1654. {
  1655. if (haystack.compareIgnoreCaseUpTo (needle, needleLength) == 0)
  1656. return index;
  1657. if (haystack.getAndAdvance() == 0)
  1658. return -1;
  1659. ++index;
  1660. }
  1661. }
  1662. template <typename Type>
  1663. static int indexOfChar (Type text, const juce_wchar charToFind) noexcept
  1664. {
  1665. int i = 0;
  1666. while (! text.isEmpty())
  1667. {
  1668. if (text.getAndAdvance() == charToFind)
  1669. return i;
  1670. ++i;
  1671. }
  1672. return -1;
  1673. }
  1674. template <typename Type>
  1675. static int indexOfCharIgnoreCase (Type text, juce_wchar charToFind) noexcept
  1676. {
  1677. charToFind = CharacterFunctions::toLowerCase (charToFind);
  1678. int i = 0;
  1679. while (! text.isEmpty())
  1680. {
  1681. if (text.toLowerCase() == charToFind)
  1682. return i;
  1683. ++text;
  1684. ++i;
  1685. }
  1686. return -1;
  1687. }
  1688. template <typename Type>
  1689. static Type findEndOfWhitespace (const Type& text) noexcept
  1690. {
  1691. Type p (text);
  1692. while (p.isWhitespace())
  1693. ++p;
  1694. return p;
  1695. }
  1696. template <typename Type>
  1697. static Type findEndOfToken (const Type& text, const Type& breakCharacters, const Type& quoteCharacters)
  1698. {
  1699. Type t (text);
  1700. juce_wchar currentQuoteChar = 0;
  1701. while (! t.isEmpty())
  1702. {
  1703. const juce_wchar c = t.getAndAdvance();
  1704. if (currentQuoteChar == 0 && breakCharacters.indexOf (c) >= 0)
  1705. {
  1706. --t;
  1707. break;
  1708. }
  1709. if (quoteCharacters.indexOf (c) >= 0)
  1710. {
  1711. if (currentQuoteChar == 0)
  1712. currentQuoteChar = c;
  1713. else if (currentQuoteChar == c)
  1714. currentQuoteChar = 0;
  1715. }
  1716. }
  1717. return t;
  1718. }
  1719. private:
  1720. static double mulexp10 (const double value, int exponent) noexcept;
  1721. };
  1722. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1723. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1724. #ifndef JUCE_STRING_UTF_TYPE
  1725. #define JUCE_STRING_UTF_TYPE 8
  1726. #endif
  1727. #if JUCE_MSVC
  1728. #pragma warning (push)
  1729. #pragma warning (disable: 4514 4996)
  1730. #endif
  1731. /*** Start of inlined file: juce_Atomic.h ***/
  1732. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1733. #define __JUCE_ATOMIC_JUCEHEADER__
  1734. /**
  1735. Simple class to hold a primitive value and perform atomic operations on it.
  1736. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  1737. There are methods to perform most of the basic atomic operations.
  1738. */
  1739. template <typename Type>
  1740. class Atomic
  1741. {
  1742. public:
  1743. /** Creates a new value, initialised to zero. */
  1744. inline Atomic() noexcept
  1745. : value (0)
  1746. {
  1747. }
  1748. /** Creates a new value, with a given initial value. */
  1749. inline Atomic (const Type initialValue) noexcept
  1750. : value (initialValue)
  1751. {
  1752. }
  1753. /** Copies another value (atomically). */
  1754. inline Atomic (const Atomic& other) noexcept
  1755. : value (other.get())
  1756. {
  1757. }
  1758. /** Destructor. */
  1759. inline ~Atomic() noexcept
  1760. {
  1761. // This class can only be used for types which are 32 or 64 bits in size.
  1762. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  1763. }
  1764. /** Atomically reads and returns the current value. */
  1765. Type get() const noexcept;
  1766. /** Copies another value onto this one (atomically). */
  1767. inline Atomic& operator= (const Atomic& other) noexcept { exchange (other.get()); return *this; }
  1768. /** Copies another value onto this one (atomically). */
  1769. inline Atomic& operator= (const Type newValue) noexcept { exchange (newValue); return *this; }
  1770. /** Atomically sets the current value. */
  1771. void set (Type newValue) noexcept { exchange (newValue); }
  1772. /** Atomically sets the current value, returning the value that was replaced. */
  1773. Type exchange (Type value) noexcept;
  1774. /** Atomically adds a number to this value, returning the new value. */
  1775. Type operator+= (Type amountToAdd) noexcept;
  1776. /** Atomically subtracts a number from this value, returning the new value. */
  1777. Type operator-= (Type amountToSubtract) noexcept;
  1778. /** Atomically increments this value, returning the new value. */
  1779. Type operator++() noexcept;
  1780. /** Atomically decrements this value, returning the new value. */
  1781. Type operator--() noexcept;
  1782. /** Atomically compares this value with a target value, and if it is equal, sets
  1783. this to be equal to a new value.
  1784. This operation is the atomic equivalent of doing this:
  1785. @code
  1786. bool compareAndSetBool (Type newValue, Type valueToCompare)
  1787. {
  1788. if (get() == valueToCompare)
  1789. {
  1790. set (newValue);
  1791. return true;
  1792. }
  1793. return false;
  1794. }
  1795. @endcode
  1796. @returns true if the comparison was true and the value was replaced; false if
  1797. the comparison failed and the value was left unchanged.
  1798. @see compareAndSetValue
  1799. */
  1800. bool compareAndSetBool (Type newValue, Type valueToCompare) noexcept;
  1801. /** Atomically compares this value with a target value, and if it is equal, sets
  1802. this to be equal to a new value.
  1803. This operation is the atomic equivalent of doing this:
  1804. @code
  1805. Type compareAndSetValue (Type newValue, Type valueToCompare)
  1806. {
  1807. Type oldValue = get();
  1808. if (oldValue == valueToCompare)
  1809. set (newValue);
  1810. return oldValue;
  1811. }
  1812. @endcode
  1813. @returns the old value before it was changed.
  1814. @see compareAndSetBool
  1815. */
  1816. Type compareAndSetValue (Type newValue, Type valueToCompare) noexcept;
  1817. /** Implements a memory read/write barrier. */
  1818. static void memoryBarrier() noexcept;
  1819. #if JUCE_64BIT
  1820. JUCE_ALIGN (8)
  1821. #else
  1822. JUCE_ALIGN (4)
  1823. #endif
  1824. /** The raw value that this class operates on.
  1825. This is exposed publically in case you need to manipulate it directly
  1826. for performance reasons.
  1827. */
  1828. volatile Type value;
  1829. private:
  1830. static inline Type castFrom32Bit (int32 value) noexcept { return *(Type*) &value; }
  1831. static inline Type castFrom64Bit (int64 value) noexcept { return *(Type*) &value; }
  1832. static inline int32 castTo32Bit (Type value) noexcept { return *(int32*) &value; }
  1833. static inline int64 castTo64Bit (Type value) noexcept { return *(int64*) &value; }
  1834. Type operator++ (int); // better to just use pre-increment with atomics..
  1835. Type operator-- (int);
  1836. };
  1837. /*
  1838. The following code is in the header so that the atomics can be inlined where possible...
  1839. */
  1840. #if (JUCE_IOS && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  1841. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  1842. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  1843. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1844. #define JUCE_MAC_ATOMICS_VOLATILE
  1845. #else
  1846. #define JUCE_MAC_ATOMICS_VOLATILE volatile
  1847. #endif
  1848. #if JUCE_PPC || JUCE_IOS
  1849. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  1850. template <typename Type> static Type OSAtomicAdd64Barrier (Type b, JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return *a += b; }
  1851. template <typename Type> static Type OSAtomicIncrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return ++*a; }
  1852. template <typename Type> static Type OSAtomicDecrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return --*a; }
  1853. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, JUCE_MAC_ATOMICS_VOLATILE Type* value) noexcept
  1854. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  1855. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1856. #endif
  1857. #elif JUCE_ANDROID
  1858. #define JUCE_ATOMICS_ANDROID 1 // Android atomic functions
  1859. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1860. #elif JUCE_GCC
  1861. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  1862. #if JUCE_IOS
  1863. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1 // (on the iphone, the 64-bit ops will compile but not link)
  1864. #endif
  1865. #else
  1866. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  1867. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  1868. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  1869. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  1870. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  1871. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  1872. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  1873. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  1874. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  1875. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  1876. #define juce_MemoryBarrier _ReadWriteBarrier
  1877. #else
  1878. // (these are defined in juce_win32_Threads.cpp)
  1879. long juce_InterlockedExchange (volatile long* a, long b) noexcept;
  1880. long juce_InterlockedIncrement (volatile long* a) noexcept;
  1881. long juce_InterlockedDecrement (volatile long* a) noexcept;
  1882. long juce_InterlockedExchangeAdd (volatile long* a, long b) noexcept;
  1883. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) noexcept;
  1884. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) noexcept;
  1885. inline void juce_MemoryBarrier() noexcept { long x = 0; juce_InterlockedIncrement (&x); }
  1886. #endif
  1887. #if JUCE_64BIT
  1888. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  1889. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  1890. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  1891. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  1892. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  1893. #else
  1894. // None of these atomics are available in a 32-bit Windows build!!
  1895. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) noexcept { jassertfalse; Type old = *a; *a += b; return old; }
  1896. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) noexcept { jassertfalse; Type old = *a; *a = b; return old; }
  1897. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) noexcept { jassertfalse; return ++*a; }
  1898. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) noexcept { jassertfalse; return --*a; }
  1899. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1900. #endif
  1901. #endif
  1902. #if JUCE_MSVC
  1903. #pragma warning (push)
  1904. #pragma warning (disable: 4311) // (truncation warning)
  1905. #endif
  1906. template <typename Type>
  1907. inline Type Atomic<Type>::get() const noexcept
  1908. {
  1909. #if JUCE_ATOMICS_MAC
  1910. return sizeof (Type) == 4 ? castFrom32Bit ((int32) OSAtomicAdd32Barrier ((int32_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value))
  1911. : castFrom64Bit ((int64) OSAtomicAdd64Barrier ((int64_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value));
  1912. #elif JUCE_ATOMICS_WINDOWS
  1913. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchangeAdd ((volatile long*) &value, (long) 0))
  1914. : castFrom64Bit ((int64) juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0));
  1915. #elif JUCE_ATOMICS_ANDROID
  1916. return value;
  1917. #elif JUCE_ATOMICS_GCC
  1918. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_add_and_fetch ((volatile int32*) &value, 0))
  1919. : castFrom64Bit ((int64) __sync_add_and_fetch ((volatile int64*) &value, 0));
  1920. #endif
  1921. }
  1922. template <typename Type>
  1923. inline Type Atomic<Type>::exchange (const Type newValue) noexcept
  1924. {
  1925. #if JUCE_ATOMICS_ANDROID
  1926. return castFrom32Bit (__atomic_swap (castTo32Bit (newValue), (volatile int*) &value));
  1927. #elif JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  1928. Type currentVal = value;
  1929. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  1930. return currentVal;
  1931. #elif JUCE_ATOMICS_WINDOWS
  1932. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue)))
  1933. : castFrom64Bit ((int64) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue)));
  1934. #endif
  1935. }
  1936. template <typename Type>
  1937. inline Type Atomic<Type>::operator+= (const Type amountToAdd) noexcept
  1938. {
  1939. #if JUCE_ATOMICS_MAC
  1940. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32Barrier ((int32_t) castTo32Bit (amountToAdd), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1941. : (Type) OSAtomicAdd64Barrier ((int64_t) amountToAdd, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1942. #elif JUCE_ATOMICS_WINDOWS
  1943. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  1944. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  1945. #elif JUCE_ATOMICS_ANDROID
  1946. for (;;)
  1947. {
  1948. const Type oldValue (value);
  1949. const Type newValue (castFrom32Bit (castTo32Bit (oldValue) + castTo32Bit (amountToAdd)));
  1950. if (compareAndSetBool (newValue, oldValue))
  1951. return newValue;
  1952. }
  1953. #elif JUCE_ATOMICS_GCC
  1954. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  1955. #endif
  1956. }
  1957. template <typename Type>
  1958. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) noexcept
  1959. {
  1960. return operator+= (juce_negate (amountToSubtract));
  1961. }
  1962. template <typename Type>
  1963. inline Type Atomic<Type>::operator++() noexcept
  1964. {
  1965. #if JUCE_ATOMICS_MAC
  1966. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1967. : (Type) OSAtomicIncrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1968. #elif JUCE_ATOMICS_WINDOWS
  1969. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  1970. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  1971. #elif JUCE_ATOMICS_ANDROID
  1972. return (Type) (__atomic_inc ((volatile int*) &value) + 1);
  1973. #elif JUCE_ATOMICS_GCC
  1974. return (Type) __sync_add_and_fetch (&value, 1);
  1975. #endif
  1976. }
  1977. template <typename Type>
  1978. inline Type Atomic<Type>::operator--() noexcept
  1979. {
  1980. #if JUCE_ATOMICS_MAC
  1981. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1982. : (Type) OSAtomicDecrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1983. #elif JUCE_ATOMICS_WINDOWS
  1984. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  1985. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  1986. #elif JUCE_ATOMICS_ANDROID
  1987. return (Type) (__atomic_dec ((volatile int*) &value) - 1);
  1988. #elif JUCE_ATOMICS_GCC
  1989. return (Type) __sync_add_and_fetch (&value, -1);
  1990. #endif
  1991. }
  1992. template <typename Type>
  1993. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) noexcept
  1994. {
  1995. #if JUCE_ATOMICS_MAC
  1996. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) castTo32Bit (valueToCompare), (int32_t) castTo32Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1997. : OSAtomicCompareAndSwap64Barrier ((int64_t) castTo64Bit (valueToCompare), (int64_t) castTo64Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1998. #elif JUCE_ATOMICS_WINDOWS
  1999. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  2000. #elif JUCE_ATOMICS_ANDROID
  2001. return __atomic_cmpxchg (castTo32Bit (valueToCompare), castTo32Bit (newValue), (volatile int*) &value) == 0;
  2002. #elif JUCE_ATOMICS_GCC
  2003. return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))
  2004. : __sync_bool_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue));
  2005. #endif
  2006. }
  2007. template <typename Type>
  2008. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) noexcept
  2009. {
  2010. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_ANDROID
  2011. for (;;) // Annoying workaround for only having a bool CAS operation..
  2012. {
  2013. if (compareAndSetBool (newValue, valueToCompare))
  2014. return valueToCompare;
  2015. const Type result = value;
  2016. if (result != valueToCompare)
  2017. return result;
  2018. }
  2019. #elif JUCE_ATOMICS_WINDOWS
  2020. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare)))
  2021. : castFrom64Bit ((int64) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare)));
  2022. #elif JUCE_ATOMICS_GCC
  2023. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_val_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)))
  2024. : castFrom64Bit ((int64) __sync_val_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)));
  2025. #endif
  2026. }
  2027. template <typename Type>
  2028. inline void Atomic<Type>::memoryBarrier() noexcept
  2029. {
  2030. #if JUCE_ATOMICS_MAC
  2031. OSMemoryBarrier();
  2032. #elif JUCE_ATOMICS_GCC
  2033. __sync_synchronize();
  2034. #elif JUCE_ATOMICS_WINDOWS
  2035. juce_MemoryBarrier();
  2036. #endif
  2037. }
  2038. #if JUCE_MSVC
  2039. #pragma warning (pop)
  2040. #endif
  2041. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2042. /*** End of inlined file: juce_Atomic.h ***/
  2043. /*** Start of inlined file: juce_CharPointer_UTF8.h ***/
  2044. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2045. #define __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2046. /**
  2047. Wraps a pointer to a null-terminated UTF-8 character string, and provides
  2048. various methods to operate on the data.
  2049. @see CharPointer_UTF16, CharPointer_UTF32
  2050. */
  2051. class CharPointer_UTF8
  2052. {
  2053. public:
  2054. typedef char CharType;
  2055. inline explicit CharPointer_UTF8 (const CharType* const rawPointer) noexcept
  2056. : data (const_cast <CharType*> (rawPointer))
  2057. {
  2058. }
  2059. inline CharPointer_UTF8 (const CharPointer_UTF8& other) noexcept
  2060. : data (other.data)
  2061. {
  2062. }
  2063. inline CharPointer_UTF8& operator= (const CharPointer_UTF8& other) noexcept
  2064. {
  2065. data = other.data;
  2066. return *this;
  2067. }
  2068. inline CharPointer_UTF8& operator= (const CharType* text) noexcept
  2069. {
  2070. data = const_cast <CharType*> (text);
  2071. return *this;
  2072. }
  2073. /** This is a pointer comparison, it doesn't compare the actual text. */
  2074. inline bool operator== (const CharPointer_UTF8& other) const noexcept { return data == other.data; }
  2075. inline bool operator!= (const CharPointer_UTF8& other) const noexcept { return data != other.data; }
  2076. inline bool operator<= (const CharPointer_UTF8& other) const noexcept { return data <= other.data; }
  2077. inline bool operator< (const CharPointer_UTF8& other) const noexcept { return data < other.data; }
  2078. inline bool operator>= (const CharPointer_UTF8& other) const noexcept { return data >= other.data; }
  2079. inline bool operator> (const CharPointer_UTF8& other) const noexcept { return data > other.data; }
  2080. /** Returns the address that this pointer is pointing to. */
  2081. inline CharType* getAddress() const noexcept { return data; }
  2082. /** Returns the address that this pointer is pointing to. */
  2083. inline operator const CharType*() const noexcept { return data; }
  2084. /** Returns true if this pointer is pointing to a null character. */
  2085. inline bool isEmpty() const noexcept { return *data == 0; }
  2086. /** Returns the unicode character that this pointer is pointing to. */
  2087. juce_wchar operator*() const noexcept
  2088. {
  2089. const signed char byte = (signed char) *data;
  2090. if (byte >= 0)
  2091. return byte;
  2092. uint32 n = (uint32) (uint8) byte;
  2093. uint32 mask = 0x7f;
  2094. uint32 bit = 0x40;
  2095. size_t numExtraValues = 0;
  2096. while ((n & bit) != 0 && bit > 0x10)
  2097. {
  2098. mask >>= 1;
  2099. ++numExtraValues;
  2100. bit >>= 1;
  2101. }
  2102. n &= mask;
  2103. for (size_t i = 1; i <= numExtraValues; ++i)
  2104. {
  2105. const juce_wchar nextByte = data [i];
  2106. if ((nextByte & 0xc0) != 0x80)
  2107. break;
  2108. n <<= 6;
  2109. n |= (nextByte & 0x3f);
  2110. }
  2111. return (juce_wchar) n;
  2112. }
  2113. /** Moves this pointer along to the next character in the string. */
  2114. CharPointer_UTF8& operator++() noexcept
  2115. {
  2116. const signed char n = (signed char) *data++;
  2117. if (n < 0)
  2118. {
  2119. juce_wchar bit = 0x40;
  2120. while ((n & bit) != 0 && bit > 0x8)
  2121. {
  2122. ++data;
  2123. bit >>= 1;
  2124. }
  2125. }
  2126. return *this;
  2127. }
  2128. /** Moves this pointer back to the previous character in the string. */
  2129. CharPointer_UTF8& operator--() noexcept
  2130. {
  2131. const char n = *--data;
  2132. if ((n & 0xc0) == 0xc0)
  2133. {
  2134. int count = 3;
  2135. do
  2136. {
  2137. --data;
  2138. }
  2139. while ((*data & 0xc0) == 0xc0 && --count >= 0);
  2140. }
  2141. return *this;
  2142. }
  2143. /** Returns the character that this pointer is currently pointing to, and then
  2144. advances the pointer to point to the next character. */
  2145. juce_wchar getAndAdvance() noexcept
  2146. {
  2147. const signed char byte = (signed char) *data++;
  2148. if (byte >= 0)
  2149. return byte;
  2150. uint32 n = (uint32) (uint8) byte;
  2151. uint32 mask = 0x7f;
  2152. uint32 bit = 0x40;
  2153. int numExtraValues = 0;
  2154. while ((n & bit) != 0 && bit > 0x8)
  2155. {
  2156. mask >>= 1;
  2157. ++numExtraValues;
  2158. bit >>= 1;
  2159. }
  2160. n &= mask;
  2161. while (--numExtraValues >= 0)
  2162. {
  2163. const uint32 nextByte = (uint32) (uint8) *data++;
  2164. if ((nextByte & 0xc0) != 0x80)
  2165. break;
  2166. n <<= 6;
  2167. n |= (nextByte & 0x3f);
  2168. }
  2169. return (juce_wchar) n;
  2170. }
  2171. /** Moves this pointer along to the next character in the string. */
  2172. CharPointer_UTF8 operator++ (int) noexcept
  2173. {
  2174. CharPointer_UTF8 temp (*this);
  2175. ++*this;
  2176. return temp;
  2177. }
  2178. /** Moves this pointer forwards by the specified number of characters. */
  2179. void operator+= (int numToSkip) noexcept
  2180. {
  2181. if (numToSkip < 0)
  2182. {
  2183. while (++numToSkip <= 0)
  2184. --*this;
  2185. }
  2186. else
  2187. {
  2188. while (--numToSkip >= 0)
  2189. ++*this;
  2190. }
  2191. }
  2192. /** Moves this pointer backwards by the specified number of characters. */
  2193. void operator-= (int numToSkip) noexcept
  2194. {
  2195. operator+= (-numToSkip);
  2196. }
  2197. /** Returns the character at a given character index from the start of the string. */
  2198. juce_wchar operator[] (int characterIndex) const noexcept
  2199. {
  2200. CharPointer_UTF8 p (*this);
  2201. p += characterIndex;
  2202. return *p;
  2203. }
  2204. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2205. CharPointer_UTF8 operator+ (int numToSkip) const noexcept
  2206. {
  2207. CharPointer_UTF8 p (*this);
  2208. p += numToSkip;
  2209. return p;
  2210. }
  2211. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2212. CharPointer_UTF8 operator- (int numToSkip) const noexcept
  2213. {
  2214. CharPointer_UTF8 p (*this);
  2215. p += -numToSkip;
  2216. return p;
  2217. }
  2218. /** Returns the number of characters in this string. */
  2219. size_t length() const noexcept
  2220. {
  2221. const CharType* d = data;
  2222. size_t count = 0;
  2223. for (;;)
  2224. {
  2225. const uint32 n = (uint32) (uint8) *d++;
  2226. if ((n & 0x80) != 0)
  2227. {
  2228. uint32 bit = 0x40;
  2229. while ((n & bit) != 0)
  2230. {
  2231. ++d;
  2232. bit >>= 1;
  2233. if (bit == 0)
  2234. break; // illegal utf-8 sequence
  2235. }
  2236. }
  2237. else if (n == 0)
  2238. break;
  2239. ++count;
  2240. }
  2241. return count;
  2242. }
  2243. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2244. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  2245. {
  2246. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2247. }
  2248. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2249. size_t lengthUpTo (const CharPointer_UTF8& end) const noexcept
  2250. {
  2251. return CharacterFunctions::lengthUpTo (*this, end);
  2252. }
  2253. /** Returns the number of bytes that are used to represent this string.
  2254. This includes the terminating null character.
  2255. */
  2256. size_t sizeInBytes() const noexcept
  2257. {
  2258. return strlen (data) + 1;
  2259. }
  2260. /** Returns the number of bytes that would be needed to represent the given
  2261. unicode character in this encoding format.
  2262. */
  2263. static size_t getBytesRequiredFor (const juce_wchar charToWrite) noexcept
  2264. {
  2265. size_t num = 1;
  2266. const uint32 c = (uint32) charToWrite;
  2267. if (c >= 0x80)
  2268. {
  2269. ++num;
  2270. if (c >= 0x800)
  2271. {
  2272. ++num;
  2273. if (c >= 0x10000)
  2274. ++num;
  2275. }
  2276. }
  2277. return num;
  2278. }
  2279. /** Returns the number of bytes that would be needed to represent the given
  2280. string in this encoding format.
  2281. The value returned does NOT include the terminating null character.
  2282. */
  2283. template <class CharPointer>
  2284. static size_t getBytesRequiredFor (CharPointer text) noexcept
  2285. {
  2286. size_t count = 0;
  2287. juce_wchar n;
  2288. while ((n = text.getAndAdvance()) != 0)
  2289. count += getBytesRequiredFor (n);
  2290. return count;
  2291. }
  2292. /** Returns a pointer to the null character that terminates this string. */
  2293. CharPointer_UTF8 findTerminatingNull() const noexcept
  2294. {
  2295. return CharPointer_UTF8 (data + strlen (data));
  2296. }
  2297. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2298. void write (const juce_wchar charToWrite) noexcept
  2299. {
  2300. const uint32 c = (uint32) charToWrite;
  2301. if (c >= 0x80)
  2302. {
  2303. int numExtraBytes = 1;
  2304. if (c >= 0x800)
  2305. {
  2306. ++numExtraBytes;
  2307. if (c >= 0x10000)
  2308. ++numExtraBytes;
  2309. }
  2310. *data++ = (CharType) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  2311. while (--numExtraBytes >= 0)
  2312. *data++ = (CharType) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  2313. }
  2314. else
  2315. {
  2316. *data++ = (CharType) c;
  2317. }
  2318. }
  2319. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2320. inline void writeNull() const noexcept
  2321. {
  2322. *data = 0;
  2323. }
  2324. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2325. template <typename CharPointer>
  2326. void writeAll (const CharPointer& src) noexcept
  2327. {
  2328. CharacterFunctions::copyAll (*this, src);
  2329. }
  2330. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2331. void writeAll (const CharPointer_UTF8& src) noexcept
  2332. {
  2333. const CharType* s = src.data;
  2334. while ((*data = *s) != 0)
  2335. {
  2336. ++data;
  2337. ++s;
  2338. }
  2339. }
  2340. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2341. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2342. to the destination buffer before stopping.
  2343. */
  2344. template <typename CharPointer>
  2345. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  2346. {
  2347. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2348. }
  2349. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2350. The maxChars parameter specifies the maximum number of characters that can be
  2351. written to the destination buffer before stopping (including the terminating null).
  2352. */
  2353. template <typename CharPointer>
  2354. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  2355. {
  2356. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2357. }
  2358. /** Compares this string with another one. */
  2359. template <typename CharPointer>
  2360. int compare (const CharPointer& other) const noexcept
  2361. {
  2362. return CharacterFunctions::compare (*this, other);
  2363. }
  2364. /** Compares this string with another one, up to a specified number of characters. */
  2365. template <typename CharPointer>
  2366. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  2367. {
  2368. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2369. }
  2370. /** Compares this string with another one. */
  2371. template <typename CharPointer>
  2372. int compareIgnoreCase (const CharPointer& other) const noexcept
  2373. {
  2374. return CharacterFunctions::compareIgnoreCase (*this, other);
  2375. }
  2376. /** Compares this string with another one. */
  2377. int compareIgnoreCase (const CharPointer_UTF8& other) const noexcept
  2378. {
  2379. #if JUCE_WINDOWS
  2380. return stricmp (data, other.data);
  2381. #else
  2382. return strcasecmp (data, other.data);
  2383. #endif
  2384. }
  2385. /** Compares this string with another one, up to a specified number of characters. */
  2386. template <typename CharPointer>
  2387. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  2388. {
  2389. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2390. }
  2391. /** Compares this string with another one, up to a specified number of characters. */
  2392. int compareIgnoreCaseUpTo (const CharPointer_UTF8& other, const int maxChars) const noexcept
  2393. {
  2394. #if JUCE_WINDOWS
  2395. return strnicmp (data, other.data, maxChars);
  2396. #else
  2397. return strncasecmp (data, other.data, maxChars);
  2398. #endif
  2399. }
  2400. /** Returns the character index of a substring, or -1 if it isn't found. */
  2401. template <typename CharPointer>
  2402. int indexOf (const CharPointer& stringToFind) const noexcept
  2403. {
  2404. return CharacterFunctions::indexOf (*this, stringToFind);
  2405. }
  2406. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2407. int indexOf (const juce_wchar charToFind) const noexcept
  2408. {
  2409. return CharacterFunctions::indexOfChar (*this, charToFind);
  2410. }
  2411. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2412. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  2413. {
  2414. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2415. : CharacterFunctions::indexOfChar (*this, charToFind);
  2416. }
  2417. /** Returns true if the first character of this string is whitespace. */
  2418. bool isWhitespace() const noexcept { return *data == ' ' || (*data <= 13 && *data >= 9); }
  2419. /** Returns true if the first character of this string is a digit. */
  2420. bool isDigit() const noexcept { return *data >= '0' && *data <= '9'; }
  2421. /** Returns true if the first character of this string is a letter. */
  2422. bool isLetter() const noexcept { return CharacterFunctions::isLetter (operator*()) != 0; }
  2423. /** Returns true if the first character of this string is a letter or digit. */
  2424. bool isLetterOrDigit() const noexcept { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2425. /** Returns true if the first character of this string is upper-case. */
  2426. bool isUpperCase() const noexcept { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2427. /** Returns true if the first character of this string is lower-case. */
  2428. bool isLowerCase() const noexcept { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2429. /** Returns an upper-case version of the first character of this string. */
  2430. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (operator*()); }
  2431. /** Returns a lower-case version of the first character of this string. */
  2432. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (operator*()); }
  2433. /** Parses this string as a 32-bit integer. */
  2434. int getIntValue32() const noexcept { return atoi (data); }
  2435. /** Parses this string as a 64-bit integer. */
  2436. int64 getIntValue64() const noexcept
  2437. {
  2438. #if JUCE_LINUX || JUCE_ANDROID
  2439. return atoll (data);
  2440. #elif JUCE_WINDOWS
  2441. return _atoi64 (data);
  2442. #else
  2443. return CharacterFunctions::getIntValue <int64, CharPointer_UTF8> (*this);
  2444. #endif
  2445. }
  2446. /** Parses this string as a floating point double. */
  2447. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  2448. /** Returns the first non-whitespace character in the string. */
  2449. CharPointer_UTF8 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  2450. /** Returns true if the given unicode character can be represented in this encoding. */
  2451. static bool canRepresent (juce_wchar character) noexcept
  2452. {
  2453. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  2454. }
  2455. /** Returns true if this data contains a valid string in this encoding. */
  2456. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2457. {
  2458. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2459. {
  2460. const signed char byte = (signed char) *dataToTest;
  2461. if (byte < 0)
  2462. {
  2463. uint32 n = (uint32) (uint8) byte;
  2464. uint32 mask = 0x7f;
  2465. uint32 bit = 0x40;
  2466. int numExtraValues = 0;
  2467. while ((n & bit) != 0)
  2468. {
  2469. if (bit <= 0x10)
  2470. return false;
  2471. mask >>= 1;
  2472. ++numExtraValues;
  2473. bit >>= 1;
  2474. }
  2475. n &= mask;
  2476. while (--numExtraValues >= 0)
  2477. {
  2478. const uint32 nextByte = (uint32) (uint8) *dataToTest++;
  2479. if ((nextByte & 0xc0) != 0x80)
  2480. return false;
  2481. }
  2482. }
  2483. }
  2484. return true;
  2485. }
  2486. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2487. CharPointer_UTF8 atomicSwap (const CharPointer_UTF8& newValue)
  2488. {
  2489. return CharPointer_UTF8 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2490. }
  2491. /** These values are the byte-order-mark (BOM) values for a UTF-8 stream. */
  2492. enum
  2493. {
  2494. byteOrderMark1 = 0xef,
  2495. byteOrderMark2 = 0xbb,
  2496. byteOrderMark3 = 0xbf
  2497. };
  2498. private:
  2499. CharType* data;
  2500. };
  2501. #endif // __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2502. /*** End of inlined file: juce_CharPointer_UTF8.h ***/
  2503. /*** Start of inlined file: juce_CharPointer_UTF16.h ***/
  2504. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2505. #define __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2506. /**
  2507. Wraps a pointer to a null-terminated UTF-16 character string, and provides
  2508. various methods to operate on the data.
  2509. @see CharPointer_UTF8, CharPointer_UTF32
  2510. */
  2511. class CharPointer_UTF16
  2512. {
  2513. public:
  2514. #if JUCE_NATIVE_WCHAR_IS_UTF16
  2515. typedef wchar_t CharType;
  2516. #else
  2517. typedef int16 CharType;
  2518. #endif
  2519. inline explicit CharPointer_UTF16 (const CharType* const rawPointer) noexcept
  2520. : data (const_cast <CharType*> (rawPointer))
  2521. {
  2522. }
  2523. inline CharPointer_UTF16 (const CharPointer_UTF16& other) noexcept
  2524. : data (other.data)
  2525. {
  2526. }
  2527. inline CharPointer_UTF16& operator= (const CharPointer_UTF16& other) noexcept
  2528. {
  2529. data = other.data;
  2530. return *this;
  2531. }
  2532. inline CharPointer_UTF16& operator= (const CharType* text) noexcept
  2533. {
  2534. data = const_cast <CharType*> (text);
  2535. return *this;
  2536. }
  2537. /** This is a pointer comparison, it doesn't compare the actual text. */
  2538. inline bool operator== (const CharPointer_UTF16& other) const noexcept { return data == other.data; }
  2539. inline bool operator!= (const CharPointer_UTF16& other) const noexcept { return data != other.data; }
  2540. inline bool operator<= (const CharPointer_UTF16& other) const noexcept { return data <= other.data; }
  2541. inline bool operator< (const CharPointer_UTF16& other) const noexcept { return data < other.data; }
  2542. inline bool operator>= (const CharPointer_UTF16& other) const noexcept { return data >= other.data; }
  2543. inline bool operator> (const CharPointer_UTF16& other) const noexcept { return data > other.data; }
  2544. /** Returns the address that this pointer is pointing to. */
  2545. inline CharType* getAddress() const noexcept { return data; }
  2546. /** Returns the address that this pointer is pointing to. */
  2547. inline operator const CharType*() const noexcept { return data; }
  2548. /** Returns true if this pointer is pointing to a null character. */
  2549. inline bool isEmpty() const noexcept { return *data == 0; }
  2550. /** Returns the unicode character that this pointer is pointing to. */
  2551. juce_wchar operator*() const noexcept
  2552. {
  2553. uint32 n = (uint32) (uint16) *data;
  2554. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) data[1]) >= 0xdc00)
  2555. n = 0x10000 + (((n - 0xd800) << 10) | (((uint32) (uint16) data[1]) - 0xdc00));
  2556. return (juce_wchar) n;
  2557. }
  2558. /** Moves this pointer along to the next character in the string. */
  2559. CharPointer_UTF16& operator++() noexcept
  2560. {
  2561. const juce_wchar n = *data++;
  2562. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2563. ++data;
  2564. return *this;
  2565. }
  2566. /** Moves this pointer back to the previous character in the string. */
  2567. CharPointer_UTF16& operator--() noexcept
  2568. {
  2569. const juce_wchar n = *--data;
  2570. if (n >= 0xdc00 && n <= 0xdfff)
  2571. --data;
  2572. return *this;
  2573. }
  2574. /** Returns the character that this pointer is currently pointing to, and then
  2575. advances the pointer to point to the next character. */
  2576. juce_wchar getAndAdvance() noexcept
  2577. {
  2578. uint32 n = (uint32) (uint16) *data++;
  2579. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2580. n = 0x10000 + ((((n - 0xd800) << 10) | (((uint32) (uint16) *data++) - 0xdc00)));
  2581. return (juce_wchar) n;
  2582. }
  2583. /** Moves this pointer along to the next character in the string. */
  2584. CharPointer_UTF16 operator++ (int) noexcept
  2585. {
  2586. CharPointer_UTF16 temp (*this);
  2587. ++*this;
  2588. return temp;
  2589. }
  2590. /** Moves this pointer forwards by the specified number of characters. */
  2591. void operator+= (int numToSkip) noexcept
  2592. {
  2593. if (numToSkip < 0)
  2594. {
  2595. while (++numToSkip <= 0)
  2596. --*this;
  2597. }
  2598. else
  2599. {
  2600. while (--numToSkip >= 0)
  2601. ++*this;
  2602. }
  2603. }
  2604. /** Moves this pointer backwards by the specified number of characters. */
  2605. void operator-= (int numToSkip) noexcept
  2606. {
  2607. operator+= (-numToSkip);
  2608. }
  2609. /** Returns the character at a given character index from the start of the string. */
  2610. juce_wchar operator[] (const int characterIndex) const noexcept
  2611. {
  2612. CharPointer_UTF16 p (*this);
  2613. p += characterIndex;
  2614. return *p;
  2615. }
  2616. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2617. CharPointer_UTF16 operator+ (const int numToSkip) const noexcept
  2618. {
  2619. CharPointer_UTF16 p (*this);
  2620. p += numToSkip;
  2621. return p;
  2622. }
  2623. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2624. CharPointer_UTF16 operator- (const int numToSkip) const noexcept
  2625. {
  2626. CharPointer_UTF16 p (*this);
  2627. p += -numToSkip;
  2628. return p;
  2629. }
  2630. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2631. void write (juce_wchar charToWrite) noexcept
  2632. {
  2633. if (charToWrite >= 0x10000)
  2634. {
  2635. charToWrite -= 0x10000;
  2636. *data++ = (CharType) (0xd800 + (charToWrite >> 10));
  2637. *data++ = (CharType) (0xdc00 + (charToWrite & 0x3ff));
  2638. }
  2639. else
  2640. {
  2641. *data++ = (CharType) charToWrite;
  2642. }
  2643. }
  2644. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2645. inline void writeNull() const noexcept
  2646. {
  2647. *data = 0;
  2648. }
  2649. /** Returns the number of characters in this string. */
  2650. size_t length() const noexcept
  2651. {
  2652. const CharType* d = data;
  2653. size_t count = 0;
  2654. for (;;)
  2655. {
  2656. const int n = *d++;
  2657. if (n >= 0xd800 && n <= 0xdfff)
  2658. {
  2659. if (*d++ == 0)
  2660. break;
  2661. }
  2662. else if (n == 0)
  2663. break;
  2664. ++count;
  2665. }
  2666. return count;
  2667. }
  2668. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2669. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  2670. {
  2671. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2672. }
  2673. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2674. size_t lengthUpTo (const CharPointer_UTF16& end) const noexcept
  2675. {
  2676. return CharacterFunctions::lengthUpTo (*this, end);
  2677. }
  2678. /** Returns the number of bytes that are used to represent this string.
  2679. This includes the terminating null character.
  2680. */
  2681. size_t sizeInBytes() const noexcept
  2682. {
  2683. return sizeof (CharType) * (findNullIndex (data) + 1);
  2684. }
  2685. /** Returns the number of bytes that would be needed to represent the given
  2686. unicode character in this encoding format.
  2687. */
  2688. static size_t getBytesRequiredFor (const juce_wchar charToWrite) noexcept
  2689. {
  2690. return (charToWrite >= 0x10000) ? (sizeof (CharType) * 2) : sizeof (CharType);
  2691. }
  2692. /** Returns the number of bytes that would be needed to represent the given
  2693. string in this encoding format.
  2694. The value returned does NOT include the terminating null character.
  2695. */
  2696. template <class CharPointer>
  2697. static size_t getBytesRequiredFor (CharPointer text) noexcept
  2698. {
  2699. size_t count = 0;
  2700. juce_wchar n;
  2701. while ((n = text.getAndAdvance()) != 0)
  2702. count += getBytesRequiredFor (n);
  2703. return count;
  2704. }
  2705. /** Returns a pointer to the null character that terminates this string. */
  2706. CharPointer_UTF16 findTerminatingNull() const noexcept
  2707. {
  2708. const CharType* t = data;
  2709. while (*t != 0)
  2710. ++t;
  2711. return CharPointer_UTF16 (t);
  2712. }
  2713. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2714. template <typename CharPointer>
  2715. void writeAll (const CharPointer& src) noexcept
  2716. {
  2717. CharacterFunctions::copyAll (*this, src);
  2718. }
  2719. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2720. void writeAll (const CharPointer_UTF16& src) noexcept
  2721. {
  2722. const CharType* s = src.data;
  2723. while ((*data = *s) != 0)
  2724. {
  2725. ++data;
  2726. ++s;
  2727. }
  2728. }
  2729. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2730. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2731. to the destination buffer before stopping.
  2732. */
  2733. template <typename CharPointer>
  2734. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  2735. {
  2736. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2737. }
  2738. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2739. The maxChars parameter specifies the maximum number of characters that can be
  2740. written to the destination buffer before stopping (including the terminating null).
  2741. */
  2742. template <typename CharPointer>
  2743. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  2744. {
  2745. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2746. }
  2747. /** Compares this string with another one. */
  2748. template <typename CharPointer>
  2749. int compare (const CharPointer& other) const noexcept
  2750. {
  2751. return CharacterFunctions::compare (*this, other);
  2752. }
  2753. /** Compares this string with another one, up to a specified number of characters. */
  2754. template <typename CharPointer>
  2755. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  2756. {
  2757. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2758. }
  2759. /** Compares this string with another one. */
  2760. template <typename CharPointer>
  2761. int compareIgnoreCase (const CharPointer& other) const noexcept
  2762. {
  2763. return CharacterFunctions::compareIgnoreCase (*this, other);
  2764. }
  2765. /** Compares this string with another one, up to a specified number of characters. */
  2766. template <typename CharPointer>
  2767. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  2768. {
  2769. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2770. }
  2771. #if JUCE_WINDOWS && ! DOXYGEN
  2772. int compareIgnoreCase (const CharPointer_UTF16& other) const noexcept
  2773. {
  2774. return _wcsicmp (data, other.data);
  2775. }
  2776. int compareIgnoreCaseUpTo (const CharPointer_UTF16& other, int maxChars) const noexcept
  2777. {
  2778. return _wcsnicmp (data, other.data, maxChars);
  2779. }
  2780. int indexOf (const CharPointer_UTF16& stringToFind) const noexcept
  2781. {
  2782. const CharType* const t = wcsstr (data, stringToFind.getAddress());
  2783. return t == nullptr ? -1 : (int) (t - data);
  2784. }
  2785. #endif
  2786. /** Returns the character index of a substring, or -1 if it isn't found. */
  2787. template <typename CharPointer>
  2788. int indexOf (const CharPointer& stringToFind) const noexcept
  2789. {
  2790. return CharacterFunctions::indexOf (*this, stringToFind);
  2791. }
  2792. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2793. int indexOf (const juce_wchar charToFind) const noexcept
  2794. {
  2795. return CharacterFunctions::indexOfChar (*this, charToFind);
  2796. }
  2797. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2798. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  2799. {
  2800. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2801. : CharacterFunctions::indexOfChar (*this, charToFind);
  2802. }
  2803. /** Returns true if the first character of this string is whitespace. */
  2804. bool isWhitespace() const noexcept { return CharacterFunctions::isWhitespace (operator*()) != 0; }
  2805. /** Returns true if the first character of this string is a digit. */
  2806. bool isDigit() const noexcept { return CharacterFunctions::isDigit (operator*()) != 0; }
  2807. /** Returns true if the first character of this string is a letter. */
  2808. bool isLetter() const noexcept { return CharacterFunctions::isLetter (operator*()) != 0; }
  2809. /** Returns true if the first character of this string is a letter or digit. */
  2810. bool isLetterOrDigit() const noexcept { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2811. /** Returns true if the first character of this string is upper-case. */
  2812. bool isUpperCase() const noexcept { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2813. /** Returns true if the first character of this string is lower-case. */
  2814. bool isLowerCase() const noexcept { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2815. /** Returns an upper-case version of the first character of this string. */
  2816. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (operator*()); }
  2817. /** Returns a lower-case version of the first character of this string. */
  2818. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (operator*()); }
  2819. /** Parses this string as a 32-bit integer. */
  2820. int getIntValue32() const noexcept
  2821. {
  2822. #if JUCE_WINDOWS
  2823. return _wtoi (data);
  2824. #else
  2825. return CharacterFunctions::getIntValue <int, CharPointer_UTF16> (*this);
  2826. #endif
  2827. }
  2828. /** Parses this string as a 64-bit integer. */
  2829. int64 getIntValue64() const noexcept
  2830. {
  2831. #if JUCE_WINDOWS
  2832. return _wtoi64 (data);
  2833. #else
  2834. return CharacterFunctions::getIntValue <int64, CharPointer_UTF16> (*this);
  2835. #endif
  2836. }
  2837. /** Parses this string as a floating point double. */
  2838. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  2839. /** Returns the first non-whitespace character in the string. */
  2840. CharPointer_UTF16 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  2841. /** Returns true if the given unicode character can be represented in this encoding. */
  2842. static bool canRepresent (juce_wchar character) noexcept
  2843. {
  2844. return ((unsigned int) character) < (unsigned int) 0x10ffff
  2845. && (((unsigned int) character) < 0xd800 || ((unsigned int) character) > 0xdfff);
  2846. }
  2847. /** Returns true if this data contains a valid string in this encoding. */
  2848. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2849. {
  2850. maxBytesToRead /= sizeof (CharType);
  2851. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2852. {
  2853. const uint32 n = (uint32) (uint16) *dataToTest++;
  2854. if (n >= 0xd800)
  2855. {
  2856. if (n > 0x10ffff)
  2857. return false;
  2858. if (n <= 0xdfff)
  2859. {
  2860. if (n > 0xdc00)
  2861. return false;
  2862. const uint32 nextChar = (uint32) (uint16) *dataToTest++;
  2863. if (nextChar < 0xdc00 || nextChar > 0xdfff)
  2864. return false;
  2865. }
  2866. }
  2867. }
  2868. return true;
  2869. }
  2870. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2871. CharPointer_UTF16 atomicSwap (const CharPointer_UTF16& newValue)
  2872. {
  2873. return CharPointer_UTF16 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2874. }
  2875. /** These values are the byte-order-mark (BOM) values for a UTF-16 stream. */
  2876. enum
  2877. {
  2878. byteOrderMarkBE1 = 0xfe,
  2879. byteOrderMarkBE2 = 0xff,
  2880. byteOrderMarkLE1 = 0xff,
  2881. byteOrderMarkLE2 = 0xfe
  2882. };
  2883. private:
  2884. CharType* data;
  2885. static int findNullIndex (const CharType* const t) noexcept
  2886. {
  2887. int n = 0;
  2888. while (t[n] != 0)
  2889. ++n;
  2890. return n;
  2891. }
  2892. };
  2893. #endif // __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2894. /*** End of inlined file: juce_CharPointer_UTF16.h ***/
  2895. /*** Start of inlined file: juce_CharPointer_UTF32.h ***/
  2896. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2897. #define __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2898. /**
  2899. Wraps a pointer to a null-terminated UTF-32 character string, and provides
  2900. various methods to operate on the data.
  2901. @see CharPointer_UTF8, CharPointer_UTF16
  2902. */
  2903. class CharPointer_UTF32
  2904. {
  2905. public:
  2906. typedef juce_wchar CharType;
  2907. inline explicit CharPointer_UTF32 (const CharType* const rawPointer) noexcept
  2908. : data (const_cast <CharType*> (rawPointer))
  2909. {
  2910. }
  2911. inline CharPointer_UTF32 (const CharPointer_UTF32& other) noexcept
  2912. : data (other.data)
  2913. {
  2914. }
  2915. inline CharPointer_UTF32& operator= (const CharPointer_UTF32& other) noexcept
  2916. {
  2917. data = other.data;
  2918. return *this;
  2919. }
  2920. inline CharPointer_UTF32& operator= (const CharType* text) noexcept
  2921. {
  2922. data = const_cast <CharType*> (text);
  2923. return *this;
  2924. }
  2925. /** This is a pointer comparison, it doesn't compare the actual text. */
  2926. inline bool operator== (const CharPointer_UTF32& other) const noexcept { return data == other.data; }
  2927. inline bool operator!= (const CharPointer_UTF32& other) const noexcept { return data != other.data; }
  2928. inline bool operator<= (const CharPointer_UTF32& other) const noexcept { return data <= other.data; }
  2929. inline bool operator< (const CharPointer_UTF32& other) const noexcept { return data < other.data; }
  2930. inline bool operator>= (const CharPointer_UTF32& other) const noexcept { return data >= other.data; }
  2931. inline bool operator> (const CharPointer_UTF32& other) const noexcept { return data > other.data; }
  2932. /** Returns the address that this pointer is pointing to. */
  2933. inline CharType* getAddress() const noexcept { return data; }
  2934. /** Returns the address that this pointer is pointing to. */
  2935. inline operator const CharType*() const noexcept { return data; }
  2936. /** Returns true if this pointer is pointing to a null character. */
  2937. inline bool isEmpty() const noexcept { return *data == 0; }
  2938. /** Returns the unicode character that this pointer is pointing to. */
  2939. inline juce_wchar operator*() const noexcept { return *data; }
  2940. /** Moves this pointer along to the next character in the string. */
  2941. inline CharPointer_UTF32& operator++() noexcept
  2942. {
  2943. ++data;
  2944. return *this;
  2945. }
  2946. /** Moves this pointer to the previous character in the string. */
  2947. inline CharPointer_UTF32& operator--() noexcept
  2948. {
  2949. --data;
  2950. return *this;
  2951. }
  2952. /** Returns the character that this pointer is currently pointing to, and then
  2953. advances the pointer to point to the next character. */
  2954. inline juce_wchar getAndAdvance() noexcept { return *data++; }
  2955. /** Moves this pointer along to the next character in the string. */
  2956. CharPointer_UTF32 operator++ (int) noexcept
  2957. {
  2958. CharPointer_UTF32 temp (*this);
  2959. ++data;
  2960. return temp;
  2961. }
  2962. /** Moves this pointer forwards by the specified number of characters. */
  2963. inline void operator+= (const int numToSkip) noexcept
  2964. {
  2965. data += numToSkip;
  2966. }
  2967. inline void operator-= (const int numToSkip) noexcept
  2968. {
  2969. data -= numToSkip;
  2970. }
  2971. /** Returns the character at a given character index from the start of the string. */
  2972. inline juce_wchar& operator[] (const int characterIndex) const noexcept
  2973. {
  2974. return data [characterIndex];
  2975. }
  2976. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2977. CharPointer_UTF32 operator+ (const int numToSkip) const noexcept
  2978. {
  2979. return CharPointer_UTF32 (data + numToSkip);
  2980. }
  2981. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2982. CharPointer_UTF32 operator- (const int numToSkip) const noexcept
  2983. {
  2984. return CharPointer_UTF32 (data - numToSkip);
  2985. }
  2986. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2987. inline void write (const juce_wchar charToWrite) noexcept
  2988. {
  2989. *data++ = charToWrite;
  2990. }
  2991. inline void replaceChar (const juce_wchar newChar) noexcept
  2992. {
  2993. *data = newChar;
  2994. }
  2995. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2996. inline void writeNull() const noexcept
  2997. {
  2998. *data = 0;
  2999. }
  3000. /** Returns the number of characters in this string. */
  3001. size_t length() const noexcept
  3002. {
  3003. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  3004. return wcslen (data);
  3005. #else
  3006. size_t n = 0;
  3007. while (data[n] != 0)
  3008. ++n;
  3009. return n;
  3010. #endif
  3011. }
  3012. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  3013. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  3014. {
  3015. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  3016. }
  3017. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  3018. size_t lengthUpTo (const CharPointer_UTF32& end) const noexcept
  3019. {
  3020. return CharacterFunctions::lengthUpTo (*this, end);
  3021. }
  3022. /** Returns the number of bytes that are used to represent this string.
  3023. This includes the terminating null character.
  3024. */
  3025. size_t sizeInBytes() const noexcept
  3026. {
  3027. return sizeof (CharType) * (length() + 1);
  3028. }
  3029. /** Returns the number of bytes that would be needed to represent the given
  3030. unicode character in this encoding format.
  3031. */
  3032. static inline size_t getBytesRequiredFor (const juce_wchar) noexcept
  3033. {
  3034. return sizeof (CharType);
  3035. }
  3036. /** Returns the number of bytes that would be needed to represent the given
  3037. string in this encoding format.
  3038. The value returned does NOT include the terminating null character.
  3039. */
  3040. template <class CharPointer>
  3041. static size_t getBytesRequiredFor (const CharPointer& text) noexcept
  3042. {
  3043. return sizeof (CharType) * text.length();
  3044. }
  3045. /** Returns a pointer to the null character that terminates this string. */
  3046. CharPointer_UTF32 findTerminatingNull() const noexcept
  3047. {
  3048. return CharPointer_UTF32 (data + length());
  3049. }
  3050. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3051. template <typename CharPointer>
  3052. void writeAll (const CharPointer& src) noexcept
  3053. {
  3054. CharacterFunctions::copyAll (*this, src);
  3055. }
  3056. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3057. void writeAll (const CharPointer_UTF32& src) noexcept
  3058. {
  3059. const CharType* s = src.data;
  3060. while ((*data = *s) != 0)
  3061. {
  3062. ++data;
  3063. ++s;
  3064. }
  3065. }
  3066. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3067. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3068. to the destination buffer before stopping.
  3069. */
  3070. template <typename CharPointer>
  3071. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  3072. {
  3073. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3074. }
  3075. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3076. The maxChars parameter specifies the maximum number of characters that can be
  3077. written to the destination buffer before stopping (including the terminating null).
  3078. */
  3079. template <typename CharPointer>
  3080. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  3081. {
  3082. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3083. }
  3084. /** Compares this string with another one. */
  3085. template <typename CharPointer>
  3086. int compare (const CharPointer& other) const noexcept
  3087. {
  3088. return CharacterFunctions::compare (*this, other);
  3089. }
  3090. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  3091. /** Compares this string with another one. */
  3092. int compare (const CharPointer_UTF32& other) const noexcept
  3093. {
  3094. return wcscmp (data, other.data);
  3095. }
  3096. #endif
  3097. /** Compares this string with another one, up to a specified number of characters. */
  3098. template <typename CharPointer>
  3099. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  3100. {
  3101. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3102. }
  3103. /** Compares this string with another one. */
  3104. template <typename CharPointer>
  3105. int compareIgnoreCase (const CharPointer& other) const
  3106. {
  3107. return CharacterFunctions::compareIgnoreCase (*this, other);
  3108. }
  3109. /** Compares this string with another one, up to a specified number of characters. */
  3110. template <typename CharPointer>
  3111. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  3112. {
  3113. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3114. }
  3115. /** Returns the character index of a substring, or -1 if it isn't found. */
  3116. template <typename CharPointer>
  3117. int indexOf (const CharPointer& stringToFind) const noexcept
  3118. {
  3119. return CharacterFunctions::indexOf (*this, stringToFind);
  3120. }
  3121. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3122. int indexOf (const juce_wchar charToFind) const noexcept
  3123. {
  3124. int i = 0;
  3125. while (data[i] != 0)
  3126. {
  3127. if (data[i] == charToFind)
  3128. return i;
  3129. ++i;
  3130. }
  3131. return -1;
  3132. }
  3133. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3134. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  3135. {
  3136. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3137. : CharacterFunctions::indexOfChar (*this, charToFind);
  3138. }
  3139. /** Returns true if the first character of this string is whitespace. */
  3140. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3141. /** Returns true if the first character of this string is a digit. */
  3142. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3143. /** Returns true if the first character of this string is a letter. */
  3144. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3145. /** Returns true if the first character of this string is a letter or digit. */
  3146. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3147. /** Returns true if the first character of this string is upper-case. */
  3148. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3149. /** Returns true if the first character of this string is lower-case. */
  3150. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3151. /** Returns an upper-case version of the first character of this string. */
  3152. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (*data); }
  3153. /** Returns a lower-case version of the first character of this string. */
  3154. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (*data); }
  3155. /** Parses this string as a 32-bit integer. */
  3156. int getIntValue32() const noexcept { return CharacterFunctions::getIntValue <int, CharPointer_UTF32> (*this); }
  3157. /** Parses this string as a 64-bit integer. */
  3158. int64 getIntValue64() const noexcept { return CharacterFunctions::getIntValue <int64, CharPointer_UTF32> (*this); }
  3159. /** Parses this string as a floating point double. */
  3160. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  3161. /** Returns the first non-whitespace character in the string. */
  3162. CharPointer_UTF32 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  3163. /** Returns true if the given unicode character can be represented in this encoding. */
  3164. static bool canRepresent (juce_wchar character) noexcept
  3165. {
  3166. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  3167. }
  3168. /** Returns true if this data contains a valid string in this encoding. */
  3169. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3170. {
  3171. maxBytesToRead /= sizeof (CharType);
  3172. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  3173. if (! canRepresent (*dataToTest++))
  3174. return false;
  3175. return true;
  3176. }
  3177. /** Atomically swaps this pointer for a new value, returning the previous value. */
  3178. CharPointer_UTF32 atomicSwap (const CharPointer_UTF32& newValue)
  3179. {
  3180. return CharPointer_UTF32 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  3181. }
  3182. private:
  3183. CharType* data;
  3184. };
  3185. #endif // __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  3186. /*** End of inlined file: juce_CharPointer_UTF32.h ***/
  3187. /*** Start of inlined file: juce_CharPointer_ASCII.h ***/
  3188. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3189. #define __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3190. /**
  3191. Wraps a pointer to a null-terminated ASCII character string, and provides
  3192. various methods to operate on the data.
  3193. A valid ASCII string is assumed to not contain any characters above 127.
  3194. @see CharPointer_UTF8, CharPointer_UTF16, CharPointer_UTF32
  3195. */
  3196. class CharPointer_ASCII
  3197. {
  3198. public:
  3199. typedef char CharType;
  3200. inline explicit CharPointer_ASCII (const CharType* const rawPointer) noexcept
  3201. : data (const_cast <CharType*> (rawPointer))
  3202. {
  3203. }
  3204. inline CharPointer_ASCII (const CharPointer_ASCII& other) noexcept
  3205. : data (other.data)
  3206. {
  3207. }
  3208. inline CharPointer_ASCII& operator= (const CharPointer_ASCII& other) noexcept
  3209. {
  3210. data = other.data;
  3211. return *this;
  3212. }
  3213. inline CharPointer_ASCII& operator= (const CharType* text) noexcept
  3214. {
  3215. data = const_cast <CharType*> (text);
  3216. return *this;
  3217. }
  3218. /** This is a pointer comparison, it doesn't compare the actual text. */
  3219. inline bool operator== (const CharPointer_ASCII& other) const noexcept { return data == other.data; }
  3220. inline bool operator!= (const CharPointer_ASCII& other) const noexcept { return data != other.data; }
  3221. inline bool operator<= (const CharPointer_ASCII& other) const noexcept { return data <= other.data; }
  3222. inline bool operator< (const CharPointer_ASCII& other) const noexcept { return data < other.data; }
  3223. inline bool operator>= (const CharPointer_ASCII& other) const noexcept { return data >= other.data; }
  3224. inline bool operator> (const CharPointer_ASCII& other) const noexcept { return data > other.data; }
  3225. /** Returns the address that this pointer is pointing to. */
  3226. inline CharType* getAddress() const noexcept { return data; }
  3227. /** Returns the address that this pointer is pointing to. */
  3228. inline operator const CharType*() const noexcept { return data; }
  3229. /** Returns true if this pointer is pointing to a null character. */
  3230. inline bool isEmpty() const noexcept { return *data == 0; }
  3231. /** Returns the unicode character that this pointer is pointing to. */
  3232. inline juce_wchar operator*() const noexcept { return *data; }
  3233. /** Moves this pointer along to the next character in the string. */
  3234. inline CharPointer_ASCII& operator++() noexcept
  3235. {
  3236. ++data;
  3237. return *this;
  3238. }
  3239. /** Moves this pointer to the previous character in the string. */
  3240. inline CharPointer_ASCII& operator--() noexcept
  3241. {
  3242. --data;
  3243. return *this;
  3244. }
  3245. /** Returns the character that this pointer is currently pointing to, and then
  3246. advances the pointer to point to the next character. */
  3247. inline juce_wchar getAndAdvance() noexcept { return *data++; }
  3248. /** Moves this pointer along to the next character in the string. */
  3249. CharPointer_ASCII operator++ (int) noexcept
  3250. {
  3251. CharPointer_ASCII temp (*this);
  3252. ++data;
  3253. return temp;
  3254. }
  3255. /** Moves this pointer forwards by the specified number of characters. */
  3256. inline void operator+= (const int numToSkip) noexcept
  3257. {
  3258. data += numToSkip;
  3259. }
  3260. inline void operator-= (const int numToSkip) noexcept
  3261. {
  3262. data -= numToSkip;
  3263. }
  3264. /** Returns the character at a given character index from the start of the string. */
  3265. inline juce_wchar operator[] (const int characterIndex) const noexcept
  3266. {
  3267. return (juce_wchar) (unsigned char) data [characterIndex];
  3268. }
  3269. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  3270. CharPointer_ASCII operator+ (const int numToSkip) const noexcept
  3271. {
  3272. return CharPointer_ASCII (data + numToSkip);
  3273. }
  3274. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  3275. CharPointer_ASCII operator- (const int numToSkip) const noexcept
  3276. {
  3277. return CharPointer_ASCII (data - numToSkip);
  3278. }
  3279. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  3280. inline void write (const juce_wchar charToWrite) noexcept
  3281. {
  3282. *data++ = (char) charToWrite;
  3283. }
  3284. inline void replaceChar (const juce_wchar newChar) noexcept
  3285. {
  3286. *data = (char) newChar;
  3287. }
  3288. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  3289. inline void writeNull() const noexcept
  3290. {
  3291. *data = 0;
  3292. }
  3293. /** Returns the number of characters in this string. */
  3294. size_t length() const noexcept
  3295. {
  3296. return (size_t) strlen (data);
  3297. }
  3298. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  3299. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  3300. {
  3301. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  3302. }
  3303. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  3304. size_t lengthUpTo (const CharPointer_ASCII& end) const noexcept
  3305. {
  3306. return CharacterFunctions::lengthUpTo (*this, end);
  3307. }
  3308. /** Returns the number of bytes that are used to represent this string.
  3309. This includes the terminating null character.
  3310. */
  3311. size_t sizeInBytes() const noexcept
  3312. {
  3313. return length() + 1;
  3314. }
  3315. /** Returns the number of bytes that would be needed to represent the given
  3316. unicode character in this encoding format.
  3317. */
  3318. static inline size_t getBytesRequiredFor (const juce_wchar) noexcept
  3319. {
  3320. return 1;
  3321. }
  3322. /** Returns the number of bytes that would be needed to represent the given
  3323. string in this encoding format.
  3324. The value returned does NOT include the terminating null character.
  3325. */
  3326. template <class CharPointer>
  3327. static size_t getBytesRequiredFor (const CharPointer& text) noexcept
  3328. {
  3329. return text.length();
  3330. }
  3331. /** Returns a pointer to the null character that terminates this string. */
  3332. CharPointer_ASCII findTerminatingNull() const noexcept
  3333. {
  3334. return CharPointer_ASCII (data + length());
  3335. }
  3336. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3337. template <typename CharPointer>
  3338. void writeAll (const CharPointer& src) noexcept
  3339. {
  3340. CharacterFunctions::copyAll (*this, src);
  3341. }
  3342. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3343. void writeAll (const CharPointer_ASCII& src) noexcept
  3344. {
  3345. strcpy (data, src.data);
  3346. }
  3347. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3348. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3349. to the destination buffer before stopping.
  3350. */
  3351. template <typename CharPointer>
  3352. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  3353. {
  3354. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3355. }
  3356. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3357. The maxChars parameter specifies the maximum number of characters that can be
  3358. written to the destination buffer before stopping (including the terminating null).
  3359. */
  3360. template <typename CharPointer>
  3361. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  3362. {
  3363. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3364. }
  3365. /** Compares this string with another one. */
  3366. template <typename CharPointer>
  3367. int compare (const CharPointer& other) const noexcept
  3368. {
  3369. return CharacterFunctions::compare (*this, other);
  3370. }
  3371. /** Compares this string with another one. */
  3372. int compare (const CharPointer_ASCII& other) const noexcept
  3373. {
  3374. return strcmp (data, other.data);
  3375. }
  3376. /** Compares this string with another one, up to a specified number of characters. */
  3377. template <typename CharPointer>
  3378. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  3379. {
  3380. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3381. }
  3382. /** Compares this string with another one, up to a specified number of characters. */
  3383. int compareUpTo (const CharPointer_ASCII& other, const int maxChars) const noexcept
  3384. {
  3385. return strncmp (data, other.data, (size_t) maxChars);
  3386. }
  3387. /** Compares this string with another one. */
  3388. template <typename CharPointer>
  3389. int compareIgnoreCase (const CharPointer& other) const
  3390. {
  3391. return CharacterFunctions::compareIgnoreCase (*this, other);
  3392. }
  3393. int compareIgnoreCase (const CharPointer_ASCII& other) const
  3394. {
  3395. #if JUCE_WINDOWS
  3396. return stricmp (data, other.data);
  3397. #else
  3398. return strcasecmp (data, other.data);
  3399. #endif
  3400. }
  3401. /** Compares this string with another one, up to a specified number of characters. */
  3402. template <typename CharPointer>
  3403. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  3404. {
  3405. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3406. }
  3407. /** Returns the character index of a substring, or -1 if it isn't found. */
  3408. template <typename CharPointer>
  3409. int indexOf (const CharPointer& stringToFind) const noexcept
  3410. {
  3411. return CharacterFunctions::indexOf (*this, stringToFind);
  3412. }
  3413. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3414. int indexOf (const juce_wchar charToFind) const noexcept
  3415. {
  3416. int i = 0;
  3417. while (data[i] != 0)
  3418. {
  3419. if (data[i] == (char) charToFind)
  3420. return i;
  3421. ++i;
  3422. }
  3423. return -1;
  3424. }
  3425. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3426. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  3427. {
  3428. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3429. : CharacterFunctions::indexOfChar (*this, charToFind);
  3430. }
  3431. /** Returns true if the first character of this string is whitespace. */
  3432. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3433. /** Returns true if the first character of this string is a digit. */
  3434. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3435. /** Returns true if the first character of this string is a letter. */
  3436. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3437. /** Returns true if the first character of this string is a letter or digit. */
  3438. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3439. /** Returns true if the first character of this string is upper-case. */
  3440. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3441. /** Returns true if the first character of this string is lower-case. */
  3442. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3443. /** Returns an upper-case version of the first character of this string. */
  3444. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (*data); }
  3445. /** Returns a lower-case version of the first character of this string. */
  3446. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (*data); }
  3447. /** Parses this string as a 32-bit integer. */
  3448. int getIntValue32() const noexcept { return atoi (data); }
  3449. /** Parses this string as a 64-bit integer. */
  3450. int64 getIntValue64() const noexcept
  3451. {
  3452. #if JUCE_LINUX || JUCE_ANDROID
  3453. return atoll (data);
  3454. #elif JUCE_WINDOWS
  3455. return _atoi64 (data);
  3456. #else
  3457. return CharacterFunctions::getIntValue <int64, CharPointer_ASCII> (*this);
  3458. #endif
  3459. }
  3460. /** Parses this string as a floating point double. */
  3461. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  3462. /** Returns the first non-whitespace character in the string. */
  3463. CharPointer_ASCII findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  3464. /** Returns true if the given unicode character can be represented in this encoding. */
  3465. static bool canRepresent (juce_wchar character) noexcept
  3466. {
  3467. return ((unsigned int) character) < (unsigned int) 128;
  3468. }
  3469. /** Returns true if this data contains a valid string in this encoding. */
  3470. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3471. {
  3472. while (--maxBytesToRead >= 0)
  3473. {
  3474. if (((signed char) *dataToTest) <= 0)
  3475. return *dataToTest == 0;
  3476. ++dataToTest;
  3477. }
  3478. return true;
  3479. }
  3480. private:
  3481. CharType* data;
  3482. };
  3483. #endif // __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3484. /*** End of inlined file: juce_CharPointer_ASCII.h ***/
  3485. #if JUCE_MSVC
  3486. #pragma warning (pop)
  3487. #endif
  3488. class OutputStream;
  3489. /**
  3490. The JUCE String class!
  3491. Using a reference-counted internal representation, these strings are fast
  3492. and efficient, and there are methods to do just about any operation you'll ever
  3493. dream of.
  3494. @see StringArray, StringPairArray
  3495. */
  3496. class JUCE_API String
  3497. {
  3498. public:
  3499. /** Creates an empty string.
  3500. @see empty
  3501. */
  3502. String() noexcept;
  3503. /** Creates a copy of another string. */
  3504. String (const String& other) noexcept;
  3505. /** Creates a string from a zero-terminated ascii text string.
  3506. The string passed-in must not contain any characters with a value above 127, because
  3507. these can't be converted to unicode without knowing the original encoding that was
  3508. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3509. assertion.
  3510. To create strings with extended characters from UTF-8, you should explicitly call
  3511. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3512. use UTF-8 with escape characters in your source code to represent extended characters,
  3513. because there's no other way to represent unicode strings in a way that isn't dependent
  3514. on the compiler, source code editor and platform.
  3515. */
  3516. String (const char* text);
  3517. /** Creates a string from a string of 8-bit ascii characters.
  3518. The string passed-in must not contain any characters with a value above 127, because
  3519. these can't be converted to unicode without knowing the original encoding that was
  3520. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3521. assertion.
  3522. To create strings with extended characters from UTF-8, you should explicitly call
  3523. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3524. use UTF-8 with escape characters in your source code to represent extended characters,
  3525. because there's no other way to represent unicode strings in a way that isn't dependent
  3526. on the compiler, source code editor and platform.
  3527. This will use up the the first maxChars characters of the string (or less if the string
  3528. is actually shorter).
  3529. */
  3530. String (const char* text, size_t maxChars);
  3531. /** Creates a string from a whcar_t character string.
  3532. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3533. */
  3534. String (const wchar_t* text);
  3535. /** Creates a string from a whcar_t character string.
  3536. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3537. */
  3538. String (const wchar_t* text, size_t maxChars);
  3539. /** Creates a string from a UTF-8 character string */
  3540. String (const CharPointer_UTF8& text);
  3541. /** Creates a string from a UTF-8 character string */
  3542. String (const CharPointer_UTF8& text, size_t maxChars);
  3543. /** Creates a string from a UTF-8 character string */
  3544. String (const CharPointer_UTF8& start, const CharPointer_UTF8& end);
  3545. /** Creates a string from a UTF-16 character string */
  3546. String (const CharPointer_UTF16& text);
  3547. /** Creates a string from a UTF-16 character string */
  3548. String (const CharPointer_UTF16& text, size_t maxChars);
  3549. /** Creates a string from a UTF-16 character string */
  3550. String (const CharPointer_UTF16& start, const CharPointer_UTF16& end);
  3551. /** Creates a string from a UTF-32 character string */
  3552. String (const CharPointer_UTF32& text);
  3553. /** Creates a string from a UTF-32 character string */
  3554. String (const CharPointer_UTF32& text, size_t maxChars);
  3555. /** Creates a string from a UTF-32 character string */
  3556. String (const CharPointer_UTF32& start, const CharPointer_UTF32& end);
  3557. /** Creates a string from an ASCII character string */
  3558. String (const CharPointer_ASCII& text);
  3559. /** Creates a string from a single character. */
  3560. static const String charToString (juce_wchar character);
  3561. /** Destructor. */
  3562. ~String() noexcept;
  3563. /** This is an empty string that can be used whenever one is needed.
  3564. It's better to use this than String() because it explains what's going on
  3565. and is more efficient.
  3566. */
  3567. static const String empty;
  3568. /** This is the character encoding type used internally to store the string.
  3569. By setting the value of JUCE_STRING_UTF_TYPE to 8, 16, or 32, you can change the
  3570. internal storage format of the String class. UTF-8 uses the least space (if your strings
  3571. contain few extended characters), but call operator[] involves iterating the string to find
  3572. the required index. UTF-32 provides instant random access to its characters, but uses 4 bytes
  3573. per character to store them. UTF-16 uses more space than UTF-8 and is also slow to index,
  3574. but is the native wchar_t format used in Windows.
  3575. It doesn't matter too much which format you pick, because the toUTF8(), toUTF16() and
  3576. toUTF32() methods let you access the string's content in any of the other formats.
  3577. */
  3578. #if (JUCE_STRING_UTF_TYPE == 32)
  3579. typedef CharPointer_UTF32 CharPointerType;
  3580. #elif (JUCE_STRING_UTF_TYPE == 16)
  3581. typedef CharPointer_UTF16 CharPointerType;
  3582. #elif (JUCE_STRING_UTF_TYPE == 8)
  3583. typedef CharPointer_UTF8 CharPointerType;
  3584. #else
  3585. #error "You must set the value of JUCE_STRING_UTF_TYPE to be either 8, 16, or 32!"
  3586. #endif
  3587. /** Generates a probably-unique 32-bit hashcode from this string. */
  3588. int hashCode() const noexcept;
  3589. /** Generates a probably-unique 64-bit hashcode from this string. */
  3590. int64 hashCode64() const noexcept;
  3591. /** Returns the number of characters in the string. */
  3592. int length() const noexcept;
  3593. // Assignment and concatenation operators..
  3594. /** Replaces this string's contents with another string. */
  3595. String& operator= (const String& other) noexcept;
  3596. /** Appends another string at the end of this one. */
  3597. String& operator+= (const String& stringToAppend);
  3598. /** Appends another string at the end of this one. */
  3599. String& operator+= (const char* textToAppend);
  3600. /** Appends another string at the end of this one. */
  3601. String& operator+= (const wchar_t* textToAppend);
  3602. /** Appends a decimal number at the end of this string. */
  3603. String& operator+= (int numberToAppend);
  3604. /** Appends a character at the end of this string. */
  3605. String& operator+= (char characterToAppend);
  3606. /** Appends a character at the end of this string. */
  3607. String& operator+= (wchar_t characterToAppend);
  3608. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  3609. /** Appends a character at the end of this string. */
  3610. String& operator+= (juce_wchar characterToAppend);
  3611. #endif
  3612. /** Appends a string to the end of this one.
  3613. @param textToAppend the string to add
  3614. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3615. */
  3616. void append (const String& textToAppend, size_t maxCharsToTake);
  3617. /** Appends a string to the end of this one.
  3618. @param textToAppend the string to add
  3619. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3620. */
  3621. template <class CharPointer>
  3622. void appendCharPointer (const CharPointer& textToAppend, size_t maxCharsToTake)
  3623. {
  3624. if (textToAppend.getAddress() != nullptr)
  3625. {
  3626. size_t extraBytesNeeded = 0;
  3627. size_t numChars = 0;
  3628. for (CharPointer t (textToAppend); numChars < maxCharsToTake && ! t.isEmpty();)
  3629. {
  3630. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3631. ++numChars;
  3632. }
  3633. if (numChars > 0)
  3634. {
  3635. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3636. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3637. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeWithCharLimit (textToAppend, (int) (numChars + 1));
  3638. }
  3639. }
  3640. }
  3641. /** Appends a string to the end of this one. */
  3642. template <class CharPointer>
  3643. void appendCharPointer (const CharPointer& textToAppend)
  3644. {
  3645. if (textToAppend.getAddress() != nullptr)
  3646. {
  3647. size_t extraBytesNeeded = 0;
  3648. for (CharPointer t (textToAppend); ! t.isEmpty();)
  3649. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3650. if (extraBytesNeeded > 0)
  3651. {
  3652. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3653. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3654. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeAll (textToAppend);
  3655. }
  3656. }
  3657. }
  3658. // Comparison methods..
  3659. /** Returns true if the string contains no characters.
  3660. Note that there's also an isNotEmpty() method to help write readable code.
  3661. @see containsNonWhitespaceChars()
  3662. */
  3663. inline bool isEmpty() const noexcept { return text[0] == 0; }
  3664. /** Returns true if the string contains at least one character.
  3665. Note that there's also an isEmpty() method to help write readable code.
  3666. @see containsNonWhitespaceChars()
  3667. */
  3668. inline bool isNotEmpty() const noexcept { return text[0] != 0; }
  3669. /** Case-insensitive comparison with another string. */
  3670. bool equalsIgnoreCase (const String& other) const noexcept;
  3671. /** Case-insensitive comparison with another string. */
  3672. bool equalsIgnoreCase (const wchar_t* other) const noexcept;
  3673. /** Case-insensitive comparison with another string. */
  3674. bool equalsIgnoreCase (const char* other) const noexcept;
  3675. /** Case-sensitive comparison with another string.
  3676. @returns 0 if the two strings are identical; negative if this string comes before
  3677. the other one alphabetically, or positive if it comes after it.
  3678. */
  3679. int compare (const String& other) const noexcept;
  3680. /** Case-sensitive comparison with another string.
  3681. @returns 0 if the two strings are identical; negative if this string comes before
  3682. the other one alphabetically, or positive if it comes after it.
  3683. */
  3684. int compare (const char* other) const noexcept;
  3685. /** Case-sensitive comparison with another string.
  3686. @returns 0 if the two strings are identical; negative if this string comes before
  3687. the other one alphabetically, or positive if it comes after it.
  3688. */
  3689. int compare (const wchar_t* other) const noexcept;
  3690. /** Case-insensitive comparison with another string.
  3691. @returns 0 if the two strings are identical; negative if this string comes before
  3692. the other one alphabetically, or positive if it comes after it.
  3693. */
  3694. int compareIgnoreCase (const String& other) const noexcept;
  3695. /** Lexicographic comparison with another string.
  3696. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  3697. characters, making it good for sorting human-readable strings.
  3698. @returns 0 if the two strings are identical; negative if this string comes before
  3699. the other one alphabetically, or positive if it comes after it.
  3700. */
  3701. int compareLexicographically (const String& other) const noexcept;
  3702. /** Tests whether the string begins with another string.
  3703. If the parameter is an empty string, this will always return true.
  3704. Uses a case-sensitive comparison.
  3705. */
  3706. bool startsWith (const String& text) const noexcept;
  3707. /** Tests whether the string begins with a particular character.
  3708. If the character is 0, this will always return false.
  3709. Uses a case-sensitive comparison.
  3710. */
  3711. bool startsWithChar (juce_wchar character) const noexcept;
  3712. /** Tests whether the string begins with another string.
  3713. If the parameter is an empty string, this will always return true.
  3714. Uses a case-insensitive comparison.
  3715. */
  3716. bool startsWithIgnoreCase (const String& text) const noexcept;
  3717. /** Tests whether the string ends with another string.
  3718. If the parameter is an empty string, this will always return true.
  3719. Uses a case-sensitive comparison.
  3720. */
  3721. bool endsWith (const String& text) const noexcept;
  3722. /** Tests whether the string ends with a particular character.
  3723. If the character is 0, this will always return false.
  3724. Uses a case-sensitive comparison.
  3725. */
  3726. bool endsWithChar (juce_wchar character) const noexcept;
  3727. /** Tests whether the string ends with another string.
  3728. If the parameter is an empty string, this will always return true.
  3729. Uses a case-insensitive comparison.
  3730. */
  3731. bool endsWithIgnoreCase (const String& text) const noexcept;
  3732. /** Tests whether the string contains another substring.
  3733. If the parameter is an empty string, this will always return true.
  3734. Uses a case-sensitive comparison.
  3735. */
  3736. bool contains (const String& text) const noexcept;
  3737. /** Tests whether the string contains a particular character.
  3738. Uses a case-sensitive comparison.
  3739. */
  3740. bool containsChar (juce_wchar character) const noexcept;
  3741. /** Tests whether the string contains another substring.
  3742. Uses a case-insensitive comparison.
  3743. */
  3744. bool containsIgnoreCase (const String& text) const noexcept;
  3745. /** Tests whether the string contains another substring as a distict word.
  3746. @returns true if the string contains this word, surrounded by
  3747. non-alphanumeric characters
  3748. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3749. */
  3750. bool containsWholeWord (const String& wordToLookFor) const noexcept;
  3751. /** Tests whether the string contains another substring as a distict word.
  3752. @returns true if the string contains this word, surrounded by
  3753. non-alphanumeric characters
  3754. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3755. */
  3756. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const noexcept;
  3757. /** Finds an instance of another substring if it exists as a distict word.
  3758. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3759. then this will return the index of the start of the substring. If it isn't
  3760. found, then it will return -1
  3761. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3762. */
  3763. int indexOfWholeWord (const String& wordToLookFor) const noexcept;
  3764. /** Finds an instance of another substring if it exists as a distict word.
  3765. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3766. then this will return the index of the start of the substring. If it isn't
  3767. found, then it will return -1
  3768. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3769. */
  3770. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const noexcept;
  3771. /** Looks for any of a set of characters in the string.
  3772. Uses a case-sensitive comparison.
  3773. @returns true if the string contains any of the characters from
  3774. the string that is passed in.
  3775. */
  3776. bool containsAnyOf (const String& charactersItMightContain) const noexcept;
  3777. /** Looks for a set of characters in the string.
  3778. Uses a case-sensitive comparison.
  3779. @returns Returns false if any of the characters in this string do not occur in
  3780. the parameter string. If this string is empty, the return value will
  3781. always be true.
  3782. */
  3783. bool containsOnly (const String& charactersItMightContain) const noexcept;
  3784. /** Returns true if this string contains any non-whitespace characters.
  3785. This will return false if the string contains only whitespace characters, or
  3786. if it's empty.
  3787. It is equivalent to calling "myString.trim().isNotEmpty()".
  3788. */
  3789. bool containsNonWhitespaceChars() const noexcept;
  3790. /** Returns true if the string matches this simple wildcard expression.
  3791. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  3792. This isn't a full-blown regex though! The only wildcard characters supported
  3793. are "*" and "?". It's mainly intended for filename pattern matching.
  3794. */
  3795. bool matchesWildcard (const String& wildcard, bool ignoreCase) const noexcept;
  3796. // Substring location methods..
  3797. /** Searches for a character inside this string.
  3798. Uses a case-sensitive comparison.
  3799. @returns the index of the first occurrence of the character in this
  3800. string, or -1 if it's not found.
  3801. */
  3802. int indexOfChar (juce_wchar characterToLookFor) const noexcept;
  3803. /** Searches for a character inside this string.
  3804. Uses a case-sensitive comparison.
  3805. @param startIndex the index from which the search should proceed
  3806. @param characterToLookFor the character to look for
  3807. @returns the index of the first occurrence of the character in this
  3808. string, or -1 if it's not found.
  3809. */
  3810. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const noexcept;
  3811. /** Returns the index of the first character that matches one of the characters
  3812. passed-in to this method.
  3813. This scans the string, beginning from the startIndex supplied, and if it finds
  3814. a character that appears in the string charactersToLookFor, it returns its index.
  3815. If none of these characters are found, it returns -1.
  3816. If ignoreCase is true, the comparison will be case-insensitive.
  3817. @see indexOfChar, lastIndexOfAnyOf
  3818. */
  3819. int indexOfAnyOf (const String& charactersToLookFor,
  3820. int startIndex = 0,
  3821. bool ignoreCase = false) const noexcept;
  3822. /** Searches for a substring within this string.
  3823. Uses a case-sensitive comparison.
  3824. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3825. If textToLookFor is an empty string, this will always return 0.
  3826. */
  3827. int indexOf (const String& textToLookFor) const noexcept;
  3828. /** Searches for a substring within this string.
  3829. Uses a case-sensitive comparison.
  3830. @param startIndex the index from which the search should proceed
  3831. @param textToLookFor the string to search for
  3832. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3833. If textToLookFor is an empty string, this will always return -1.
  3834. */
  3835. int indexOf (int startIndex, const String& textToLookFor) const noexcept;
  3836. /** Searches for a substring within this string.
  3837. Uses a case-insensitive comparison.
  3838. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3839. If textToLookFor is an empty string, this will always return 0.
  3840. */
  3841. int indexOfIgnoreCase (const String& textToLookFor) const noexcept;
  3842. /** Searches for a substring within this string.
  3843. Uses a case-insensitive comparison.
  3844. @param startIndex the index from which the search should proceed
  3845. @param textToLookFor the string to search for
  3846. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3847. If textToLookFor is an empty string, this will always return -1.
  3848. */
  3849. int indexOfIgnoreCase (int startIndex, const String& textToLookFor) const noexcept;
  3850. /** Searches for a character inside this string (working backwards from the end of the string).
  3851. Uses a case-sensitive comparison.
  3852. @returns the index of the last occurrence of the character in this string, or -1 if it's not found.
  3853. */
  3854. int lastIndexOfChar (juce_wchar character) const noexcept;
  3855. /** Searches for a substring inside this string (working backwards from the end of the string).
  3856. Uses a case-sensitive comparison.
  3857. @returns the index of the start of the last occurrence of the substring within this string,
  3858. or -1 if it's not found. If textToLookFor is an empty string, this will always return -1.
  3859. */
  3860. int lastIndexOf (const String& textToLookFor) const noexcept;
  3861. /** Searches for a substring inside this string (working backwards from the end of the string).
  3862. Uses a case-insensitive comparison.
  3863. @returns the index of the start of the last occurrence of the substring within this string, or -1
  3864. if it's not found. If textToLookFor is an empty string, this will always return -1.
  3865. */
  3866. int lastIndexOfIgnoreCase (const String& textToLookFor) const noexcept;
  3867. /** Returns the index of the last character in this string that matches one of the
  3868. characters passed-in to this method.
  3869. This scans the string backwards, starting from its end, and if it finds
  3870. a character that appears in the string charactersToLookFor, it returns its index.
  3871. If none of these characters are found, it returns -1.
  3872. If ignoreCase is true, the comparison will be case-insensitive.
  3873. @see lastIndexOf, indexOfAnyOf
  3874. */
  3875. int lastIndexOfAnyOf (const String& charactersToLookFor,
  3876. bool ignoreCase = false) const noexcept;
  3877. // Substring extraction and manipulation methods..
  3878. /** Returns the character at this index in the string.
  3879. In a release build, no checks are made to see if the index is within a valid range, so be
  3880. careful! In a debug build, the index is checked and an assertion fires if it's out-of-range.
  3881. Also beware that depending on the encoding format that the string is using internally, this
  3882. method may execute in either O(1) or O(n) time, so be careful when using it in your algorithms.
  3883. If you're scanning through a string to inspect its characters, you should never use this operator
  3884. for random access, it's far more efficient to call getCharPointer() to return a pointer, and
  3885. then to use that to iterate the string.
  3886. @see getCharPointer
  3887. */
  3888. const juce_wchar operator[] (int index) const noexcept;
  3889. /** Returns the final character of the string.
  3890. If the string is empty this will return 0.
  3891. */
  3892. juce_wchar getLastCharacter() const noexcept;
  3893. /** Returns a subsection of the string.
  3894. If the range specified is beyond the limits of the string, as much as
  3895. possible is returned.
  3896. @param startIndex the index of the start of the substring needed
  3897. @param endIndex all characters from startIndex up to (but not including)
  3898. this index are returned
  3899. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  3900. */
  3901. const String substring (int startIndex, int endIndex) const;
  3902. /** Returns a section of the string, starting from a given position.
  3903. @param startIndex the first character to include. If this is beyond the end
  3904. of the string, an empty string is returned. If it is zero or
  3905. less, the whole string is returned.
  3906. @returns the substring from startIndex up to the end of the string
  3907. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  3908. */
  3909. const String substring (int startIndex) const;
  3910. /** Returns a version of this string with a number of characters removed
  3911. from the end.
  3912. @param numberToDrop the number of characters to drop from the end of the
  3913. string. If this is greater than the length of the string,
  3914. an empty string will be returned. If zero or less, the
  3915. original string will be returned.
  3916. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  3917. */
  3918. const String dropLastCharacters (int numberToDrop) const;
  3919. /** Returns a number of characters from the end of the string.
  3920. This returns the last numCharacters characters from the end of the string. If the
  3921. string is shorter than numCharacters, the whole string is returned.
  3922. @see substring, dropLastCharacters, getLastCharacter
  3923. */
  3924. const String getLastCharacters (int numCharacters) const;
  3925. /** Returns a section of the string starting from a given substring.
  3926. This will search for the first occurrence of the given substring, and
  3927. return the section of the string starting from the point where this is
  3928. found (optionally not including the substring itself).
  3929. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  3930. fromFirstOccurrenceOf ("34", false) would return "56".
  3931. If the substring isn't found, the method will return an empty string.
  3932. If ignoreCase is true, the comparison will be case-insensitive.
  3933. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  3934. */
  3935. const String fromFirstOccurrenceOf (const String& substringToStartFrom,
  3936. bool includeSubStringInResult,
  3937. bool ignoreCase) const;
  3938. /** Returns a section of the string starting from the last occurrence of a given substring.
  3939. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  3940. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  3941. return the whole of the original string.
  3942. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  3943. */
  3944. const String fromLastOccurrenceOf (const String& substringToFind,
  3945. bool includeSubStringInResult,
  3946. bool ignoreCase) const;
  3947. /** Returns the start of this string, up to the first occurrence of a substring.
  3948. This will search for the first occurrence of a given substring, and then
  3949. return a copy of the string, up to the position of this substring,
  3950. optionally including or excluding the substring itself in the result.
  3951. e.g. for the string "123456", upTo ("34", false) would return "12", and
  3952. upTo ("34", true) would return "1234".
  3953. If the substring isn't found, this will return the whole of the original string.
  3954. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  3955. */
  3956. const String upToFirstOccurrenceOf (const String& substringToEndWith,
  3957. bool includeSubStringInResult,
  3958. bool ignoreCase) const;
  3959. /** Returns the start of this string, up to the last occurrence of a substring.
  3960. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  3961. If the substring isn't found, this will return the whole of the original string.
  3962. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  3963. */
  3964. const String upToLastOccurrenceOf (const String& substringToFind,
  3965. bool includeSubStringInResult,
  3966. bool ignoreCase) const;
  3967. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  3968. const String trim() const;
  3969. /** Returns a copy of this string with any whitespace characters removed from the start. */
  3970. const String trimStart() const;
  3971. /** Returns a copy of this string with any whitespace characters removed from the end. */
  3972. const String trimEnd() const;
  3973. /** Returns a copy of this string, having removed a specified set of characters from its start.
  3974. Characters are removed from the start of the string until it finds one that is not in the
  3975. specified set, and then it stops.
  3976. @param charactersToTrim the set of characters to remove.
  3977. @see trim, trimStart, trimCharactersAtEnd
  3978. */
  3979. const String trimCharactersAtStart (const String& charactersToTrim) const;
  3980. /** Returns a copy of this string, having removed a specified set of characters from its end.
  3981. Characters are removed from the end of the string until it finds one that is not in the
  3982. specified set, and then it stops.
  3983. @param charactersToTrim the set of characters to remove.
  3984. @see trim, trimEnd, trimCharactersAtStart
  3985. */
  3986. const String trimCharactersAtEnd (const String& charactersToTrim) const;
  3987. /** Returns an upper-case version of this string. */
  3988. const String toUpperCase() const;
  3989. /** Returns an lower-case version of this string. */
  3990. const String toLowerCase() const;
  3991. /** Replaces a sub-section of the string with another string.
  3992. This will return a copy of this string, with a set of characters
  3993. from startIndex to startIndex + numCharsToReplace removed, and with
  3994. a new string inserted in their place.
  3995. Note that this is a const method, and won't alter the string itself.
  3996. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  3997. it will be constrained to a valid range.
  3998. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  3999. characters will be taken out.
  4000. @param stringToInsert the new string to insert at startIndex after the characters have been
  4001. removed.
  4002. */
  4003. const String replaceSection (int startIndex,
  4004. int numCharactersToReplace,
  4005. const String& stringToInsert) const;
  4006. /** Replaces all occurrences of a substring with another string.
  4007. Returns a copy of this string, with any occurrences of stringToReplace
  4008. swapped for stringToInsertInstead.
  4009. Note that this is a const method, and won't alter the string itself.
  4010. */
  4011. const String replace (const String& stringToReplace,
  4012. const String& stringToInsertInstead,
  4013. bool ignoreCase = false) const;
  4014. /** Returns a string with all occurrences of a character replaced with a different one. */
  4015. const String replaceCharacter (juce_wchar characterToReplace,
  4016. juce_wchar characterToInsertInstead) const;
  4017. /** Replaces a set of characters with another set.
  4018. Returns a string in which each character from charactersToReplace has been replaced
  4019. by the character at the equivalent position in newCharacters (so the two strings
  4020. passed in must be the same length).
  4021. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  4022. Note that this is a const method, and won't affect the string itself.
  4023. */
  4024. const String replaceCharacters (const String& charactersToReplace,
  4025. const String& charactersToInsertInstead) const;
  4026. /** Returns a version of this string that only retains a fixed set of characters.
  4027. This will return a copy of this string, omitting any characters which are not
  4028. found in the string passed-in.
  4029. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  4030. Note that this is a const method, and won't alter the string itself.
  4031. */
  4032. const String retainCharacters (const String& charactersToRetain) const;
  4033. /** Returns a version of this string with a set of characters removed.
  4034. This will return a copy of this string, omitting any characters which are
  4035. found in the string passed-in.
  4036. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  4037. Note that this is a const method, and won't alter the string itself.
  4038. */
  4039. const String removeCharacters (const String& charactersToRemove) const;
  4040. /** Returns a section from the start of the string that only contains a certain set of characters.
  4041. This returns the leftmost section of the string, up to (and not including) the
  4042. first character that doesn't appear in the string passed in.
  4043. */
  4044. const String initialSectionContainingOnly (const String& permittedCharacters) const;
  4045. /** Returns a section from the start of the string that only contains a certain set of characters.
  4046. This returns the leftmost section of the string, up to (and not including) the
  4047. first character that occurs in the string passed in. (If none of the specified
  4048. characters are found in the string, the return value will just be the original string).
  4049. */
  4050. const String initialSectionNotContaining (const String& charactersToStopAt) const;
  4051. /** Checks whether the string might be in quotation marks.
  4052. @returns true if the string begins with a quote character (either a double or single quote).
  4053. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  4054. @see unquoted, quoted
  4055. */
  4056. bool isQuotedString() const;
  4057. /** Removes quotation marks from around the string, (if there are any).
  4058. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  4059. at the ends of the string are not affected. If there aren't any quotes, the original string
  4060. is returned.
  4061. Note that this is a const method, and won't alter the string itself.
  4062. @see isQuotedString, quoted
  4063. */
  4064. const String unquoted() const;
  4065. /** Adds quotation marks around a string.
  4066. This will return a copy of the string with a quote at the start and end, (but won't
  4067. add the quote if there's already one there, so it's safe to call this on strings that
  4068. may already have quotes around them).
  4069. Note that this is a const method, and won't alter the string itself.
  4070. @param quoteCharacter the character to add at the start and end
  4071. @see isQuotedString, unquoted
  4072. */
  4073. const String quoted (juce_wchar quoteCharacter = '"') const;
  4074. /** Creates a string which is a version of a string repeated and joined together.
  4075. @param stringToRepeat the string to repeat
  4076. @param numberOfTimesToRepeat how many times to repeat it
  4077. */
  4078. static const String repeatedString (const String& stringToRepeat,
  4079. int numberOfTimesToRepeat);
  4080. /** Returns a copy of this string with the specified character repeatedly added to its
  4081. beginning until the total length is at least the minimum length specified.
  4082. */
  4083. const String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  4084. /** Returns a copy of this string with the specified character repeatedly added to its
  4085. end until the total length is at least the minimum length specified.
  4086. */
  4087. const String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  4088. /** Creates a string from data in an unknown format.
  4089. This looks at some binary data and tries to guess whether it's Unicode
  4090. or 8-bit characters, then returns a string that represents it correctly.
  4091. Should be able to handle Unicode endianness correctly, by looking at
  4092. the first two bytes.
  4093. */
  4094. static const String createStringFromData (const void* data, int size);
  4095. /** Creates a String from a printf-style parameter list.
  4096. I don't like this method. I don't use it myself, and I recommend avoiding it and
  4097. using the operator<< methods or pretty much anything else instead. It's only provided
  4098. here because of the popular unrest that was stirred-up when I tried to remove it...
  4099. If you're really determined to use it, at least make sure that you never, ever,
  4100. pass any String objects to it as parameters. And bear in mind that internally, depending
  4101. on the platform, it may be using wchar_t or char character types, so that even string
  4102. literals can't be safely used as parameters if you're writing portable code.
  4103. */
  4104. static const String formatted (const String formatString, ... );
  4105. // Numeric conversions..
  4106. /** Creates a string containing this signed 32-bit integer as a decimal number.
  4107. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4108. */
  4109. explicit String (int decimalInteger);
  4110. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  4111. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4112. */
  4113. explicit String (unsigned int decimalInteger);
  4114. /** Creates a string containing this signed 16-bit integer as a decimal number.
  4115. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4116. */
  4117. explicit String (short decimalInteger);
  4118. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  4119. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4120. */
  4121. explicit String (unsigned short decimalInteger);
  4122. /** Creates a string containing this signed 64-bit integer as a decimal number.
  4123. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4124. */
  4125. explicit String (int64 largeIntegerValue);
  4126. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  4127. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4128. */
  4129. explicit String (uint64 largeIntegerValue);
  4130. /** Creates a string representing this floating-point number.
  4131. @param floatValue the value to convert to a string
  4132. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4133. decimal places, and will not use exponent notation. If 0 or
  4134. less, it will use exponent notation if necessary.
  4135. @see getDoubleValue, getIntValue
  4136. */
  4137. explicit String (float floatValue,
  4138. int numberOfDecimalPlaces = 0);
  4139. /** Creates a string representing this floating-point number.
  4140. @param doubleValue the value to convert to a string
  4141. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4142. decimal places, and will not use exponent notation. If 0 or
  4143. less, it will use exponent notation if necessary.
  4144. @see getFloatValue, getIntValue
  4145. */
  4146. explicit String (double doubleValue,
  4147. int numberOfDecimalPlaces = 0);
  4148. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  4149. @returns the value of the string as a 32 bit signed base-10 integer.
  4150. @see getTrailingIntValue, getHexValue32, getHexValue64
  4151. */
  4152. int getIntValue() const noexcept;
  4153. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  4154. @returns the value of the string as a 64 bit signed base-10 integer.
  4155. */
  4156. int64 getLargeIntValue() const noexcept;
  4157. /** Parses a decimal number from the end of the string.
  4158. This will look for a value at the end of the string.
  4159. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  4160. Negative numbers are not handled, so "xyz-5" returns 5.
  4161. @see getIntValue
  4162. */
  4163. int getTrailingIntValue() const noexcept;
  4164. /** Parses this string as a floating point number.
  4165. @returns the value of the string as a 32-bit floating point value.
  4166. @see getDoubleValue
  4167. */
  4168. float getFloatValue() const noexcept;
  4169. /** Parses this string as a floating point number.
  4170. @returns the value of the string as a 64-bit floating point value.
  4171. @see getFloatValue
  4172. */
  4173. double getDoubleValue() const noexcept;
  4174. /** Parses the string as a hexadecimal number.
  4175. Non-hexadecimal characters in the string are ignored.
  4176. If the string contains too many characters, then the lowest significant
  4177. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  4178. @returns a 32-bit number which is the value of the string in hex.
  4179. */
  4180. int getHexValue32() const noexcept;
  4181. /** Parses the string as a hexadecimal number.
  4182. Non-hexadecimal characters in the string are ignored.
  4183. If the string contains too many characters, then the lowest significant
  4184. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  4185. @returns a 64-bit number which is the value of the string in hex.
  4186. */
  4187. int64 getHexValue64() const noexcept;
  4188. /** Creates a string representing this 32-bit value in hexadecimal. */
  4189. static const String toHexString (int number);
  4190. /** Creates a string representing this 64-bit value in hexadecimal. */
  4191. static const String toHexString (int64 number);
  4192. /** Creates a string representing this 16-bit value in hexadecimal. */
  4193. static const String toHexString (short number);
  4194. /** Creates a string containing a hex dump of a block of binary data.
  4195. @param data the binary data to use as input
  4196. @param size how many bytes of data to use
  4197. @param groupSize how many bytes are grouped together before inserting a
  4198. space into the output. e.g. group size 0 has no spaces,
  4199. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  4200. like "bea1 c2ff".
  4201. */
  4202. static const String toHexString (const unsigned char* data,
  4203. int size,
  4204. int groupSize = 1);
  4205. /** Returns the character pointer currently being used to store this string.
  4206. Because it returns a reference to the string's internal data, the pointer
  4207. that is returned must not be stored anywhere, as it can be deleted whenever the
  4208. string changes.
  4209. */
  4210. inline const CharPointerType& getCharPointer() const noexcept { return text; }
  4211. /** Returns a pointer to a UTF-8 version of this string.
  4212. Because it returns a reference to the string's internal data, the pointer
  4213. that is returned must not be stored anywhere, as it can be deleted whenever the
  4214. string changes.
  4215. To find out how many bytes you need to store this string as UTF-8, you can call
  4216. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4217. @see getCharPointer, toUTF16, toUTF32
  4218. */
  4219. const CharPointer_UTF8 toUTF8() const;
  4220. /** Returns a pointer to a UTF-32 version of this string.
  4221. Because it returns a reference to the string's internal data, the pointer
  4222. that is returned must not be stored anywhere, as it can be deleted whenever the
  4223. string changes.
  4224. To find out how many bytes you need to store this string as UTF-16, you can call
  4225. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4226. @see getCharPointer, toUTF8, toUTF32
  4227. */
  4228. CharPointer_UTF16 toUTF16() const;
  4229. /** Returns a pointer to a UTF-32 version of this string.
  4230. Because it returns a reference to the string's internal data, the pointer
  4231. that is returned must not be stored anywhere, as it can be deleted whenever the
  4232. string changes.
  4233. @see getCharPointer, toUTF8, toUTF16
  4234. */
  4235. CharPointer_UTF32 toUTF32() const;
  4236. /** Returns a pointer to a wchar_t version of this string.
  4237. Because it returns a reference to the string's internal data, the pointer
  4238. that is returned must not be stored anywhere, as it can be deleted whenever the
  4239. string changes.
  4240. Bear in mind that the wchar_t type is different on different platforms, so on
  4241. Windows, this will be equivalent to calling toUTF16(), on unix it'll be the same
  4242. as calling toUTF32(), etc.
  4243. @see getCharPointer, toUTF8, toUTF16, toUTF32
  4244. */
  4245. const wchar_t* toWideCharPointer() const;
  4246. /** Creates a String from a UTF-8 encoded buffer.
  4247. If the size is < 0, it'll keep reading until it hits a zero.
  4248. */
  4249. static const String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  4250. /** Returns the number of bytes required to represent this string as UTF8.
  4251. The number returned does NOT include the trailing zero.
  4252. @see toUTF8, copyToUTF8
  4253. */
  4254. int getNumBytesAsUTF8() const noexcept;
  4255. /** Copies the string to a buffer as UTF-8 characters.
  4256. Returns the number of bytes copied to the buffer, including the terminating null
  4257. character.
  4258. To find out how many bytes you need to store this string as UTF-8, you can call
  4259. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4260. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4261. returns the number of bytes required (including the terminating null character).
  4262. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4263. put in as many as it can while still allowing for a terminating null char at the
  4264. end, and will return the number of bytes that were actually used.
  4265. @see CharPointer_UTF8::writeWithDestByteLimit
  4266. */
  4267. int copyToUTF8 (CharPointer_UTF8::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4268. /** Copies the string to a buffer as UTF-16 characters.
  4269. Returns the number of bytes copied to the buffer, including the terminating null
  4270. character.
  4271. To find out how many bytes you need to store this string as UTF-16, you can call
  4272. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4273. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4274. returns the number of bytes required (including the terminating null character).
  4275. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4276. put in as many as it can while still allowing for a terminating null char at the
  4277. end, and will return the number of bytes that were actually used.
  4278. @see CharPointer_UTF16::writeWithDestByteLimit
  4279. */
  4280. int copyToUTF16 (CharPointer_UTF16::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4281. /** Copies the string to a buffer as UTF-16 characters.
  4282. Returns the number of bytes copied to the buffer, including the terminating null
  4283. character.
  4284. To find out how many bytes you need to store this string as UTF-32, you can call
  4285. CharPointer_UTF32::getBytesRequiredFor (myString.getCharPointer())
  4286. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4287. returns the number of bytes required (including the terminating null character).
  4288. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4289. put in as many as it can while still allowing for a terminating null char at the
  4290. end, and will return the number of bytes that were actually used.
  4291. @see CharPointer_UTF32::writeWithDestByteLimit
  4292. */
  4293. int copyToUTF32 (CharPointer_UTF32::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4294. /** Increases the string's internally allocated storage.
  4295. Although the string's contents won't be affected by this call, it will
  4296. increase the amount of memory allocated internally for the string to grow into.
  4297. If you're about to make a large number of calls to methods such
  4298. as += or <<, it's more efficient to preallocate enough extra space
  4299. beforehand, so that these methods won't have to keep resizing the string
  4300. to append the extra characters.
  4301. @param numBytesNeeded the number of bytes to allocate storage for. If this
  4302. value is less than the currently allocated size, it will
  4303. have no effect.
  4304. */
  4305. void preallocateBytes (size_t numBytesNeeded);
  4306. /** Swaps the contents of this string with another one.
  4307. This is a very fast operation, as no allocation or copying needs to be done.
  4308. */
  4309. void swapWith (String& other) noexcept;
  4310. /** A helper class to improve performance when concatenating many large strings
  4311. together.
  4312. Because appending one string to another involves measuring the length of
  4313. both strings, repeatedly doing this for many long strings will become
  4314. an exponentially slow operation. This class uses some internal state to
  4315. avoid that, so that each append operation only needs to measure the length
  4316. of the appended string.
  4317. */
  4318. class JUCE_API Concatenator
  4319. {
  4320. public:
  4321. Concatenator (String& stringToAppendTo);
  4322. ~Concatenator();
  4323. void append (const String& s);
  4324. private:
  4325. String& result;
  4326. int nextIndex;
  4327. JUCE_DECLARE_NON_COPYABLE (Concatenator);
  4328. };
  4329. private:
  4330. CharPointerType text;
  4331. struct PreallocationBytes
  4332. {
  4333. explicit PreallocationBytes (size_t);
  4334. size_t numBytes;
  4335. };
  4336. explicit String (const PreallocationBytes&); // This constructor preallocates a certain amount of memory
  4337. void appendFixedLength (const char* text, int numExtraChars);
  4338. size_t getByteOffsetOfEnd() const noexcept;
  4339. JUCE_DEPRECATED (String (const String& stringToCopy, size_t charsToAllocate));
  4340. // This private cast operator should prevent strings being accidentally cast
  4341. // to bools (this is possible because the compiler can add an implicit cast
  4342. // via a const char*)
  4343. operator bool() const noexcept { return false; }
  4344. };
  4345. /** Concatenates two strings. */
  4346. JUCE_API const String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
  4347. /** Concatenates two strings. */
  4348. JUCE_API const String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2);
  4349. /** Concatenates two strings. */
  4350. JUCE_API const String JUCE_CALLTYPE operator+ (char string1, const String& string2);
  4351. /** Concatenates two strings. */
  4352. JUCE_API const String JUCE_CALLTYPE operator+ (wchar_t string1, const String& string2);
  4353. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4354. /** Concatenates two strings. */
  4355. JUCE_API const String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
  4356. #endif
  4357. /** Concatenates two strings. */
  4358. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2);
  4359. /** Concatenates two strings. */
  4360. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* string2);
  4361. /** Concatenates two strings. */
  4362. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2);
  4363. /** Concatenates two strings. */
  4364. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
  4365. /** Concatenates two strings. */
  4366. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, wchar_t characterToAppend);
  4367. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4368. /** Concatenates two strings. */
  4369. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
  4370. #endif
  4371. /** Appends a character at the end of a string. */
  4372. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
  4373. /** Appends a character at the end of a string. */
  4374. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, wchar_t characterToAppend);
  4375. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4376. /** Appends a character at the end of a string. */
  4377. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
  4378. #endif
  4379. /** Appends a string to the end of the first one. */
  4380. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
  4381. /** Appends a string to the end of the first one. */
  4382. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const wchar_t* string2);
  4383. /** Appends a string to the end of the first one. */
  4384. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
  4385. /** Appends a decimal number at the end of a string. */
  4386. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, short number);
  4387. /** Appends a decimal number at the end of a string. */
  4388. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, int number);
  4389. /** Appends a decimal number at the end of a string. */
  4390. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, long number);
  4391. /** Appends a decimal number at the end of a string. */
  4392. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, float number);
  4393. /** Appends a decimal number at the end of a string. */
  4394. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, double number);
  4395. /** Case-sensitive comparison of two strings. */
  4396. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) noexcept;
  4397. /** Case-sensitive comparison of two strings. */
  4398. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) noexcept;
  4399. /** Case-sensitive comparison of two strings. */
  4400. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const wchar_t* string2) noexcept;
  4401. /** Case-sensitive comparison of two strings. */
  4402. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) noexcept;
  4403. /** Case-sensitive comparison of two strings. */
  4404. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) noexcept;
  4405. /** Case-sensitive comparison of two strings. */
  4406. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) noexcept;
  4407. /** Case-sensitive comparison of two strings. */
  4408. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) noexcept;
  4409. /** Case-sensitive comparison of two strings. */
  4410. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) noexcept;
  4411. /** Case-sensitive comparison of two strings. */
  4412. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const wchar_t* string2) noexcept;
  4413. /** Case-sensitive comparison of two strings. */
  4414. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) noexcept;
  4415. /** Case-sensitive comparison of two strings. */
  4416. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) noexcept;
  4417. /** Case-sensitive comparison of two strings. */
  4418. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) noexcept;
  4419. /** Case-sensitive comparison of two strings. */
  4420. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) noexcept;
  4421. /** Case-sensitive comparison of two strings. */
  4422. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) noexcept;
  4423. /** Case-sensitive comparison of two strings. */
  4424. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) noexcept;
  4425. /** Case-sensitive comparison of two strings. */
  4426. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) noexcept;
  4427. /** This operator allows you to write a juce String directly to std output streams.
  4428. This is handy for writing strings to std::cout, std::cerr, etc.
  4429. */
  4430. template <class traits>
  4431. std::basic_ostream <char, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <char, traits>& stream, const String& stringToWrite)
  4432. {
  4433. return stream << stringToWrite.toUTF8().getAddress();
  4434. }
  4435. /** This operator allows you to write a juce String directly to std output streams.
  4436. This is handy for writing strings to std::wcout, std::wcerr, etc.
  4437. */
  4438. template <class traits>
  4439. std::basic_ostream <wchar_t, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <wchar_t, traits>& stream, const String& stringToWrite)
  4440. {
  4441. return stream << stringToWrite.toWideCharPointer();
  4442. }
  4443. /** Writes a string to an OutputStream as UTF8. */
  4444. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& stringToWrite);
  4445. #endif // __JUCE_STRING_JUCEHEADER__
  4446. /*** End of inlined file: juce_String.h ***/
  4447. /**
  4448. Acts as an application-wide logging class.
  4449. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  4450. method and this will then be used by all calls to writeToLog.
  4451. The logger class also contains methods for writing messages to the debugger's
  4452. output stream.
  4453. @see FileLogger
  4454. */
  4455. class JUCE_API Logger
  4456. {
  4457. public:
  4458. /** Destructor. */
  4459. virtual ~Logger();
  4460. /** Sets the current logging class to use.
  4461. Note that the object passed in won't be deleted when no longer needed.
  4462. A null pointer can be passed-in to disable any logging.
  4463. If deleteOldLogger is set to true, the existing logger will be
  4464. deleted (if there is one).
  4465. */
  4466. static void JUCE_CALLTYPE setCurrentLogger (Logger* newLogger,
  4467. bool deleteOldLogger = false);
  4468. /** Writes a string to the current logger.
  4469. This will pass the string to the logger's logMessage() method if a logger
  4470. has been set.
  4471. @see logMessage
  4472. */
  4473. static void JUCE_CALLTYPE writeToLog (const String& message);
  4474. /** Writes a message to the standard error stream.
  4475. This can be called directly, or by using the DBG() macro in
  4476. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  4477. */
  4478. static void JUCE_CALLTYPE outputDebugString (const String& text);
  4479. protected:
  4480. Logger();
  4481. /** This is overloaded by subclasses to implement custom logging behaviour.
  4482. @see setCurrentLogger
  4483. */
  4484. virtual void logMessage (const String& message) = 0;
  4485. private:
  4486. static Logger* currentLogger;
  4487. };
  4488. #endif // __JUCE_LOGGER_JUCEHEADER__
  4489. /*** End of inlined file: juce_Logger.h ***/
  4490. /*** Start of inlined file: juce_LeakedObjectDetector.h ***/
  4491. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4492. #define __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4493. /**
  4494. Embedding an instance of this class inside another class can be used as a low-overhead
  4495. way of detecting leaked instances.
  4496. This class keeps an internal static count of the number of instances that are
  4497. active, so that when the app is shutdown and the static destructors are called,
  4498. it can check whether there are any left-over instances that may have been leaked.
  4499. To use it, use the JUCE_LEAK_DETECTOR macro as a simple way to put one in your
  4500. class declaration. Have a look through the juce codebase for examples, it's used
  4501. in most of the classes.
  4502. */
  4503. template <class OwnerClass>
  4504. class LeakedObjectDetector
  4505. {
  4506. public:
  4507. LeakedObjectDetector() noexcept { ++(getCounter().numObjects); }
  4508. LeakedObjectDetector (const LeakedObjectDetector&) noexcept { ++(getCounter().numObjects); }
  4509. ~LeakedObjectDetector()
  4510. {
  4511. if (--(getCounter().numObjects) < 0)
  4512. {
  4513. DBG ("*** Dangling pointer deletion! Class: " << getLeakedObjectClassName());
  4514. /** If you hit this, then you've managed to delete more instances of this class than you've
  4515. created.. That indicates that you're deleting some dangling pointers.
  4516. Note that although this assertion will have been triggered during a destructor, it might
  4517. not be this particular deletion that's at fault - the incorrect one may have happened
  4518. at an earlier point in the program, and simply not been detected until now.
  4519. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  4520. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4521. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4522. */
  4523. jassertfalse;
  4524. }
  4525. }
  4526. private:
  4527. class LeakCounter
  4528. {
  4529. public:
  4530. LeakCounter() noexcept {}
  4531. ~LeakCounter()
  4532. {
  4533. if (numObjects.value > 0)
  4534. {
  4535. DBG ("*** Leaked objects detected: " << numObjects.value << " instance(s) of class " << getLeakedObjectClassName());
  4536. /** If you hit this, then you've leaked one or more objects of the type specified by
  4537. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  4538. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  4539. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4540. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4541. */
  4542. jassertfalse;
  4543. }
  4544. }
  4545. Atomic<int> numObjects;
  4546. };
  4547. static const char* getLeakedObjectClassName()
  4548. {
  4549. return OwnerClass::getLeakedObjectClassName();
  4550. }
  4551. static LeakCounter& getCounter() noexcept
  4552. {
  4553. static LeakCounter counter;
  4554. return counter;
  4555. }
  4556. };
  4557. #if DOXYGEN || ! defined (JUCE_LEAK_DETECTOR)
  4558. #if (DOXYGEN || JUCE_CHECK_MEMORY_LEAKS)
  4559. /** This macro lets you embed a leak-detecting object inside a class.
  4560. To use it, simply declare a JUCE_LEAK_DETECTOR(YourClassName) inside a private section
  4561. of the class declaration. E.g.
  4562. @code
  4563. class MyClass
  4564. {
  4565. public:
  4566. MyClass();
  4567. void blahBlah();
  4568. private:
  4569. JUCE_LEAK_DETECTOR (MyClass);
  4570. };@endcode
  4571. @see JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR, LeakedObjectDetector
  4572. */
  4573. #define JUCE_LEAK_DETECTOR(OwnerClass) \
  4574. friend class JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass>; \
  4575. static const char* getLeakedObjectClassName() noexcept { return #OwnerClass; } \
  4576. JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass> JUCE_JOIN_MACRO (leakDetector, __LINE__);
  4577. #else
  4578. #define JUCE_LEAK_DETECTOR(OwnerClass)
  4579. #endif
  4580. #endif
  4581. #endif // __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4582. /*** End of inlined file: juce_LeakedObjectDetector.h ***/
  4583. END_JUCE_NAMESPACE
  4584. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  4585. /*** End of inlined file: juce_StandardHeader.h ***/
  4586. BEGIN_JUCE_NAMESPACE
  4587. #if JUCE_MSVC
  4588. // this is set explicitly in case the app is using a different packing size.
  4589. #pragma pack (push, 8)
  4590. #pragma warning (push)
  4591. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  4592. #ifdef __INTEL_COMPILER
  4593. #pragma warning (disable: 1125)
  4594. #endif
  4595. #endif
  4596. // this is where all the class header files get brought in..
  4597. /*** Start of inlined file: juce_core_includes.h ***/
  4598. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4599. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4600. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4601. /*** Start of inlined file: juce_AbstractFifo.h ***/
  4602. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4603. #define __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4604. /**
  4605. Encapsulates the logic required to implement a lock-free FIFO.
  4606. This class handles the logic needed when building a single-reader, single-writer FIFO.
  4607. It doesn't actually hold any data itself, but your FIFO class can use one of these to manage
  4608. its position and status when reading or writing to it.
  4609. To use it, you can call prepareToWrite() to determine the position within your own buffer that
  4610. an incoming block of data should be stored, and prepareToRead() to find out when the next
  4611. outgoing block should be read from.
  4612. e.g.
  4613. @code
  4614. class MyFifo
  4615. {
  4616. public:
  4617. MyFifo() : abstractFifo (1024)
  4618. {
  4619. }
  4620. void addToFifo (const int* someData, int numItems)
  4621. {
  4622. int start1, size1, start2, size2;
  4623. prepareToWrite (numItems, start1, size1, start2, size2);
  4624. if (size1 > 0)
  4625. copySomeData (myBuffer + start1, someData, size1);
  4626. if (size2 > 0)
  4627. copySomeData (myBuffer + start2, someData + size1, size2);
  4628. finishedWrite (size1 + size2);
  4629. }
  4630. void readFromFifo (int* someData, int numItems)
  4631. {
  4632. int start1, size1, start2, size2;
  4633. prepareToRead (numSamples, start1, size1, start2, size2);
  4634. if (size1 > 0)
  4635. copySomeData (someData, myBuffer + start1, size1);
  4636. if (size2 > 0)
  4637. copySomeData (someData + size1, myBuffer + start2, size2);
  4638. finishedRead (size1 + size2);
  4639. }
  4640. private:
  4641. AbstractFifo abstractFifo;
  4642. int myBuffer [1024];
  4643. };
  4644. @endcode
  4645. */
  4646. class JUCE_API AbstractFifo
  4647. {
  4648. public:
  4649. /** Creates a FIFO to manage a buffer with the specified capacity. */
  4650. AbstractFifo (int capacity) noexcept;
  4651. /** Destructor */
  4652. ~AbstractFifo();
  4653. /** Returns the total size of the buffer being managed. */
  4654. int getTotalSize() const noexcept;
  4655. /** Returns the number of items that can currently be added to the buffer without it overflowing. */
  4656. int getFreeSpace() const noexcept;
  4657. /** Returns the number of items that can currently be read from the buffer. */
  4658. int getNumReady() const noexcept;
  4659. /** Clears the buffer positions, so that it appears empty. */
  4660. void reset() noexcept;
  4661. /** Changes the buffer's total size.
  4662. Note that this isn't thread-safe, so don't call it if there's any danger that it
  4663. might overlap with a call to any other method in this class!
  4664. */
  4665. void setTotalSize (int newSize) noexcept;
  4666. /** Returns the location within the buffer at which an incoming block of data should be written.
  4667. Because the section of data that you want to add to the buffer may overlap the end
  4668. and wrap around to the start, two blocks within your buffer are returned, and you
  4669. should copy your data into the first one, with any remaining data spilling over into
  4670. the second.
  4671. If the number of items you ask for is too large to fit within the buffer's free space, then
  4672. blockSize1 + blockSize2 may add up to a lower value than numToWrite. If this happens, you
  4673. may decide to keep waiting and re-trying the method until there's enough space available.
  4674. After calling this method, if you choose to write your data into the blocks returned, you
  4675. must call finishedWrite() to tell the FIFO how much data you actually added.
  4676. e.g.
  4677. @code
  4678. void addToFifo (const int* someData, int numItems)
  4679. {
  4680. int start1, size1, start2, size2;
  4681. prepareToWrite (numItems, start1, size1, start2, size2);
  4682. if (size1 > 0)
  4683. copySomeData (myBuffer + start1, someData, size1);
  4684. if (size2 > 0)
  4685. copySomeData (myBuffer + start2, someData + size1, size2);
  4686. finishedWrite (size1 + size2);
  4687. }
  4688. @endcode
  4689. @param numToWrite indicates how many items you'd like to add to the buffer
  4690. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4691. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4692. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4693. the first block should be written
  4694. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4695. @see finishedWrite
  4696. */
  4697. void prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept;
  4698. /** Called after reading from the FIFO, to indicate that this many items have been added.
  4699. @see prepareToWrite
  4700. */
  4701. void finishedWrite (int numWritten) noexcept;
  4702. /** Returns the location within the buffer from which the next block of data should be read.
  4703. Because the section of data that you want to read from the buffer may overlap the end
  4704. and wrap around to the start, two blocks within your buffer are returned, and you
  4705. should read from both of them.
  4706. If the number of items you ask for is greater than the amount of data available, then
  4707. blockSize1 + blockSize2 may add up to a lower value than numWanted. If this happens, you
  4708. may decide to keep waiting and re-trying the method until there's enough data available.
  4709. After calling this method, if you choose to read the data, you must call finishedRead() to
  4710. tell the FIFO how much data you have consumed.
  4711. e.g.
  4712. @code
  4713. void readFromFifo (int* someData, int numItems)
  4714. {
  4715. int start1, size1, start2, size2;
  4716. prepareToRead (numSamples, start1, size1, start2, size2);
  4717. if (size1 > 0)
  4718. copySomeData (someData, myBuffer + start1, size1);
  4719. if (size2 > 0)
  4720. copySomeData (someData + size1, myBuffer + start2, size2);
  4721. finishedRead (size1 + size2);
  4722. }
  4723. @endcode
  4724. @param numWanted indicates how many items you'd like to add to the buffer
  4725. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4726. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4727. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4728. the first block should be written
  4729. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4730. @see finishedRead
  4731. */
  4732. void prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept;
  4733. /** Called after reading from the FIFO, to indicate that this many items have now been consumed.
  4734. @see prepareToRead
  4735. */
  4736. void finishedRead (int numRead) noexcept;
  4737. private:
  4738. int bufferSize;
  4739. Atomic <int> validStart, validEnd;
  4740. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AbstractFifo);
  4741. };
  4742. #endif // __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4743. /*** End of inlined file: juce_AbstractFifo.h ***/
  4744. #endif
  4745. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4746. /*** Start of inlined file: juce_Array.h ***/
  4747. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4748. #define __JUCE_ARRAY_JUCEHEADER__
  4749. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  4750. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4751. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4752. /*** Start of inlined file: juce_HeapBlock.h ***/
  4753. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4754. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  4755. /**
  4756. Very simple container class to hold a pointer to some data on the heap.
  4757. When you need to allocate some heap storage for something, always try to use
  4758. this class instead of allocating the memory directly using malloc/free.
  4759. A HeapBlock<char> object can be treated in pretty much exactly the same way
  4760. as an char*, but as long as you allocate it on the stack or as a class member,
  4761. it's almost impossible for it to leak memory.
  4762. It also makes your code much more concise and readable than doing the same thing
  4763. using direct allocations,
  4764. E.g. instead of this:
  4765. @code
  4766. int* temp = (int*) malloc (1024 * sizeof (int));
  4767. memcpy (temp, xyz, 1024 * sizeof (int));
  4768. free (temp);
  4769. temp = (int*) calloc (2048 * sizeof (int));
  4770. temp[0] = 1234;
  4771. memcpy (foobar, temp, 2048 * sizeof (int));
  4772. free (temp);
  4773. @endcode
  4774. ..you could just write this:
  4775. @code
  4776. HeapBlock <int> temp (1024);
  4777. memcpy (temp, xyz, 1024 * sizeof (int));
  4778. temp.calloc (2048);
  4779. temp[0] = 1234;
  4780. memcpy (foobar, temp, 2048 * sizeof (int));
  4781. @endcode
  4782. The class is extremely lightweight, containing only a pointer to the
  4783. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  4784. as their less object-oriented counterparts. Despite adding safety, you probably
  4785. won't sacrifice any performance by using this in place of normal pointers.
  4786. @see Array, OwnedArray, MemoryBlock
  4787. */
  4788. template <class ElementType>
  4789. class HeapBlock
  4790. {
  4791. public:
  4792. /** Creates a HeapBlock which is initially just a null pointer.
  4793. After creation, you can resize the array using the malloc(), calloc(),
  4794. or realloc() methods.
  4795. */
  4796. HeapBlock() noexcept : data (nullptr)
  4797. {
  4798. }
  4799. /** Creates a HeapBlock containing a number of elements.
  4800. The contents of the block are undefined, as it will have been created by a
  4801. malloc call.
  4802. If you want an array of zero values, you can use the calloc() method instead.
  4803. */
  4804. explicit HeapBlock (const size_t numElements)
  4805. : data (static_cast <ElementType*> (::malloc (numElements * sizeof (ElementType))))
  4806. {
  4807. }
  4808. /** Destructor.
  4809. This will free the data, if any has been allocated.
  4810. */
  4811. ~HeapBlock()
  4812. {
  4813. ::free (data);
  4814. }
  4815. /** Returns a raw pointer to the allocated data.
  4816. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4817. freed by calling the free() method.
  4818. */
  4819. inline operator ElementType*() const noexcept { return data; }
  4820. /** Returns a raw pointer to the allocated data.
  4821. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4822. freed by calling the free() method.
  4823. */
  4824. inline ElementType* getData() const noexcept { return data; }
  4825. /** Returns a void pointer to the allocated data.
  4826. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4827. freed by calling the free() method.
  4828. */
  4829. inline operator void*() const noexcept { return static_cast <void*> (data); }
  4830. /** Returns a void pointer to the allocated data.
  4831. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4832. freed by calling the free() method.
  4833. */
  4834. inline operator const void*() const noexcept { return static_cast <const void*> (data); }
  4835. /** Lets you use indirect calls to the first element in the array.
  4836. Obviously this will cause problems if the array hasn't been initialised, because it'll
  4837. be referencing a null pointer.
  4838. */
  4839. inline ElementType* operator->() const noexcept { return data; }
  4840. /** Returns a reference to one of the data elements.
  4841. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  4842. has no idea of the size it currently has allocated.
  4843. */
  4844. template <typename IndexType>
  4845. inline ElementType& operator[] (IndexType index) const noexcept { return data [index]; }
  4846. /** Returns a pointer to a data element at an offset from the start of the array.
  4847. This is the same as doing pointer arithmetic on the raw pointer itself.
  4848. */
  4849. template <typename IndexType>
  4850. inline ElementType* operator+ (IndexType index) const noexcept { return data + index; }
  4851. /** Compares the pointer with another pointer.
  4852. This can be handy for checking whether this is a null pointer.
  4853. */
  4854. inline bool operator== (const ElementType* const otherPointer) const noexcept { return otherPointer == data; }
  4855. /** Compares the pointer with another pointer.
  4856. This can be handy for checking whether this is a null pointer.
  4857. */
  4858. inline bool operator!= (const ElementType* const otherPointer) const noexcept { return otherPointer != data; }
  4859. /** Allocates a specified amount of memory.
  4860. This uses the normal malloc to allocate an amount of memory for this object.
  4861. Any previously allocated memory will be freed by this method.
  4862. The number of bytes allocated will be (newNumElements * elementSize). Normally
  4863. you wouldn't need to specify the second parameter, but it can be handy if you need
  4864. to allocate a size in bytes rather than in terms of the number of elements.
  4865. The data that is allocated will be freed when this object is deleted, or when you
  4866. call free() or any of the allocation methods.
  4867. */
  4868. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4869. {
  4870. ::free (data);
  4871. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4872. }
  4873. /** Allocates a specified amount of memory and clears it.
  4874. This does the same job as the malloc() method, but clears the memory that it allocates.
  4875. */
  4876. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4877. {
  4878. ::free (data);
  4879. data = static_cast <ElementType*> (::calloc (newNumElements, elementSize));
  4880. }
  4881. /** Allocates a specified amount of memory and optionally clears it.
  4882. This does the same job as either malloc() or calloc(), depending on the
  4883. initialiseToZero parameter.
  4884. */
  4885. void allocate (const size_t newNumElements, const bool initialiseToZero)
  4886. {
  4887. ::free (data);
  4888. if (initialiseToZero)
  4889. data = static_cast <ElementType*> (::calloc (newNumElements, sizeof (ElementType)));
  4890. else
  4891. data = static_cast <ElementType*> (::malloc (newNumElements * sizeof (ElementType)));
  4892. }
  4893. /** Re-allocates a specified amount of memory.
  4894. The semantics of this method are the same as malloc() and calloc(), but it
  4895. uses realloc() to keep as much of the existing data as possible.
  4896. */
  4897. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4898. {
  4899. if (data == nullptr)
  4900. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4901. else
  4902. data = static_cast <ElementType*> (::realloc (data, newNumElements * elementSize));
  4903. }
  4904. /** Frees any currently-allocated data.
  4905. This will free the data and reset this object to be a null pointer.
  4906. */
  4907. void free()
  4908. {
  4909. ::free (data);
  4910. data = nullptr;
  4911. }
  4912. /** Swaps this object's data with the data of another HeapBlock.
  4913. The two objects simply exchange their data pointers.
  4914. */
  4915. void swapWith (HeapBlock <ElementType>& other) noexcept
  4916. {
  4917. std::swap (data, other.data);
  4918. }
  4919. /** This fills the block with zeros, up to the number of elements specified.
  4920. Since the block has no way of knowing its own size, you must make sure that the number of
  4921. elements you specify doesn't exceed the allocated size.
  4922. */
  4923. void clear (size_t numElements) noexcept
  4924. {
  4925. zeromem (data, sizeof (ElementType) * numElements);
  4926. }
  4927. private:
  4928. ElementType* data;
  4929. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HeapBlock);
  4930. };
  4931. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  4932. /*** End of inlined file: juce_HeapBlock.h ***/
  4933. /**
  4934. Implements some basic array storage allocation functions.
  4935. This class isn't really for public use - it's used by the other
  4936. array classes, but might come in handy for some purposes.
  4937. It inherits from a critical section class to allow the arrays to use
  4938. the "empty base class optimisation" pattern to reduce their footprint.
  4939. @see Array, OwnedArray, ReferenceCountedArray
  4940. */
  4941. template <class ElementType, class TypeOfCriticalSectionToUse>
  4942. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  4943. {
  4944. public:
  4945. /** Creates an empty array. */
  4946. ArrayAllocationBase() noexcept
  4947. : numAllocated (0)
  4948. {
  4949. }
  4950. /** Destructor. */
  4951. ~ArrayAllocationBase()
  4952. {
  4953. }
  4954. /** Changes the amount of storage allocated.
  4955. This will retain any data currently held in the array, and either add or
  4956. remove extra space at the end.
  4957. @param numElements the number of elements that are needed
  4958. */
  4959. void setAllocatedSize (const int numElements)
  4960. {
  4961. if (numAllocated != numElements)
  4962. {
  4963. if (numElements > 0)
  4964. elements.realloc (numElements);
  4965. else
  4966. elements.free();
  4967. numAllocated = numElements;
  4968. }
  4969. }
  4970. /** Increases the amount of storage allocated if it is less than a given amount.
  4971. This will retain any data currently held in the array, but will add
  4972. extra space at the end to make sure there it's at least as big as the size
  4973. passed in. If it's already bigger, no action is taken.
  4974. @param minNumElements the minimum number of elements that are needed
  4975. */
  4976. void ensureAllocatedSize (const int minNumElements)
  4977. {
  4978. if (minNumElements > numAllocated)
  4979. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  4980. }
  4981. /** Minimises the amount of storage allocated so that it's no more than
  4982. the given number of elements.
  4983. */
  4984. void shrinkToNoMoreThan (const int maxNumElements)
  4985. {
  4986. if (maxNumElements < numAllocated)
  4987. setAllocatedSize (maxNumElements);
  4988. }
  4989. /** Swap the contents of two objects. */
  4990. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) noexcept
  4991. {
  4992. elements.swapWith (other.elements);
  4993. std::swap (numAllocated, other.numAllocated);
  4994. }
  4995. HeapBlock <ElementType> elements;
  4996. int numAllocated;
  4997. private:
  4998. JUCE_DECLARE_NON_COPYABLE (ArrayAllocationBase);
  4999. };
  5000. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  5001. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  5002. /*** Start of inlined file: juce_ElementComparator.h ***/
  5003. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5004. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5005. /**
  5006. Sorts a range of elements in an array.
  5007. The comparator object that is passed-in must define a public method with the following
  5008. signature:
  5009. @code
  5010. int compareElements (ElementType first, ElementType second);
  5011. @endcode
  5012. ..and this method must return:
  5013. - a value of < 0 if the first comes before the second
  5014. - a value of 0 if the two objects are equivalent
  5015. - a value of > 0 if the second comes before the first
  5016. To improve performance, the compareElements() method can be declared as static or const.
  5017. @param comparator an object which defines a compareElements() method
  5018. @param array the array to sort
  5019. @param firstElement the index of the first element of the range to be sorted
  5020. @param lastElement the index of the last element in the range that needs
  5021. sorting (this is inclusive)
  5022. @param retainOrderOfEquivalentItems if true, the order of items that the
  5023. comparator deems the same will be maintained - this will be
  5024. a slower algorithm than if they are allowed to be moved around.
  5025. @see sortArrayRetainingOrder
  5026. */
  5027. template <class ElementType, class ElementComparator>
  5028. static void sortArray (ElementComparator& comparator,
  5029. ElementType* const array,
  5030. int firstElement,
  5031. int lastElement,
  5032. const bool retainOrderOfEquivalentItems)
  5033. {
  5034. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5035. // avoids getting warning messages about the parameter being unused
  5036. if (lastElement > firstElement)
  5037. {
  5038. if (retainOrderOfEquivalentItems)
  5039. {
  5040. for (int i = firstElement; i < lastElement; ++i)
  5041. {
  5042. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  5043. {
  5044. std::swap (array[i], array[i + 1]);
  5045. if (i > firstElement)
  5046. i -= 2;
  5047. }
  5048. }
  5049. }
  5050. else
  5051. {
  5052. int fromStack[30], toStack[30];
  5053. int stackIndex = 0;
  5054. for (;;)
  5055. {
  5056. const int size = (lastElement - firstElement) + 1;
  5057. if (size <= 8)
  5058. {
  5059. int j = lastElement;
  5060. int maxIndex;
  5061. while (j > firstElement)
  5062. {
  5063. maxIndex = firstElement;
  5064. for (int k = firstElement + 1; k <= j; ++k)
  5065. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  5066. maxIndex = k;
  5067. std::swap (array[j], array[maxIndex]);
  5068. --j;
  5069. }
  5070. }
  5071. else
  5072. {
  5073. const int mid = firstElement + (size >> 1);
  5074. std::swap (array[mid], array[firstElement]);
  5075. int i = firstElement;
  5076. int j = lastElement + 1;
  5077. for (;;)
  5078. {
  5079. while (++i <= lastElement
  5080. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  5081. {}
  5082. while (--j > firstElement
  5083. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  5084. {}
  5085. if (j < i)
  5086. break;
  5087. std::swap (array[i], array[j]);
  5088. }
  5089. std::swap (array[j], array[firstElement]);
  5090. if (j - 1 - firstElement >= lastElement - i)
  5091. {
  5092. if (firstElement + 1 < j)
  5093. {
  5094. fromStack [stackIndex] = firstElement;
  5095. toStack [stackIndex] = j - 1;
  5096. ++stackIndex;
  5097. }
  5098. if (i < lastElement)
  5099. {
  5100. firstElement = i;
  5101. continue;
  5102. }
  5103. }
  5104. else
  5105. {
  5106. if (i < lastElement)
  5107. {
  5108. fromStack [stackIndex] = i;
  5109. toStack [stackIndex] = lastElement;
  5110. ++stackIndex;
  5111. }
  5112. if (firstElement + 1 < j)
  5113. {
  5114. lastElement = j - 1;
  5115. continue;
  5116. }
  5117. }
  5118. }
  5119. if (--stackIndex < 0)
  5120. break;
  5121. jassert (stackIndex < numElementsInArray (fromStack));
  5122. firstElement = fromStack [stackIndex];
  5123. lastElement = toStack [stackIndex];
  5124. }
  5125. }
  5126. }
  5127. }
  5128. /**
  5129. Searches a sorted array of elements, looking for the index at which a specified value
  5130. should be inserted for it to be in the correct order.
  5131. The comparator object that is passed-in must define a public method with the following
  5132. signature:
  5133. @code
  5134. int compareElements (ElementType first, ElementType second);
  5135. @endcode
  5136. ..and this method must return:
  5137. - a value of < 0 if the first comes before the second
  5138. - a value of 0 if the two objects are equivalent
  5139. - a value of > 0 if the second comes before the first
  5140. To improve performance, the compareElements() method can be declared as static or const.
  5141. @param comparator an object which defines a compareElements() method
  5142. @param array the array to search
  5143. @param newElement the value that is going to be inserted
  5144. @param firstElement the index of the first element to search
  5145. @param lastElement the index of the last element in the range (this is non-inclusive)
  5146. */
  5147. template <class ElementType, class ElementComparator>
  5148. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  5149. ElementType* const array,
  5150. const ElementType newElement,
  5151. int firstElement,
  5152. int lastElement)
  5153. {
  5154. jassert (firstElement <= lastElement);
  5155. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5156. // avoids getting warning messages about the parameter being unused
  5157. while (firstElement < lastElement)
  5158. {
  5159. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  5160. {
  5161. ++firstElement;
  5162. break;
  5163. }
  5164. else
  5165. {
  5166. const int halfway = (firstElement + lastElement) >> 1;
  5167. if (halfway == firstElement)
  5168. {
  5169. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5170. ++firstElement;
  5171. break;
  5172. }
  5173. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5174. {
  5175. firstElement = halfway;
  5176. }
  5177. else
  5178. {
  5179. lastElement = halfway;
  5180. }
  5181. }
  5182. }
  5183. return firstElement;
  5184. }
  5185. /**
  5186. A simple ElementComparator class that can be used to sort an array of
  5187. objects that support the '<' operator.
  5188. This will work for primitive types and objects that implement operator<().
  5189. Example: @code
  5190. Array <int> myArray;
  5191. DefaultElementComparator<int> sorter;
  5192. myArray.sort (sorter);
  5193. @endcode
  5194. @see ElementComparator
  5195. */
  5196. template <class ElementType>
  5197. class DefaultElementComparator
  5198. {
  5199. private:
  5200. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5201. public:
  5202. static int compareElements (ParameterType first, ParameterType second)
  5203. {
  5204. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  5205. }
  5206. };
  5207. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5208. /*** End of inlined file: juce_ElementComparator.h ***/
  5209. /*** Start of inlined file: juce_CriticalSection.h ***/
  5210. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  5211. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  5212. /*** Start of inlined file: juce_ScopedLock.h ***/
  5213. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  5214. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  5215. /**
  5216. Automatically locks and unlocks a mutex object.
  5217. Use one of these as a local variable to provide RAII-based locking of a mutex.
  5218. The templated class could be a CriticalSection, SpinLock, or anything else that
  5219. provides enter() and exit() methods.
  5220. e.g. @code
  5221. CriticalSection myCriticalSection;
  5222. for (;;)
  5223. {
  5224. const GenericScopedLock<CriticalSection> myScopedLock (myCriticalSection);
  5225. // myCriticalSection is now locked
  5226. ...do some stuff...
  5227. // myCriticalSection gets unlocked here.
  5228. }
  5229. @endcode
  5230. @see GenericScopedUnlock, CriticalSection, SpinLock, ScopedLock, ScopedUnlock
  5231. */
  5232. template <class LockType>
  5233. class GenericScopedLock
  5234. {
  5235. public:
  5236. /** Creates a GenericScopedLock.
  5237. As soon as it is created, this will acquire the lock, and when the GenericScopedLock
  5238. object is deleted, the lock will be released.
  5239. Make sure this object is created and deleted by the same thread,
  5240. otherwise there are no guarantees what will happen! Best just to use it
  5241. as a local stack object, rather than creating one with the new() operator.
  5242. */
  5243. inline explicit GenericScopedLock (const LockType& lock) noexcept : lock_ (lock) { lock.enter(); }
  5244. /** Destructor.
  5245. The lock will be released when the destructor is called.
  5246. Make sure this object is created and deleted by the same thread, otherwise there are
  5247. no guarantees what will happen!
  5248. */
  5249. inline ~GenericScopedLock() noexcept { lock_.exit(); }
  5250. private:
  5251. const LockType& lock_;
  5252. JUCE_DECLARE_NON_COPYABLE (GenericScopedLock);
  5253. };
  5254. /**
  5255. Automatically unlocks and re-locks a mutex object.
  5256. This is the reverse of a GenericScopedLock object - instead of locking the mutex
  5257. for the lifetime of this object, it unlocks it.
  5258. Make sure you don't try to unlock mutexes that aren't actually locked!
  5259. e.g. @code
  5260. CriticalSection myCriticalSection;
  5261. for (;;)
  5262. {
  5263. const GenericScopedLock<CriticalSection> myScopedLock (myCriticalSection);
  5264. // myCriticalSection is now locked
  5265. ... do some stuff with it locked ..
  5266. while (xyz)
  5267. {
  5268. ... do some stuff with it locked ..
  5269. const GenericScopedUnlock<CriticalSection> unlocker (myCriticalSection);
  5270. // myCriticalSection is now unlocked for the remainder of this block,
  5271. // and re-locked at the end.
  5272. ...do some stuff with it unlocked ...
  5273. }
  5274. // myCriticalSection gets unlocked here.
  5275. }
  5276. @endcode
  5277. @see GenericScopedLock, CriticalSection, ScopedLock, ScopedUnlock
  5278. */
  5279. template <class LockType>
  5280. class GenericScopedUnlock
  5281. {
  5282. public:
  5283. /** Creates a GenericScopedUnlock.
  5284. As soon as it is created, this will unlock the CriticalSection, and
  5285. when the ScopedLock object is deleted, the CriticalSection will
  5286. be re-locked.
  5287. Make sure this object is created and deleted by the same thread,
  5288. otherwise there are no guarantees what will happen! Best just to use it
  5289. as a local stack object, rather than creating one with the new() operator.
  5290. */
  5291. inline explicit GenericScopedUnlock (const LockType& lock) noexcept : lock_ (lock) { lock.exit(); }
  5292. /** Destructor.
  5293. The CriticalSection will be unlocked when the destructor is called.
  5294. Make sure this object is created and deleted by the same thread,
  5295. otherwise there are no guarantees what will happen!
  5296. */
  5297. inline ~GenericScopedUnlock() noexcept { lock_.enter(); }
  5298. private:
  5299. const LockType& lock_;
  5300. JUCE_DECLARE_NON_COPYABLE (GenericScopedUnlock);
  5301. };
  5302. /**
  5303. Automatically locks and unlocks a mutex object.
  5304. Use one of these as a local variable to provide RAII-based locking of a mutex.
  5305. The templated class could be a CriticalSection, SpinLock, or anything else that
  5306. provides enter() and exit() methods.
  5307. e.g. @code
  5308. CriticalSection myCriticalSection;
  5309. for (;;)
  5310. {
  5311. const GenericScopedTryLock<CriticalSection> myScopedTryLock (myCriticalSection);
  5312. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  5313. // should test this with the isLocked() method before doing your thread-unsafe
  5314. // action..
  5315. if (myScopedTryLock.isLocked())
  5316. {
  5317. ...do some stuff...
  5318. }
  5319. else
  5320. {
  5321. ..our attempt at locking failed because another thread had already locked it..
  5322. }
  5323. // myCriticalSection gets unlocked here (if it was locked)
  5324. }
  5325. @endcode
  5326. @see CriticalSection::tryEnter, GenericScopedLock, GenericScopedUnlock
  5327. */
  5328. template <class LockType>
  5329. class GenericScopedTryLock
  5330. {
  5331. public:
  5332. /** Creates a GenericScopedTryLock.
  5333. As soon as it is created, this will attempt to acquire the lock, and when the
  5334. GenericScopedTryLock is deleted, the lock will be released (if the lock was
  5335. successfully acquired).
  5336. Make sure this object is created and deleted by the same thread,
  5337. otherwise there are no guarantees what will happen! Best just to use it
  5338. as a local stack object, rather than creating one with the new() operator.
  5339. */
  5340. inline explicit GenericScopedTryLock (const LockType& lock) noexcept
  5341. : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  5342. /** Destructor.
  5343. The mutex will be unlocked (if it had been successfully locked) when the
  5344. destructor is called.
  5345. Make sure this object is created and deleted by the same thread,
  5346. otherwise there are no guarantees what will happen!
  5347. */
  5348. inline ~GenericScopedTryLock() noexcept { if (lockWasSuccessful) lock_.exit(); }
  5349. /** Returns true if the mutex was successfully locked. */
  5350. bool isLocked() const noexcept { return lockWasSuccessful; }
  5351. private:
  5352. const LockType& lock_;
  5353. const bool lockWasSuccessful;
  5354. JUCE_DECLARE_NON_COPYABLE (GenericScopedTryLock);
  5355. };
  5356. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  5357. /*** End of inlined file: juce_ScopedLock.h ***/
  5358. /**
  5359. A mutex class.
  5360. A CriticalSection acts as a re-entrant mutex lock. The best way to lock and unlock
  5361. one of these is by using RAII in the form of a local ScopedLock object - have a look
  5362. through the codebase for many examples of how to do this.
  5363. @see ScopedLock, ScopedTryLock, ScopedUnlock, SpinLock, ReadWriteLock, Thread, InterProcessLock
  5364. */
  5365. class JUCE_API CriticalSection
  5366. {
  5367. public:
  5368. /** Creates a CriticalSection object. */
  5369. CriticalSection() noexcept;
  5370. /** Destructor.
  5371. If the critical section is deleted whilst locked, any subsequent behaviour
  5372. is unpredictable.
  5373. */
  5374. ~CriticalSection() noexcept;
  5375. /** Acquires the lock.
  5376. If the lock is already held by the caller thread, the method returns immediately.
  5377. If the lock is currently held by another thread, this will wait until it becomes free.
  5378. It's strongly recommended that you never call this method directly - instead use the
  5379. ScopedLock class to manage the locking using an RAII pattern instead.
  5380. @see exit, tryEnter, ScopedLock
  5381. */
  5382. void enter() const noexcept;
  5383. /** Attempts to lock this critical section without blocking.
  5384. This method behaves identically to CriticalSection::enter, except that the caller thread
  5385. does not wait if the lock is currently held by another thread but returns false immediately.
  5386. @returns false if the lock is currently held by another thread, true otherwise.
  5387. @see enter
  5388. */
  5389. bool tryEnter() const noexcept;
  5390. /** Releases the lock.
  5391. If the caller thread hasn't got the lock, this can have unpredictable results.
  5392. If the enter() method has been called multiple times by the thread, each
  5393. call must be matched by a call to exit() before other threads will be allowed
  5394. to take over the lock.
  5395. @see enter, ScopedLock
  5396. */
  5397. void exit() const noexcept;
  5398. /** Provides the type of scoped lock to use with a CriticalSection. */
  5399. typedef GenericScopedLock <CriticalSection> ScopedLockType;
  5400. /** Provides the type of scoped unlocker to use with a CriticalSection. */
  5401. typedef GenericScopedUnlock <CriticalSection> ScopedUnlockType;
  5402. /** Provides the type of scoped try-locker to use with a CriticalSection. */
  5403. typedef GenericScopedTryLock <CriticalSection> ScopedTryLockType;
  5404. private:
  5405. #if JUCE_WINDOWS
  5406. // To avoid including windows.h in the public JUCE headers, we'll just allocate a
  5407. // block of memory here that's big enough to be used internally as a windows critical
  5408. // section structure.
  5409. #if JUCE_64BIT
  5410. uint8 internal [44];
  5411. #else
  5412. uint8 internal [24];
  5413. #endif
  5414. #else
  5415. mutable pthread_mutex_t internal;
  5416. #endif
  5417. JUCE_DECLARE_NON_COPYABLE (CriticalSection);
  5418. };
  5419. /**
  5420. A class that can be used in place of a real CriticalSection object, but which
  5421. doesn't perform any locking.
  5422. This is currently used by some templated classes, and most compilers should
  5423. manage to optimise it out of existence.
  5424. @see CriticalSection, Array, OwnedArray, ReferenceCountedArray
  5425. */
  5426. class JUCE_API DummyCriticalSection
  5427. {
  5428. public:
  5429. inline DummyCriticalSection() noexcept {}
  5430. inline ~DummyCriticalSection() noexcept {}
  5431. inline void enter() const noexcept {}
  5432. inline bool tryEnter() const noexcept { return true; }
  5433. inline void exit() const noexcept {}
  5434. /** A dummy scoped-lock type to use with a dummy critical section. */
  5435. struct ScopedLockType
  5436. {
  5437. ScopedLockType (const DummyCriticalSection&) noexcept {}
  5438. };
  5439. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  5440. typedef ScopedLockType ScopedUnlockType;
  5441. private:
  5442. JUCE_DECLARE_NON_COPYABLE (DummyCriticalSection);
  5443. };
  5444. /**
  5445. Automatically locks and unlocks a CriticalSection object.
  5446. Use one of these as a local variable to provide RAII-based locking of a CriticalSection.
  5447. e.g. @code
  5448. CriticalSection myCriticalSection;
  5449. for (;;)
  5450. {
  5451. const ScopedLock myScopedLock (myCriticalSection);
  5452. // myCriticalSection is now locked
  5453. ...do some stuff...
  5454. // myCriticalSection gets unlocked here.
  5455. }
  5456. @endcode
  5457. @see CriticalSection, ScopedUnlock
  5458. */
  5459. typedef CriticalSection::ScopedLockType ScopedLock;
  5460. /**
  5461. Automatically unlocks and re-locks a CriticalSection object.
  5462. This is the reverse of a ScopedLock object - instead of locking the critical
  5463. section for the lifetime of this object, it unlocks it.
  5464. Make sure you don't try to unlock critical sections that aren't actually locked!
  5465. e.g. @code
  5466. CriticalSection myCriticalSection;
  5467. for (;;)
  5468. {
  5469. const ScopedLock myScopedLock (myCriticalSection);
  5470. // myCriticalSection is now locked
  5471. ... do some stuff with it locked ..
  5472. while (xyz)
  5473. {
  5474. ... do some stuff with it locked ..
  5475. const ScopedUnlock unlocker (myCriticalSection);
  5476. // myCriticalSection is now unlocked for the remainder of this block,
  5477. // and re-locked at the end.
  5478. ...do some stuff with it unlocked ...
  5479. }
  5480. // myCriticalSection gets unlocked here.
  5481. }
  5482. @endcode
  5483. @see CriticalSection, ScopedLock
  5484. */
  5485. typedef CriticalSection::ScopedUnlockType ScopedUnlock;
  5486. /**
  5487. Automatically tries to lock and unlock a CriticalSection object.
  5488. Use one of these as a local variable to control access to a CriticalSection.
  5489. e.g. @code
  5490. CriticalSection myCriticalSection;
  5491. for (;;)
  5492. {
  5493. const ScopedTryLock myScopedTryLock (myCriticalSection);
  5494. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  5495. // should test this with the isLocked() method before doing your thread-unsafe
  5496. // action..
  5497. if (myScopedTryLock.isLocked())
  5498. {
  5499. ...do some stuff...
  5500. }
  5501. else
  5502. {
  5503. ..our attempt at locking failed because another thread had already locked it..
  5504. }
  5505. // myCriticalSection gets unlocked here (if it was locked)
  5506. }
  5507. @endcode
  5508. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  5509. */
  5510. typedef CriticalSection::ScopedTryLockType ScopedTryLock;
  5511. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  5512. /*** End of inlined file: juce_CriticalSection.h ***/
  5513. /**
  5514. Holds a resizable array of primitive or copy-by-value objects.
  5515. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  5516. The Array class can be used to hold simple, non-polymorphic objects as well as primitive types - to
  5517. do so, the class must fulfil these requirements:
  5518. - it must have a copy constructor and assignment operator
  5519. - it must be able to be relocated in memory by a memcpy without this causing any problems - so
  5520. objects whose functionality relies on external pointers or references to themselves can be used.
  5521. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  5522. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  5523. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  5524. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  5525. specialised class StringArray, which provides more useful functions.
  5526. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5527. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5528. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  5529. */
  5530. template <typename ElementType,
  5531. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  5532. class Array
  5533. {
  5534. private:
  5535. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5536. public:
  5537. /** Creates an empty array. */
  5538. Array() noexcept
  5539. : numUsed (0)
  5540. {
  5541. }
  5542. /** Creates a copy of another array.
  5543. @param other the array to copy
  5544. */
  5545. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  5546. {
  5547. const ScopedLockType lock (other.getLock());
  5548. numUsed = other.numUsed;
  5549. data.setAllocatedSize (other.numUsed);
  5550. for (int i = 0; i < numUsed; ++i)
  5551. new (data.elements + i) ElementType (other.data.elements[i]);
  5552. }
  5553. /** Initalises from a null-terminated C array of values.
  5554. @param values the array to copy from
  5555. */
  5556. template <typename TypeToCreateFrom>
  5557. explicit Array (const TypeToCreateFrom* values)
  5558. : numUsed (0)
  5559. {
  5560. while (*values != TypeToCreateFrom())
  5561. add (*values++);
  5562. }
  5563. /** Initalises from a C array of values.
  5564. @param values the array to copy from
  5565. @param numValues the number of values in the array
  5566. */
  5567. template <typename TypeToCreateFrom>
  5568. Array (const TypeToCreateFrom* values, int numValues)
  5569. : numUsed (numValues)
  5570. {
  5571. data.setAllocatedSize (numValues);
  5572. for (int i = 0; i < numValues; ++i)
  5573. new (data.elements + i) ElementType (values[i]);
  5574. }
  5575. /** Destructor. */
  5576. ~Array()
  5577. {
  5578. for (int i = 0; i < numUsed; ++i)
  5579. data.elements[i].~ElementType();
  5580. }
  5581. /** Copies another array.
  5582. @param other the array to copy
  5583. */
  5584. Array& operator= (const Array& other)
  5585. {
  5586. if (this != &other)
  5587. {
  5588. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  5589. swapWithArray (otherCopy);
  5590. }
  5591. return *this;
  5592. }
  5593. /** Compares this array to another one.
  5594. Two arrays are considered equal if they both contain the same set of
  5595. elements, in the same order.
  5596. @param other the other array to compare with
  5597. */
  5598. template <class OtherArrayType>
  5599. bool operator== (const OtherArrayType& other) const
  5600. {
  5601. const ScopedLockType lock (getLock());
  5602. const typename OtherArrayType::ScopedLockType lock2 (other.getLock());
  5603. if (numUsed != other.numUsed)
  5604. return false;
  5605. for (int i = numUsed; --i >= 0;)
  5606. if (! (data.elements [i] == other.data.elements [i]))
  5607. return false;
  5608. return true;
  5609. }
  5610. /** Compares this array to another one.
  5611. Two arrays are considered equal if they both contain the same set of
  5612. elements, in the same order.
  5613. @param other the other array to compare with
  5614. */
  5615. template <class OtherArrayType>
  5616. bool operator!= (const OtherArrayType& other) const
  5617. {
  5618. return ! operator== (other);
  5619. }
  5620. /** Removes all elements from the array.
  5621. This will remove all the elements, and free any storage that the array is
  5622. using. To clear the array without freeing the storage, use the clearQuick()
  5623. method instead.
  5624. @see clearQuick
  5625. */
  5626. void clear()
  5627. {
  5628. const ScopedLockType lock (getLock());
  5629. for (int i = 0; i < numUsed; ++i)
  5630. data.elements[i].~ElementType();
  5631. data.setAllocatedSize (0);
  5632. numUsed = 0;
  5633. }
  5634. /** Removes all elements from the array without freeing the array's allocated storage.
  5635. @see clear
  5636. */
  5637. void clearQuick()
  5638. {
  5639. const ScopedLockType lock (getLock());
  5640. for (int i = 0; i < numUsed; ++i)
  5641. data.elements[i].~ElementType();
  5642. numUsed = 0;
  5643. }
  5644. /** Returns the current number of elements in the array.
  5645. */
  5646. inline int size() const noexcept
  5647. {
  5648. return numUsed;
  5649. }
  5650. /** Returns one of the elements in the array.
  5651. If the index passed in is beyond the range of valid elements, this
  5652. will return zero.
  5653. If you're certain that the index will always be a valid element, you
  5654. can call getUnchecked() instead, which is faster.
  5655. @param index the index of the element being requested (0 is the first element in the array)
  5656. @see getUnchecked, getFirst, getLast
  5657. */
  5658. inline ElementType operator[] (const int index) const
  5659. {
  5660. const ScopedLockType lock (getLock());
  5661. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  5662. : ElementType();
  5663. }
  5664. /** Returns one of the elements in the array, without checking the index passed in.
  5665. Unlike the operator[] method, this will try to return an element without
  5666. checking that the index is within the bounds of the array, so should only
  5667. be used when you're confident that it will always be a valid index.
  5668. @param index the index of the element being requested (0 is the first element in the array)
  5669. @see operator[], getFirst, getLast
  5670. */
  5671. inline const ElementType getUnchecked (const int index) const
  5672. {
  5673. const ScopedLockType lock (getLock());
  5674. jassert (isPositiveAndBelow (index, numUsed));
  5675. return data.elements [index];
  5676. }
  5677. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  5678. This is like getUnchecked, but returns a direct reference to the element, so that
  5679. you can alter it directly. Obviously this can be dangerous, so only use it when
  5680. absolutely necessary.
  5681. @param index the index of the element being requested (0 is the first element in the array)
  5682. @see operator[], getFirst, getLast
  5683. */
  5684. inline ElementType& getReference (const int index) const noexcept
  5685. {
  5686. const ScopedLockType lock (getLock());
  5687. jassert (isPositiveAndBelow (index, numUsed));
  5688. return data.elements [index];
  5689. }
  5690. /** Returns the first element in the array, or 0 if the array is empty.
  5691. @see operator[], getUnchecked, getLast
  5692. */
  5693. inline ElementType getFirst() const
  5694. {
  5695. const ScopedLockType lock (getLock());
  5696. return (numUsed > 0) ? data.elements [0]
  5697. : ElementType();
  5698. }
  5699. /** Returns the last element in the array, or 0 if the array is empty.
  5700. @see operator[], getUnchecked, getFirst
  5701. */
  5702. inline ElementType getLast() const
  5703. {
  5704. const ScopedLockType lock (getLock());
  5705. return (numUsed > 0) ? data.elements [numUsed - 1]
  5706. : ElementType();
  5707. }
  5708. /** Returns a pointer to the actual array data.
  5709. This pointer will only be valid until the next time a non-const method
  5710. is called on the array.
  5711. */
  5712. inline ElementType* getRawDataPointer() noexcept
  5713. {
  5714. return data.elements;
  5715. }
  5716. /** Returns a pointer to the first element in the array.
  5717. This method is provided for compatibility with standard C++ iteration mechanisms.
  5718. */
  5719. inline ElementType* begin() const noexcept
  5720. {
  5721. return data.elements;
  5722. }
  5723. /** Returns a pointer to the element which follows the last element in the array.
  5724. This method is provided for compatibility with standard C++ iteration mechanisms.
  5725. */
  5726. inline ElementType* end() const noexcept
  5727. {
  5728. return data.elements + numUsed;
  5729. }
  5730. /** Finds the index of the first element which matches the value passed in.
  5731. This will search the array for the given object, and return the index
  5732. of its first occurrence. If the object isn't found, the method will return -1.
  5733. @param elementToLookFor the value or object to look for
  5734. @returns the index of the object, or -1 if it's not found
  5735. */
  5736. int indexOf (ParameterType elementToLookFor) const
  5737. {
  5738. const ScopedLockType lock (getLock());
  5739. const ElementType* e = data.elements.getData();
  5740. const ElementType* const end = e + numUsed;
  5741. for (; e != end; ++e)
  5742. if (elementToLookFor == *e)
  5743. return static_cast <int> (e - data.elements.getData());
  5744. return -1;
  5745. }
  5746. /** Returns true if the array contains at least one occurrence of an object.
  5747. @param elementToLookFor the value or object to look for
  5748. @returns true if the item is found
  5749. */
  5750. bool contains (ParameterType elementToLookFor) const
  5751. {
  5752. const ScopedLockType lock (getLock());
  5753. const ElementType* e = data.elements.getData();
  5754. const ElementType* const end = e + numUsed;
  5755. for (; e != end; ++e)
  5756. if (elementToLookFor == *e)
  5757. return true;
  5758. return false;
  5759. }
  5760. /** Appends a new element at the end of the array.
  5761. @param newElement the new object to add to the array
  5762. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  5763. */
  5764. void add (ParameterType newElement)
  5765. {
  5766. const ScopedLockType lock (getLock());
  5767. data.ensureAllocatedSize (numUsed + 1);
  5768. new (data.elements + numUsed++) ElementType (newElement);
  5769. }
  5770. /** Inserts a new element into the array at a given position.
  5771. If the index is less than 0 or greater than the size of the array, the
  5772. element will be added to the end of the array.
  5773. Otherwise, it will be inserted into the array, moving all the later elements
  5774. along to make room.
  5775. @param indexToInsertAt the index at which the new element should be
  5776. inserted (pass in -1 to add it to the end)
  5777. @param newElement the new object to add to the array
  5778. @see add, addSorted, addUsingDefaultSort, set
  5779. */
  5780. void insert (int indexToInsertAt, ParameterType newElement)
  5781. {
  5782. const ScopedLockType lock (getLock());
  5783. data.ensureAllocatedSize (numUsed + 1);
  5784. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5785. {
  5786. ElementType* const insertPos = data.elements + indexToInsertAt;
  5787. const int numberToMove = numUsed - indexToInsertAt;
  5788. if (numberToMove > 0)
  5789. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  5790. new (insertPos) ElementType (newElement);
  5791. ++numUsed;
  5792. }
  5793. else
  5794. {
  5795. new (data.elements + numUsed++) ElementType (newElement);
  5796. }
  5797. }
  5798. /** Inserts multiple copies of an element into the array at a given position.
  5799. If the index is less than 0 or greater than the size of the array, the
  5800. element will be added to the end of the array.
  5801. Otherwise, it will be inserted into the array, moving all the later elements
  5802. along to make room.
  5803. @param indexToInsertAt the index at which the new element should be inserted
  5804. @param newElement the new object to add to the array
  5805. @param numberOfTimesToInsertIt how many copies of the value to insert
  5806. @see insert, add, addSorted, set
  5807. */
  5808. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  5809. int numberOfTimesToInsertIt)
  5810. {
  5811. if (numberOfTimesToInsertIt > 0)
  5812. {
  5813. const ScopedLockType lock (getLock());
  5814. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  5815. ElementType* insertPos;
  5816. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5817. {
  5818. insertPos = data.elements + indexToInsertAt;
  5819. const int numberToMove = numUsed - indexToInsertAt;
  5820. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  5821. }
  5822. else
  5823. {
  5824. insertPos = data.elements + numUsed;
  5825. }
  5826. numUsed += numberOfTimesToInsertIt;
  5827. while (--numberOfTimesToInsertIt >= 0)
  5828. new (insertPos++) ElementType (newElement);
  5829. }
  5830. }
  5831. /** Inserts an array of values into this array at a given position.
  5832. If the index is less than 0 or greater than the size of the array, the
  5833. new elements will be added to the end of the array.
  5834. Otherwise, they will be inserted into the array, moving all the later elements
  5835. along to make room.
  5836. @param indexToInsertAt the index at which the first new element should be inserted
  5837. @param newElements the new values to add to the array
  5838. @param numberOfElements how many items are in the array
  5839. @see insert, add, addSorted, set
  5840. */
  5841. void insertArray (int indexToInsertAt,
  5842. const ElementType* newElements,
  5843. int numberOfElements)
  5844. {
  5845. if (numberOfElements > 0)
  5846. {
  5847. const ScopedLockType lock (getLock());
  5848. data.ensureAllocatedSize (numUsed + numberOfElements);
  5849. ElementType* insertPos;
  5850. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5851. {
  5852. insertPos = data.elements + indexToInsertAt;
  5853. const int numberToMove = numUsed - indexToInsertAt;
  5854. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  5855. }
  5856. else
  5857. {
  5858. insertPos = data.elements + numUsed;
  5859. }
  5860. numUsed += numberOfElements;
  5861. while (--numberOfElements >= 0)
  5862. new (insertPos++) ElementType (*newElements++);
  5863. }
  5864. }
  5865. /** Appends a new element at the end of the array as long as the array doesn't
  5866. already contain it.
  5867. If the array already contains an element that matches the one passed in, nothing
  5868. will be done.
  5869. @param newElement the new object to add to the array
  5870. */
  5871. void addIfNotAlreadyThere (ParameterType newElement)
  5872. {
  5873. const ScopedLockType lock (getLock());
  5874. if (! contains (newElement))
  5875. add (newElement);
  5876. }
  5877. /** Replaces an element with a new value.
  5878. If the index is less than zero, this method does nothing.
  5879. If the index is beyond the end of the array, the item is added to the end of the array.
  5880. @param indexToChange the index whose value you want to change
  5881. @param newValue the new value to set for this index.
  5882. @see add, insert
  5883. */
  5884. void set (const int indexToChange, ParameterType newValue)
  5885. {
  5886. jassert (indexToChange >= 0);
  5887. const ScopedLockType lock (getLock());
  5888. if (isPositiveAndBelow (indexToChange, numUsed))
  5889. {
  5890. data.elements [indexToChange] = newValue;
  5891. }
  5892. else if (indexToChange >= 0)
  5893. {
  5894. data.ensureAllocatedSize (numUsed + 1);
  5895. new (data.elements + numUsed++) ElementType (newValue);
  5896. }
  5897. }
  5898. /** Replaces an element with a new value without doing any bounds-checking.
  5899. This just sets a value directly in the array's internal storage, so you'd
  5900. better make sure it's in range!
  5901. @param indexToChange the index whose value you want to change
  5902. @param newValue the new value to set for this index.
  5903. @see set, getUnchecked
  5904. */
  5905. void setUnchecked (const int indexToChange, ParameterType newValue)
  5906. {
  5907. const ScopedLockType lock (getLock());
  5908. jassert (isPositiveAndBelow (indexToChange, numUsed));
  5909. data.elements [indexToChange] = newValue;
  5910. }
  5911. /** Adds elements from an array to the end of this array.
  5912. @param elementsToAdd the array of elements to add
  5913. @param numElementsToAdd how many elements are in this other array
  5914. @see add
  5915. */
  5916. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  5917. {
  5918. const ScopedLockType lock (getLock());
  5919. if (numElementsToAdd > 0)
  5920. {
  5921. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5922. while (--numElementsToAdd >= 0)
  5923. {
  5924. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  5925. ++numUsed;
  5926. }
  5927. }
  5928. }
  5929. /** This swaps the contents of this array with those of another array.
  5930. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5931. because it just swaps their internal pointers.
  5932. */
  5933. void swapWithArray (Array& otherArray) noexcept
  5934. {
  5935. const ScopedLockType lock1 (getLock());
  5936. const ScopedLockType lock2 (otherArray.getLock());
  5937. data.swapWith (otherArray.data);
  5938. swapVariables (numUsed, otherArray.numUsed);
  5939. }
  5940. /** Adds elements from another array to the end of this array.
  5941. @param arrayToAddFrom the array from which to copy the elements
  5942. @param startIndex the first element of the other array to start copying from
  5943. @param numElementsToAdd how many elements to add from the other array. If this
  5944. value is negative or greater than the number of available elements,
  5945. all available elements will be copied.
  5946. @see add
  5947. */
  5948. template <class OtherArrayType>
  5949. void addArray (const OtherArrayType& arrayToAddFrom,
  5950. int startIndex = 0,
  5951. int numElementsToAdd = -1)
  5952. {
  5953. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5954. {
  5955. const ScopedLockType lock2 (getLock());
  5956. if (startIndex < 0)
  5957. {
  5958. jassertfalse;
  5959. startIndex = 0;
  5960. }
  5961. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5962. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5963. while (--numElementsToAdd >= 0)
  5964. add (arrayToAddFrom.getUnchecked (startIndex++));
  5965. }
  5966. }
  5967. /** Inserts a new element into the array, assuming that the array is sorted.
  5968. This will use a comparator to find the position at which the new element
  5969. should go. If the array isn't sorted, the behaviour of this
  5970. method will be unpredictable.
  5971. @param comparator the comparator to use to compare the elements - see the sort()
  5972. method for details about the form this object should take
  5973. @param newElement the new element to insert to the array
  5974. @returns the index at which the new item was added
  5975. @see addUsingDefaultSort, add, sort
  5976. */
  5977. template <class ElementComparator>
  5978. int addSorted (ElementComparator& comparator, ParameterType newElement)
  5979. {
  5980. const ScopedLockType lock (getLock());
  5981. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed);
  5982. insert (index, newElement);
  5983. return index;
  5984. }
  5985. /** Inserts a new element into the array, assuming that the array is sorted.
  5986. This will use the DefaultElementComparator class for sorting, so your ElementType
  5987. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  5988. method will be unpredictable.
  5989. @param newElement the new element to insert to the array
  5990. @see addSorted, sort
  5991. */
  5992. void addUsingDefaultSort (ParameterType newElement)
  5993. {
  5994. DefaultElementComparator <ElementType> comparator;
  5995. addSorted (comparator, newElement);
  5996. }
  5997. /** Finds the index of an element in the array, assuming that the array is sorted.
  5998. This will use a comparator to do a binary-chop to find the index of the given
  5999. element, if it exists. If the array isn't sorted, the behaviour of this
  6000. method will be unpredictable.
  6001. @param comparator the comparator to use to compare the elements - see the sort()
  6002. method for details about the form this object should take
  6003. @param elementToLookFor the element to search for
  6004. @returns the index of the element, or -1 if it's not found
  6005. @see addSorted, sort
  6006. */
  6007. template <class ElementComparator>
  6008. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  6009. {
  6010. (void) comparator; // if you pass in an object with a static compareElements() method, this
  6011. // avoids getting warning messages about the parameter being unused
  6012. const ScopedLockType lock (getLock());
  6013. int start = 0;
  6014. int end = numUsed;
  6015. for (;;)
  6016. {
  6017. if (start >= end)
  6018. {
  6019. return -1;
  6020. }
  6021. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  6022. {
  6023. return start;
  6024. }
  6025. else
  6026. {
  6027. const int halfway = (start + end) >> 1;
  6028. if (halfway == start)
  6029. return -1;
  6030. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  6031. start = halfway;
  6032. else
  6033. end = halfway;
  6034. }
  6035. }
  6036. }
  6037. /** Removes an element from the array.
  6038. This will remove the element at a given index, and move back
  6039. all the subsequent elements to close the gap.
  6040. If the index passed in is out-of-range, nothing will happen.
  6041. @param indexToRemove the index of the element to remove
  6042. @returns the element that has been removed
  6043. @see removeValue, removeRange
  6044. */
  6045. ElementType remove (const int indexToRemove)
  6046. {
  6047. const ScopedLockType lock (getLock());
  6048. if (isPositiveAndBelow (indexToRemove, numUsed))
  6049. {
  6050. --numUsed;
  6051. ElementType* const e = data.elements + indexToRemove;
  6052. ElementType removed (*e);
  6053. e->~ElementType();
  6054. const int numberToShift = numUsed - indexToRemove;
  6055. if (numberToShift > 0)
  6056. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  6057. if ((numUsed << 1) < data.numAllocated)
  6058. minimiseStorageOverheads();
  6059. return removed;
  6060. }
  6061. else
  6062. {
  6063. return ElementType();
  6064. }
  6065. }
  6066. /** Removes an item from the array.
  6067. This will remove the first occurrence of the given element from the array.
  6068. If the item isn't found, no action is taken.
  6069. @param valueToRemove the object to try to remove
  6070. @see remove, removeRange
  6071. */
  6072. void removeValue (ParameterType valueToRemove)
  6073. {
  6074. const ScopedLockType lock (getLock());
  6075. ElementType* const e = data.elements;
  6076. for (int i = 0; i < numUsed; ++i)
  6077. {
  6078. if (valueToRemove == e[i])
  6079. {
  6080. remove (i);
  6081. break;
  6082. }
  6083. }
  6084. }
  6085. /** Removes a range of elements from the array.
  6086. This will remove a set of elements, starting from the given index,
  6087. and move subsequent elements down to close the gap.
  6088. If the range extends beyond the bounds of the array, it will
  6089. be safely clipped to the size of the array.
  6090. @param startIndex the index of the first element to remove
  6091. @param numberToRemove how many elements should be removed
  6092. @see remove, removeValue
  6093. */
  6094. void removeRange (int startIndex, int numberToRemove)
  6095. {
  6096. const ScopedLockType lock (getLock());
  6097. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  6098. startIndex = jlimit (0, numUsed, startIndex);
  6099. if (endIndex > startIndex)
  6100. {
  6101. ElementType* const e = data.elements + startIndex;
  6102. numberToRemove = endIndex - startIndex;
  6103. for (int i = 0; i < numberToRemove; ++i)
  6104. e[i].~ElementType();
  6105. const int numToShift = numUsed - endIndex;
  6106. if (numToShift > 0)
  6107. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  6108. numUsed -= numberToRemove;
  6109. if ((numUsed << 1) < data.numAllocated)
  6110. minimiseStorageOverheads();
  6111. }
  6112. }
  6113. /** Removes the last n elements from the array.
  6114. @param howManyToRemove how many elements to remove from the end of the array
  6115. @see remove, removeValue, removeRange
  6116. */
  6117. void removeLast (int howManyToRemove = 1)
  6118. {
  6119. const ScopedLockType lock (getLock());
  6120. if (howManyToRemove > numUsed)
  6121. howManyToRemove = numUsed;
  6122. for (int i = 1; i <= howManyToRemove; ++i)
  6123. data.elements [numUsed - i].~ElementType();
  6124. numUsed -= howManyToRemove;
  6125. if ((numUsed << 1) < data.numAllocated)
  6126. minimiseStorageOverheads();
  6127. }
  6128. /** Removes any elements which are also in another array.
  6129. @param otherArray the other array in which to look for elements to remove
  6130. @see removeValuesNotIn, remove, removeValue, removeRange
  6131. */
  6132. template <class OtherArrayType>
  6133. void removeValuesIn (const OtherArrayType& otherArray)
  6134. {
  6135. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  6136. const ScopedLockType lock2 (getLock());
  6137. if (this == &otherArray)
  6138. {
  6139. clear();
  6140. }
  6141. else
  6142. {
  6143. if (otherArray.size() > 0)
  6144. {
  6145. for (int i = numUsed; --i >= 0;)
  6146. if (otherArray.contains (data.elements [i]))
  6147. remove (i);
  6148. }
  6149. }
  6150. }
  6151. /** Removes any elements which are not found in another array.
  6152. Only elements which occur in this other array will be retained.
  6153. @param otherArray the array in which to look for elements NOT to remove
  6154. @see removeValuesIn, remove, removeValue, removeRange
  6155. */
  6156. template <class OtherArrayType>
  6157. void removeValuesNotIn (const OtherArrayType& otherArray)
  6158. {
  6159. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  6160. const ScopedLockType lock2 (getLock());
  6161. if (this != &otherArray)
  6162. {
  6163. if (otherArray.size() <= 0)
  6164. {
  6165. clear();
  6166. }
  6167. else
  6168. {
  6169. for (int i = numUsed; --i >= 0;)
  6170. if (! otherArray.contains (data.elements [i]))
  6171. remove (i);
  6172. }
  6173. }
  6174. }
  6175. /** Swaps over two elements in the array.
  6176. This swaps over the elements found at the two indexes passed in.
  6177. If either index is out-of-range, this method will do nothing.
  6178. @param index1 index of one of the elements to swap
  6179. @param index2 index of the other element to swap
  6180. */
  6181. void swap (const int index1,
  6182. const int index2)
  6183. {
  6184. const ScopedLockType lock (getLock());
  6185. if (isPositiveAndBelow (index1, numUsed)
  6186. && isPositiveAndBelow (index2, numUsed))
  6187. {
  6188. swapVariables (data.elements [index1],
  6189. data.elements [index2]);
  6190. }
  6191. }
  6192. /** Moves one of the values to a different position.
  6193. This will move the value to a specified index, shuffling along
  6194. any intervening elements as required.
  6195. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  6196. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  6197. @param currentIndex the index of the value to be moved. If this isn't a
  6198. valid index, then nothing will be done
  6199. @param newIndex the index at which you'd like this value to end up. If this
  6200. is less than zero, the value will be moved to the end
  6201. of the array
  6202. */
  6203. void move (const int currentIndex, int newIndex) noexcept
  6204. {
  6205. if (currentIndex != newIndex)
  6206. {
  6207. const ScopedLockType lock (getLock());
  6208. if (isPositiveAndBelow (currentIndex, numUsed))
  6209. {
  6210. if (! isPositiveAndBelow (newIndex, numUsed))
  6211. newIndex = numUsed - 1;
  6212. char tempCopy [sizeof (ElementType)];
  6213. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  6214. if (newIndex > currentIndex)
  6215. {
  6216. memmove (data.elements + currentIndex,
  6217. data.elements + currentIndex + 1,
  6218. (newIndex - currentIndex) * sizeof (ElementType));
  6219. }
  6220. else
  6221. {
  6222. memmove (data.elements + newIndex + 1,
  6223. data.elements + newIndex,
  6224. (currentIndex - newIndex) * sizeof (ElementType));
  6225. }
  6226. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  6227. }
  6228. }
  6229. }
  6230. /** Reduces the amount of storage being used by the array.
  6231. Arrays typically allocate slightly more storage than they need, and after
  6232. removing elements, they may have quite a lot of unused space allocated.
  6233. This method will reduce the amount of allocated storage to a minimum.
  6234. */
  6235. void minimiseStorageOverheads()
  6236. {
  6237. const ScopedLockType lock (getLock());
  6238. data.shrinkToNoMoreThan (numUsed);
  6239. }
  6240. /** Increases the array's internal storage to hold a minimum number of elements.
  6241. Calling this before adding a large known number of elements means that
  6242. the array won't have to keep dynamically resizing itself as the elements
  6243. are added, and it'll therefore be more efficient.
  6244. */
  6245. void ensureStorageAllocated (const int minNumElements)
  6246. {
  6247. const ScopedLockType lock (getLock());
  6248. data.ensureAllocatedSize (minNumElements);
  6249. }
  6250. /** Sorts the elements in the array.
  6251. This will use a comparator object to sort the elements into order. The object
  6252. passed must have a method of the form:
  6253. @code
  6254. int compareElements (ElementType first, ElementType second);
  6255. @endcode
  6256. ..and this method must return:
  6257. - a value of < 0 if the first comes before the second
  6258. - a value of 0 if the two objects are equivalent
  6259. - a value of > 0 if the second comes before the first
  6260. To improve performance, the compareElements() method can be declared as static or const.
  6261. @param comparator the comparator to use for comparing elements.
  6262. @param retainOrderOfEquivalentItems if this is true, then items
  6263. which the comparator says are equivalent will be
  6264. kept in the order in which they currently appear
  6265. in the array. This is slower to perform, but may
  6266. be important in some cases. If it's false, a faster
  6267. algorithm is used, but equivalent elements may be
  6268. rearranged.
  6269. @see addSorted, indexOfSorted, sortArray
  6270. */
  6271. template <class ElementComparator>
  6272. void sort (ElementComparator& comparator,
  6273. const bool retainOrderOfEquivalentItems = false) const
  6274. {
  6275. const ScopedLockType lock (getLock());
  6276. (void) comparator; // if you pass in an object with a static compareElements() method, this
  6277. // avoids getting warning messages about the parameter being unused
  6278. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  6279. }
  6280. /** Returns the CriticalSection that locks this array.
  6281. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  6282. an object of ScopedLockType as an RAII lock for it.
  6283. */
  6284. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  6285. /** Returns the type of scoped lock to use for locking this array */
  6286. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  6287. private:
  6288. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  6289. int numUsed;
  6290. };
  6291. #endif // __JUCE_ARRAY_JUCEHEADER__
  6292. /*** End of inlined file: juce_Array.h ***/
  6293. #endif
  6294. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6295. #endif
  6296. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6297. /*** Start of inlined file: juce_DynamicObject.h ***/
  6298. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6299. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6300. /*** Start of inlined file: juce_NamedValueSet.h ***/
  6301. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  6302. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  6303. /*** Start of inlined file: juce_Variant.h ***/
  6304. #ifndef __JUCE_VARIANT_JUCEHEADER__
  6305. #define __JUCE_VARIANT_JUCEHEADER__
  6306. /*** Start of inlined file: juce_Identifier.h ***/
  6307. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  6308. #define __JUCE_IDENTIFIER_JUCEHEADER__
  6309. /*** Start of inlined file: juce_StringPool.h ***/
  6310. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  6311. #define __JUCE_STRINGPOOL_JUCEHEADER__
  6312. /**
  6313. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  6314. comparison speed when dealing with many duplicate strings.
  6315. When you add a string to a pool using getPooledString, it'll return a character
  6316. array containing the same string. This array is owned by the pool, and the same array
  6317. is returned every time a matching string is asked for. This means that it's trivial to
  6318. compare two pooled strings for equality, as you can simply compare their pointers. It
  6319. also cuts down on storage if you're using many copies of the same string.
  6320. */
  6321. class JUCE_API StringPool
  6322. {
  6323. public:
  6324. /** Creates an empty pool. */
  6325. StringPool() noexcept;
  6326. /** Destructor */
  6327. ~StringPool();
  6328. /** Returns a pointer to a copy of the string that is passed in.
  6329. The pool will always return the same pointer when asked for a string that matches it.
  6330. The pool will own all the pointers that it returns, deleting them when the pool itself
  6331. is deleted.
  6332. */
  6333. const String::CharPointerType getPooledString (const String& original);
  6334. /** Returns a pointer to a copy of the string that is passed in.
  6335. The pool will always return the same pointer when asked for a string that matches it.
  6336. The pool will own all the pointers that it returns, deleting them when the pool itself
  6337. is deleted.
  6338. */
  6339. const String::CharPointerType getPooledString (const char* original);
  6340. /** Returns a pointer to a copy of the string that is passed in.
  6341. The pool will always return the same pointer when asked for a string that matches it.
  6342. The pool will own all the pointers that it returns, deleting them when the pool itself
  6343. is deleted.
  6344. */
  6345. const String::CharPointerType getPooledString (const wchar_t* original);
  6346. /** Returns the number of strings in the pool. */
  6347. int size() const noexcept;
  6348. /** Returns one of the strings in the pool, by index. */
  6349. const String::CharPointerType operator[] (int index) const noexcept;
  6350. private:
  6351. Array <String> strings;
  6352. };
  6353. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  6354. /*** End of inlined file: juce_StringPool.h ***/
  6355. /**
  6356. Represents a string identifier, designed for accessing properties by name.
  6357. Identifier objects are very light and fast to copy, but slower to initialise
  6358. from a string, so it's much faster to keep a static identifier object to refer
  6359. to frequently-used names, rather than constructing them each time you need it.
  6360. @see NamedPropertySet, ValueTree
  6361. */
  6362. class JUCE_API Identifier
  6363. {
  6364. public:
  6365. /** Creates a null identifier. */
  6366. Identifier() noexcept;
  6367. /** Creates an identifier with a specified name.
  6368. Because this name may need to be used in contexts such as script variables or XML
  6369. tags, it must only contain ascii letters and digits, or the underscore character.
  6370. */
  6371. Identifier (const char* name);
  6372. /** Creates an identifier with a specified name.
  6373. Because this name may need to be used in contexts such as script variables or XML
  6374. tags, it must only contain ascii letters and digits, or the underscore character.
  6375. */
  6376. Identifier (const String& name);
  6377. /** Creates a copy of another identifier. */
  6378. Identifier (const Identifier& other) noexcept;
  6379. /** Creates a copy of another identifier. */
  6380. Identifier& operator= (const Identifier& other) noexcept;
  6381. /** Destructor */
  6382. ~Identifier();
  6383. /** Compares two identifiers. This is a very fast operation. */
  6384. inline bool operator== (const Identifier& other) const noexcept { return name == other.name; }
  6385. /** Compares two identifiers. This is a very fast operation. */
  6386. inline bool operator!= (const Identifier& other) const noexcept { return name != other.name; }
  6387. /** Returns this identifier as a string. */
  6388. const String toString() const { return name; }
  6389. /** Returns this identifier's raw string pointer. */
  6390. operator const String::CharPointerType() const noexcept { return name; }
  6391. private:
  6392. String::CharPointerType name;
  6393. static StringPool& getPool();
  6394. };
  6395. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  6396. /*** End of inlined file: juce_Identifier.h ***/
  6397. /*** Start of inlined file: juce_OutputStream.h ***/
  6398. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6399. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6400. /*** Start of inlined file: juce_NewLine.h ***/
  6401. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  6402. #define __JUCE_NEWLINE_JUCEHEADER__
  6403. /** This class is used for represent a new-line character sequence.
  6404. To write a new-line to a stream, you can use the predefined 'newLine' variable, e.g.
  6405. @code
  6406. myOutputStream << "Hello World" << newLine << newLine;
  6407. @endcode
  6408. The exact character sequence that will be used for the new-line can be set and
  6409. retrieved with OutputStream::setNewLineString() and OutputStream::getNewLineString().
  6410. */
  6411. class JUCE_API NewLine
  6412. {
  6413. public:
  6414. /** Returns the default new-line sequence that the library uses.
  6415. @see OutputStream::setNewLineString()
  6416. */
  6417. static const char* getDefault() noexcept { return "\r\n"; }
  6418. /** Returns the default new-line sequence that the library uses.
  6419. @see getDefault()
  6420. */
  6421. operator const String() const { return getDefault(); }
  6422. };
  6423. /** An predefined object representing a new-line, which can be written to a string or stream.
  6424. To write a new-line to a stream, you can use the predefined 'newLine' variable like this:
  6425. @code
  6426. myOutputStream << "Hello World" << newLine << newLine;
  6427. @endcode
  6428. */
  6429. extern NewLine newLine;
  6430. /** Writes a new-line sequence to a string.
  6431. You can use the predefined object 'newLine' to invoke this, e.g.
  6432. @code
  6433. myString << "Hello World" << newLine << newLine;
  6434. @endcode
  6435. */
  6436. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&);
  6437. #endif // __JUCE_NEWLINE_JUCEHEADER__
  6438. /*** End of inlined file: juce_NewLine.h ***/
  6439. /*** Start of inlined file: juce_InputStream.h ***/
  6440. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6441. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6442. /*** Start of inlined file: juce_MemoryBlock.h ***/
  6443. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  6444. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  6445. /**
  6446. A class to hold a resizable block of raw data.
  6447. */
  6448. class JUCE_API MemoryBlock
  6449. {
  6450. public:
  6451. /** Create an uninitialised block with 0 size. */
  6452. MemoryBlock() noexcept;
  6453. /** Creates a memory block with a given initial size.
  6454. @param initialSize the size of block to create
  6455. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  6456. */
  6457. MemoryBlock (const size_t initialSize,
  6458. bool initialiseToZero = false);
  6459. /** Creates a copy of another memory block. */
  6460. MemoryBlock (const MemoryBlock& other);
  6461. /** Creates a memory block using a copy of a block of data.
  6462. @param dataToInitialiseFrom some data to copy into this block
  6463. @param sizeInBytes how much space to use
  6464. */
  6465. MemoryBlock (const void* dataToInitialiseFrom, size_t sizeInBytes);
  6466. /** Destructor. */
  6467. ~MemoryBlock() noexcept;
  6468. /** Copies another memory block onto this one.
  6469. This block will be resized and copied to exactly match the other one.
  6470. */
  6471. MemoryBlock& operator= (const MemoryBlock& other);
  6472. /** Compares two memory blocks.
  6473. @returns true only if the two blocks are the same size and have identical contents.
  6474. */
  6475. bool operator== (const MemoryBlock& other) const noexcept;
  6476. /** Compares two memory blocks.
  6477. @returns true if the two blocks are different sizes or have different contents.
  6478. */
  6479. bool operator!= (const MemoryBlock& other) const noexcept;
  6480. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  6481. */
  6482. bool matches (const void* data, size_t dataSize) const noexcept;
  6483. /** Returns a void pointer to the data.
  6484. Note that the pointer returned will probably become invalid when the
  6485. block is resized.
  6486. */
  6487. void* getData() const noexcept { return data; }
  6488. /** Returns a byte from the memory block.
  6489. This returns a reference, so you can also use it to set a byte.
  6490. */
  6491. template <typename Type>
  6492. char& operator[] (const Type offset) const noexcept { return data [offset]; }
  6493. /** Returns the block's current allocated size, in bytes. */
  6494. size_t getSize() const noexcept { return size; }
  6495. /** Resizes the memory block.
  6496. This will try to keep as much of the block's current content as it can,
  6497. and can optionally be made to clear any new space that gets allocated at
  6498. the end of the block.
  6499. @param newSize the new desired size for the block
  6500. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  6501. whether to clear the new section or just leave it
  6502. uninitialised
  6503. @see ensureSize
  6504. */
  6505. void setSize (const size_t newSize,
  6506. bool initialiseNewSpaceToZero = false);
  6507. /** Increases the block's size only if it's smaller than a given size.
  6508. @param minimumSize if the block is already bigger than this size, no action
  6509. will be taken; otherwise it will be increased to this size
  6510. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  6511. whether to clear the new section or just leave it
  6512. uninitialised
  6513. @see setSize
  6514. */
  6515. void ensureSize (const size_t minimumSize,
  6516. bool initialiseNewSpaceToZero = false);
  6517. /** Fills the entire memory block with a repeated byte value.
  6518. This is handy for clearing a block of memory to zero.
  6519. */
  6520. void fillWith (uint8 valueToUse) noexcept;
  6521. /** Adds another block of data to the end of this one.
  6522. This block's size will be increased accordingly.
  6523. */
  6524. void append (const void* data, size_t numBytes);
  6525. /** Exchanges the contents of this and another memory block.
  6526. No actual copying is required for this, so it's very fast.
  6527. */
  6528. void swapWith (MemoryBlock& other) noexcept;
  6529. /** Copies data into this MemoryBlock from a memory address.
  6530. @param srcData the memory location of the data to copy into this block
  6531. @param destinationOffset the offset in this block at which the data being copied should begin
  6532. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  6533. it will be clipped so not to do anything nasty)
  6534. */
  6535. void copyFrom (const void* srcData,
  6536. int destinationOffset,
  6537. size_t numBytes) noexcept;
  6538. /** Copies data from this MemoryBlock to a memory address.
  6539. @param destData the memory location to write to
  6540. @param sourceOffset the offset within this block from which the copied data will be read
  6541. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  6542. zeros will be used for that portion of the data)
  6543. */
  6544. void copyTo (void* destData,
  6545. int sourceOffset,
  6546. size_t numBytes) const noexcept;
  6547. /** Chops out a section of the block.
  6548. This will remove a section of the memory block and close the gap around it,
  6549. shifting any subsequent data downwards and reducing the size of the block.
  6550. If the range specified goes beyond the size of the block, it will be clipped.
  6551. */
  6552. void removeSection (size_t startByte, size_t numBytesToRemove);
  6553. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  6554. characters in the system's default encoding. */
  6555. const String toString() const;
  6556. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  6557. The block will be resized to the number of valid bytes read from the string.
  6558. Non-hex characters in the string will be ignored.
  6559. @see String::toHexString()
  6560. */
  6561. void loadFromHexString (const String& sourceHexString);
  6562. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  6563. void setBitRange (size_t bitRangeStart,
  6564. size_t numBits,
  6565. int binaryNumberToApply) noexcept;
  6566. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  6567. int getBitRange (size_t bitRangeStart,
  6568. size_t numBitsToRead) const noexcept;
  6569. /** Returns a string of characters that represent the binary contents of this block.
  6570. Uses a 64-bit encoding system to allow binary data to be turned into a string
  6571. of simple non-extended characters, e.g. for storage in XML.
  6572. @see fromBase64Encoding
  6573. */
  6574. const String toBase64Encoding() const;
  6575. /** Takes a string of encoded characters and turns it into binary data.
  6576. The string passed in must have been created by to64BitEncoding(), and this
  6577. block will be resized to recreate the original data block.
  6578. @see toBase64Encoding
  6579. */
  6580. bool fromBase64Encoding (const String& encodedString);
  6581. private:
  6582. HeapBlock <char> data;
  6583. size_t size;
  6584. static const char* const encodingTable;
  6585. JUCE_LEAK_DETECTOR (MemoryBlock);
  6586. };
  6587. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  6588. /*** End of inlined file: juce_MemoryBlock.h ***/
  6589. /** The base class for streams that read data.
  6590. Input and output streams are used throughout the library - subclasses can override
  6591. some or all of the virtual functions to implement their behaviour.
  6592. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6593. */
  6594. class JUCE_API InputStream
  6595. {
  6596. public:
  6597. /** Destructor. */
  6598. virtual ~InputStream() {}
  6599. /** Returns the total number of bytes available for reading in this stream.
  6600. Note that this is the number of bytes available from the start of the
  6601. stream, not from the current position.
  6602. If the size of the stream isn't actually known, this may return -1.
  6603. */
  6604. virtual int64 getTotalLength() = 0;
  6605. /** Returns true if the stream has no more data to read. */
  6606. virtual bool isExhausted() = 0;
  6607. /** Reads a set of bytes from the stream into a memory buffer.
  6608. This is the only read method that subclasses actually need to implement, as the
  6609. InputStream base class implements the other read methods in terms of this one (although
  6610. it's often more efficient for subclasses to implement them directly).
  6611. @param destBuffer the destination buffer for the data
  6612. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6613. memory block passed in is big enough to contain this
  6614. many bytes.
  6615. @returns the actual number of bytes that were read, which may be less than
  6616. maxBytesToRead if the stream is exhausted before it gets that far
  6617. */
  6618. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  6619. /** Reads a byte from the stream.
  6620. If the stream is exhausted, this will return zero.
  6621. @see OutputStream::writeByte
  6622. */
  6623. virtual char readByte();
  6624. /** Reads a boolean from the stream.
  6625. The bool is encoded as a single byte - 1 for true, 0 for false.
  6626. If the stream is exhausted, this will return false.
  6627. @see OutputStream::writeBool
  6628. */
  6629. virtual bool readBool();
  6630. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6631. If the next two bytes read are byte1 and byte2, this returns
  6632. (byte1 | (byte2 << 8)).
  6633. If the stream is exhausted partway through reading the bytes, this will return zero.
  6634. @see OutputStream::writeShort, readShortBigEndian
  6635. */
  6636. virtual short readShort();
  6637. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6638. If the next two bytes read are byte1 and byte2, this returns
  6639. (byte2 | (byte1 << 8)).
  6640. If the stream is exhausted partway through reading the bytes, this will return zero.
  6641. @see OutputStream::writeShortBigEndian, readShort
  6642. */
  6643. virtual short readShortBigEndian();
  6644. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6645. If the next four bytes are byte1 to byte4, this returns
  6646. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6647. If the stream is exhausted partway through reading the bytes, this will return zero.
  6648. @see OutputStream::writeInt, readIntBigEndian
  6649. */
  6650. virtual int readInt();
  6651. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6652. If the next four bytes are byte1 to byte4, this returns
  6653. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6654. If the stream is exhausted partway through reading the bytes, this will return zero.
  6655. @see OutputStream::writeIntBigEndian, readInt
  6656. */
  6657. virtual int readIntBigEndian();
  6658. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6659. If the next eight bytes are byte1 to byte8, this returns
  6660. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6661. If the stream is exhausted partway through reading the bytes, this will return zero.
  6662. @see OutputStream::writeInt64, readInt64BigEndian
  6663. */
  6664. virtual int64 readInt64();
  6665. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6666. If the next eight bytes are byte1 to byte8, this returns
  6667. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6668. If the stream is exhausted partway through reading the bytes, this will return zero.
  6669. @see OutputStream::writeInt64BigEndian, readInt64
  6670. */
  6671. virtual int64 readInt64BigEndian();
  6672. /** Reads four bytes as a 32-bit floating point value.
  6673. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6674. If the stream is exhausted partway through reading the bytes, this will return zero.
  6675. @see OutputStream::writeFloat, readDouble
  6676. */
  6677. virtual float readFloat();
  6678. /** Reads four bytes as a 32-bit floating point value.
  6679. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6680. If the stream is exhausted partway through reading the bytes, this will return zero.
  6681. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6682. */
  6683. virtual float readFloatBigEndian();
  6684. /** Reads eight bytes as a 64-bit floating point value.
  6685. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6686. If the stream is exhausted partway through reading the bytes, this will return zero.
  6687. @see OutputStream::writeDouble, readFloat
  6688. */
  6689. virtual double readDouble();
  6690. /** Reads eight bytes as a 64-bit floating point value.
  6691. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6692. If the stream is exhausted partway through reading the bytes, this will return zero.
  6693. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6694. */
  6695. virtual double readDoubleBigEndian();
  6696. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6697. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6698. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6699. @see OutputStream::writeCompressedInt()
  6700. */
  6701. virtual int readCompressedInt();
  6702. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  6703. This will read up to the next "\n" or "\r\n" or end-of-stream.
  6704. After this call, the stream's position will be left pointing to the next character
  6705. following the line-feed, but the linefeeds aren't included in the string that
  6706. is returned.
  6707. */
  6708. virtual const String readNextLine();
  6709. /** Reads a zero-terminated UTF8 string from the stream.
  6710. This will read characters from the stream until it hits a zero character or
  6711. end-of-stream.
  6712. @see OutputStream::writeString, readEntireStreamAsString
  6713. */
  6714. virtual const String readString();
  6715. /** Tries to read the whole stream and turn it into a string.
  6716. This will read from the stream's current position until the end-of-stream, and
  6717. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6718. */
  6719. virtual const String readEntireStreamAsString();
  6720. /** Reads from the stream and appends the data to a MemoryBlock.
  6721. @param destBlock the block to append the data onto
  6722. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6723. of bytes that will be read - if it's negative, data
  6724. will be read until the stream is exhausted.
  6725. @returns the number of bytes that were added to the memory block
  6726. */
  6727. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6728. int maxNumBytesToRead = -1);
  6729. /** Returns the offset of the next byte that will be read from the stream.
  6730. @see setPosition
  6731. */
  6732. virtual int64 getPosition() = 0;
  6733. /** Tries to move the current read position of the stream.
  6734. The position is an absolute number of bytes from the stream's start.
  6735. Some streams might not be able to do this, in which case they should do
  6736. nothing and return false. Others might be able to manage it by resetting
  6737. themselves and skipping to the correct position, although this is
  6738. obviously a bit slow.
  6739. @returns true if the stream manages to reposition itself correctly
  6740. @see getPosition
  6741. */
  6742. virtual bool setPosition (int64 newPosition) = 0;
  6743. /** Reads and discards a number of bytes from the stream.
  6744. Some input streams might implement this efficiently, but the base
  6745. class will just keep reading data until the requisite number of bytes
  6746. have been done.
  6747. */
  6748. virtual void skipNextBytes (int64 numBytesToSkip);
  6749. protected:
  6750. InputStream() noexcept {}
  6751. private:
  6752. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InputStream);
  6753. };
  6754. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6755. /*** End of inlined file: juce_InputStream.h ***/
  6756. class File;
  6757. /**
  6758. The base class for streams that write data to some kind of destination.
  6759. Input and output streams are used throughout the library - subclasses can override
  6760. some or all of the virtual functions to implement their behaviour.
  6761. @see InputStream, MemoryOutputStream, FileOutputStream
  6762. */
  6763. class JUCE_API OutputStream
  6764. {
  6765. protected:
  6766. OutputStream();
  6767. public:
  6768. /** Destructor.
  6769. Some subclasses might want to do things like call flush() during their
  6770. destructors.
  6771. */
  6772. virtual ~OutputStream();
  6773. /** If the stream is using a buffer, this will ensure it gets written
  6774. out to the destination. */
  6775. virtual void flush() = 0;
  6776. /** Tries to move the stream's output position.
  6777. Not all streams will be able to seek to a new position - this will return
  6778. false if it fails to work.
  6779. @see getPosition
  6780. */
  6781. virtual bool setPosition (int64 newPosition) = 0;
  6782. /** Returns the stream's current position.
  6783. @see setPosition
  6784. */
  6785. virtual int64 getPosition() = 0;
  6786. /** Writes a block of data to the stream.
  6787. When creating a subclass of OutputStream, this is the only write method
  6788. that needs to be overloaded - the base class has methods for writing other
  6789. types of data which use this to do the work.
  6790. @returns false if the write operation fails for some reason
  6791. */
  6792. virtual bool write (const void* dataToWrite,
  6793. int howManyBytes) = 0;
  6794. /** Writes a single byte to the stream.
  6795. @see InputStream::readByte
  6796. */
  6797. virtual void writeByte (char byte);
  6798. /** Writes a boolean to the stream as a single byte.
  6799. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  6800. @see InputStream::readBool
  6801. */
  6802. virtual void writeBool (bool boolValue);
  6803. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6804. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6805. @see InputStream::readShort
  6806. */
  6807. virtual void writeShort (short value);
  6808. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6809. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6810. @see InputStream::readShortBigEndian
  6811. */
  6812. virtual void writeShortBigEndian (short value);
  6813. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6814. @see InputStream::readInt
  6815. */
  6816. virtual void writeInt (int value);
  6817. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6818. @see InputStream::readIntBigEndian
  6819. */
  6820. virtual void writeIntBigEndian (int value);
  6821. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6822. @see InputStream::readInt64
  6823. */
  6824. virtual void writeInt64 (int64 value);
  6825. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6826. @see InputStream::readInt64BigEndian
  6827. */
  6828. virtual void writeInt64BigEndian (int64 value);
  6829. /** Writes a 32-bit floating point value to the stream in a binary format.
  6830. The binary 32-bit encoding of the float is written as a little-endian int.
  6831. @see InputStream::readFloat
  6832. */
  6833. virtual void writeFloat (float value);
  6834. /** Writes a 32-bit floating point value to the stream in a binary format.
  6835. The binary 32-bit encoding of the float is written as a big-endian int.
  6836. @see InputStream::readFloatBigEndian
  6837. */
  6838. virtual void writeFloatBigEndian (float value);
  6839. /** Writes a 64-bit floating point value to the stream in a binary format.
  6840. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6841. @see InputStream::readDouble
  6842. */
  6843. virtual void writeDouble (double value);
  6844. /** Writes a 64-bit floating point value to the stream in a binary format.
  6845. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6846. @see InputStream::readDoubleBigEndian
  6847. */
  6848. virtual void writeDoubleBigEndian (double value);
  6849. /** Writes a byte to the output stream a given number of times. */
  6850. virtual void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  6851. /** Writes a condensed binary encoding of a 32-bit integer.
  6852. If you're storing a lot of integers which are unlikely to have very large values,
  6853. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6854. under 0xffff only 3 bytes, etc.
  6855. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6856. @see InputStream::readCompressedInt
  6857. */
  6858. virtual void writeCompressedInt (int value);
  6859. /** Stores a string in the stream in a binary format.
  6860. This isn't the method to use if you're trying to append text to the end of a
  6861. text-file! It's intended for storing a string so that it can be retrieved later
  6862. by InputStream::readString().
  6863. It writes the string to the stream as UTF8, including the null termination character.
  6864. For appending text to a file, instead use writeText, or operator<<
  6865. @see InputStream::readString, writeText, operator<<
  6866. */
  6867. virtual void writeString (const String& text);
  6868. /** Writes a string of text to the stream.
  6869. It can either write the text as UTF-8 or UTF-16, and can also add the UTF-16 byte-order-mark
  6870. bytes (0xff, 0xfe) to indicate the endianness (these should only be used at the start
  6871. of a file).
  6872. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6873. */
  6874. virtual void writeText (const String& text,
  6875. bool asUTF16,
  6876. bool writeUTF16ByteOrderMark);
  6877. /** Reads data from an input stream and writes it to this stream.
  6878. @param source the stream to read from
  6879. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6880. less than zero, it will keep reading until the input
  6881. is exhausted)
  6882. */
  6883. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  6884. /** Sets the string that will be written to the stream when the writeNewLine()
  6885. method is called.
  6886. By default this will be set the the value of NewLine::getDefault().
  6887. */
  6888. void setNewLineString (const String& newLineString);
  6889. /** Returns the current new-line string that was set by setNewLineString(). */
  6890. const String& getNewLineString() const noexcept { return newLineString; }
  6891. private:
  6892. String newLineString;
  6893. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OutputStream);
  6894. };
  6895. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6896. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  6897. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6898. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  6899. /** Writes a character to a stream. */
  6900. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  6901. /** Writes a null-terminated text string to a stream. */
  6902. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  6903. /** Writes a block of data from a MemoryBlock to a stream. */
  6904. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  6905. /** Writes the contents of a file to a stream. */
  6906. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  6907. /** Writes a new-line to a stream.
  6908. You can use the predefined symbol 'newLine' to invoke this, e.g.
  6909. @code
  6910. myOutputStream << "Hello World" << newLine << newLine;
  6911. @endcode
  6912. @see OutputStream::setNewLineString
  6913. */
  6914. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&);
  6915. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6916. /*** End of inlined file: juce_OutputStream.h ***/
  6917. #ifndef DOXYGEN
  6918. class ReferenceCountedObject;
  6919. class DynamicObject;
  6920. #endif
  6921. /**
  6922. A variant class, that can be used to hold a range of primitive values.
  6923. A var object can hold a range of simple primitive values, strings, or
  6924. any kind of ReferenceCountedObject. The var class is intended to act like
  6925. the kind of values used in dynamic scripting languages.
  6926. @see DynamicObject
  6927. */
  6928. class JUCE_API var
  6929. {
  6930. public:
  6931. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  6932. typedef Identifier identifier;
  6933. /** Creates a void variant. */
  6934. var() noexcept;
  6935. /** Destructor. */
  6936. ~var() noexcept;
  6937. /** A static var object that can be used where you need an empty variant object. */
  6938. static const var null;
  6939. var (const var& valueToCopy);
  6940. var (int value) noexcept;
  6941. var (int64 value) noexcept;
  6942. var (bool value) noexcept;
  6943. var (double value) noexcept;
  6944. var (const char* value);
  6945. var (const wchar_t* value);
  6946. var (const String& value);
  6947. var (ReferenceCountedObject* object);
  6948. var (MethodFunction method) noexcept;
  6949. var& operator= (const var& valueToCopy);
  6950. var& operator= (int value);
  6951. var& operator= (int64 value);
  6952. var& operator= (bool value);
  6953. var& operator= (double value);
  6954. var& operator= (const char* value);
  6955. var& operator= (const wchar_t* value);
  6956. var& operator= (const String& value);
  6957. var& operator= (ReferenceCountedObject* object);
  6958. var& operator= (MethodFunction method);
  6959. void swapWith (var& other) noexcept;
  6960. operator int() const noexcept;
  6961. operator int64() const noexcept;
  6962. operator bool() const noexcept;
  6963. operator float() const noexcept;
  6964. operator double() const noexcept;
  6965. operator const String() const;
  6966. const String toString() const;
  6967. ReferenceCountedObject* getObject() const noexcept;
  6968. DynamicObject* getDynamicObject() const noexcept;
  6969. bool isVoid() const noexcept;
  6970. bool isInt() const noexcept;
  6971. bool isInt64() const noexcept;
  6972. bool isBool() const noexcept;
  6973. bool isDouble() const noexcept;
  6974. bool isString() const noexcept;
  6975. bool isObject() const noexcept;
  6976. bool isMethod() const noexcept;
  6977. /** Writes a binary representation of this value to a stream.
  6978. The data can be read back later using readFromStream().
  6979. */
  6980. void writeToStream (OutputStream& output) const;
  6981. /** Reads back a stored binary representation of a value.
  6982. The data in the stream must have been written using writeToStream(), or this
  6983. will have unpredictable results.
  6984. */
  6985. static const var readFromStream (InputStream& input);
  6986. /** If this variant is an object, this returns one of its properties. */
  6987. const var operator[] (const Identifier& propertyName) const;
  6988. /** If this variant is an object, this invokes one of its methods with no arguments. */
  6989. const var call (const Identifier& method) const;
  6990. /** If this variant is an object, this invokes one of its methods with one argument. */
  6991. const var call (const Identifier& method, const var& arg1) const;
  6992. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  6993. const var call (const Identifier& method, const var& arg1, const var& arg2) const;
  6994. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  6995. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  6996. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  6997. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  6998. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  6999. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  7000. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  7001. const var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  7002. /** If this variant is a method pointer, this invokes it on a target object. */
  7003. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  7004. /** Returns true if this var has the same value as the one supplied. */
  7005. bool equals (const var& other) const noexcept;
  7006. /** Returns true if this var has the same value and type as the one supplied.
  7007. This differs from equals() because e.g. "0" and 0 will be considered different.
  7008. */
  7009. bool equalsWithSameType (const var& other) const noexcept;
  7010. private:
  7011. class VariantType;
  7012. friend class VariantType;
  7013. class VariantType_Void;
  7014. friend class VariantType_Void;
  7015. class VariantType_Int;
  7016. friend class VariantType_Int;
  7017. class VariantType_Int64;
  7018. friend class VariantType_Int64;
  7019. class VariantType_Double;
  7020. friend class VariantType_Double;
  7021. class VariantType_Float;
  7022. friend class VariantType_Float;
  7023. class VariantType_Bool;
  7024. friend class VariantType_Bool;
  7025. class VariantType_String;
  7026. friend class VariantType_String;
  7027. class VariantType_Object;
  7028. friend class VariantType_Object;
  7029. class VariantType_Method;
  7030. friend class VariantType_Method;
  7031. union ValueUnion
  7032. {
  7033. int intValue;
  7034. int64 int64Value;
  7035. bool boolValue;
  7036. double doubleValue;
  7037. String* stringValue;
  7038. ReferenceCountedObject* objectValue;
  7039. MethodFunction methodValue;
  7040. };
  7041. const VariantType* type;
  7042. ValueUnion value;
  7043. };
  7044. bool operator== (const var& v1, const var& v2) noexcept;
  7045. bool operator!= (const var& v1, const var& v2) noexcept;
  7046. bool operator== (const var& v1, const String& v2);
  7047. bool operator!= (const var& v1, const String& v2);
  7048. bool operator== (const var& v1, const char* v2);
  7049. bool operator!= (const var& v1, const char* v2);
  7050. #endif // __JUCE_VARIANT_JUCEHEADER__
  7051. /*** End of inlined file: juce_Variant.h ***/
  7052. /*** Start of inlined file: juce_LinkedListPointer.h ***/
  7053. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7054. #define __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7055. /**
  7056. Helps to manipulate singly-linked lists of objects.
  7057. For objects that are designed to contain a pointer to the subsequent item in the
  7058. list, this class contains methods to deal with the list. To use it, the ObjectType
  7059. class that it points to must contain a LinkedListPointer called nextListItem, e.g.
  7060. @code
  7061. struct MyObject
  7062. {
  7063. int x, y, z;
  7064. // A linkable object must contain a member with this name and type, which must be
  7065. // accessible by the LinkedListPointer class. (This doesn't mean it has to be public -
  7066. // you could make your class a friend of a LinkedListPointer<MyObject> instead).
  7067. LinkedListPointer<MyObject> nextListItem;
  7068. };
  7069. LinkedListPointer<MyObject> myList;
  7070. myList.append (new MyObject());
  7071. myList.append (new MyObject());
  7072. int numItems = myList.size(); // returns 2
  7073. MyObject* lastInList = myList.getLast();
  7074. @endcode
  7075. */
  7076. template <class ObjectType>
  7077. class LinkedListPointer
  7078. {
  7079. public:
  7080. /** Creates a null pointer to an empty list. */
  7081. LinkedListPointer() noexcept
  7082. : item (nullptr)
  7083. {
  7084. }
  7085. /** Creates a pointer to a list whose head is the item provided. */
  7086. explicit LinkedListPointer (ObjectType* const headItem) noexcept
  7087. : item (headItem)
  7088. {
  7089. }
  7090. /** Sets this pointer to point to a new list. */
  7091. LinkedListPointer& operator= (ObjectType* const newItem) noexcept
  7092. {
  7093. item = newItem;
  7094. return *this;
  7095. }
  7096. /** Returns the item which this pointer points to. */
  7097. inline operator ObjectType*() const noexcept
  7098. {
  7099. return item;
  7100. }
  7101. /** Returns the item which this pointer points to. */
  7102. inline ObjectType* get() const noexcept
  7103. {
  7104. return item;
  7105. }
  7106. /** Returns the last item in the list which this pointer points to.
  7107. This will iterate the list and return the last item found. Obviously the speed
  7108. of this operation will be proportional to the size of the list. If the list is
  7109. empty the return value will be this object.
  7110. If you're planning on appending a number of items to your list, it's much more
  7111. efficient to use the Appender class than to repeatedly call getLast() to find the end.
  7112. */
  7113. LinkedListPointer& getLast() noexcept
  7114. {
  7115. LinkedListPointer* l = this;
  7116. while (l->item != nullptr)
  7117. l = &(l->item->nextListItem);
  7118. return *l;
  7119. }
  7120. /** Returns the number of items in the list.
  7121. Obviously with a simple linked list, getting the size involves iterating the list, so
  7122. this can be a lengthy operation - be careful when using this method in your code.
  7123. */
  7124. int size() const noexcept
  7125. {
  7126. int total = 0;
  7127. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  7128. ++total;
  7129. return total;
  7130. }
  7131. /** Returns the item at a given index in the list.
  7132. Since the only way to find an item is to iterate the list, this operation can obviously
  7133. be slow, depending on its size, so you should be careful when using this in algorithms.
  7134. */
  7135. LinkedListPointer& operator[] (int index) noexcept
  7136. {
  7137. LinkedListPointer* l = this;
  7138. while (--index >= 0 && l->item != nullptr)
  7139. l = &(l->item->nextListItem);
  7140. return *l;
  7141. }
  7142. /** Returns the item at a given index in the list.
  7143. Since the only way to find an item is to iterate the list, this operation can obviously
  7144. be slow, depending on its size, so you should be careful when using this in algorithms.
  7145. */
  7146. const LinkedListPointer& operator[] (int index) const noexcept
  7147. {
  7148. const LinkedListPointer* l = this;
  7149. while (--index >= 0 && l->item != nullptr)
  7150. l = &(l->item->nextListItem);
  7151. return *l;
  7152. }
  7153. /** Returns true if the list contains the given item. */
  7154. bool contains (const ObjectType* const itemToLookFor) const noexcept
  7155. {
  7156. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  7157. if (itemToLookFor == i)
  7158. return true;
  7159. return false;
  7160. }
  7161. /** Inserts an item into the list, placing it before the item that this pointer
  7162. currently points to.
  7163. */
  7164. void insertNext (ObjectType* const newItem)
  7165. {
  7166. jassert (newItem != nullptr);
  7167. jassert (newItem->nextListItem == nullptr);
  7168. newItem->nextListItem = item;
  7169. item = newItem;
  7170. }
  7171. /** Inserts an item at a numeric index in the list.
  7172. Obviously this will involve iterating the list to find the item at the given index,
  7173. so be careful about the impact this may have on execution time.
  7174. */
  7175. void insertAtIndex (int index, ObjectType* newItem)
  7176. {
  7177. jassert (newItem != nullptr);
  7178. LinkedListPointer* l = this;
  7179. while (index != 0 && l->item != nullptr)
  7180. {
  7181. l = &(l->item->nextListItem);
  7182. --index;
  7183. }
  7184. l->insertNext (newItem);
  7185. }
  7186. /** Replaces the object that this pointer points to, appending the rest of the list to
  7187. the new object, and returning the old one.
  7188. */
  7189. ObjectType* replaceNext (ObjectType* const newItem) noexcept
  7190. {
  7191. jassert (newItem != nullptr);
  7192. jassert (newItem->nextListItem == nullptr);
  7193. ObjectType* const oldItem = item;
  7194. item = newItem;
  7195. item->nextListItem = oldItem->nextListItem.item;
  7196. oldItem->nextListItem = (ObjectType*) 0;
  7197. return oldItem;
  7198. }
  7199. /** Adds an item to the end of the list.
  7200. This operation involves iterating the whole list, so can be slow - if you need to
  7201. append a number of items to your list, it's much more efficient to use the Appender
  7202. class than to repeatedly call append().
  7203. */
  7204. void append (ObjectType* const newItem)
  7205. {
  7206. getLast().item = newItem;
  7207. }
  7208. /** Creates copies of all the items in another list and adds them to this one.
  7209. This will use the ObjectType's copy constructor to try to create copies of each
  7210. item in the other list, and appends them to this list.
  7211. */
  7212. void addCopyOfList (const LinkedListPointer& other)
  7213. {
  7214. LinkedListPointer* insertPoint = this;
  7215. for (ObjectType* i = other.item; i != nullptr; i = i->nextListItem)
  7216. {
  7217. insertPoint->insertNext (new ObjectType (*i));
  7218. insertPoint = &(insertPoint->item->nextListItem);
  7219. }
  7220. }
  7221. /** Removes the head item from the list.
  7222. This won't delete the object that is removed, but returns it, so the caller can
  7223. delete it if necessary.
  7224. */
  7225. ObjectType* removeNext() noexcept
  7226. {
  7227. ObjectType* const oldItem = item;
  7228. if (oldItem != nullptr)
  7229. {
  7230. item = oldItem->nextListItem;
  7231. oldItem->nextListItem = (ObjectType*) 0;
  7232. }
  7233. return oldItem;
  7234. }
  7235. /** Removes a specific item from the list.
  7236. Note that this will not delete the item, it simply unlinks it from the list.
  7237. */
  7238. void remove (ObjectType* const itemToRemove)
  7239. {
  7240. LinkedListPointer* const l = findPointerTo (itemToRemove);
  7241. if (l != nullptr)
  7242. l->removeNext();
  7243. }
  7244. /** Iterates the list, calling the delete operator on all of its elements and
  7245. leaving this pointer empty.
  7246. */
  7247. void deleteAll()
  7248. {
  7249. while (item != nullptr)
  7250. {
  7251. ObjectType* const oldItem = item;
  7252. item = oldItem->nextListItem;
  7253. delete oldItem;
  7254. }
  7255. }
  7256. /** Finds a pointer to a given item.
  7257. If the item is found in the list, this returns the pointer that points to it. If
  7258. the item isn't found, this returns null.
  7259. */
  7260. LinkedListPointer* findPointerTo (ObjectType* const itemToLookFor) noexcept
  7261. {
  7262. LinkedListPointer* l = this;
  7263. while (l->item != nullptr)
  7264. {
  7265. if (l->item == itemToLookFor)
  7266. return l;
  7267. l = &(l->item->nextListItem);
  7268. }
  7269. return nullptr;
  7270. }
  7271. /** Copies the items in the list to an array.
  7272. The destArray must contain enough elements to hold the entire list - no checks are
  7273. made for this!
  7274. */
  7275. void copyToArray (ObjectType** destArray) const noexcept
  7276. {
  7277. jassert (destArray != nullptr);
  7278. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  7279. *destArray++ = i;
  7280. }
  7281. /**
  7282. Allows efficient repeated insertions into a list.
  7283. You can create an Appender object which points to the last element in your
  7284. list, and then repeatedly call Appender::append() to add items to the end
  7285. of the list in O(1) time.
  7286. */
  7287. class Appender
  7288. {
  7289. public:
  7290. /** Creates an appender which will add items to the given list.
  7291. */
  7292. Appender (LinkedListPointer& endOfListPointer) noexcept
  7293. : endOfList (&endOfListPointer)
  7294. {
  7295. // This can only be used to add to the end of a list.
  7296. jassert (endOfListPointer.item == nullptr);
  7297. }
  7298. /** Appends an item to the list. */
  7299. void append (ObjectType* const newItem) noexcept
  7300. {
  7301. *endOfList = newItem;
  7302. endOfList = &(newItem->nextListItem);
  7303. }
  7304. private:
  7305. LinkedListPointer* endOfList;
  7306. JUCE_DECLARE_NON_COPYABLE (Appender);
  7307. };
  7308. private:
  7309. ObjectType* item;
  7310. JUCE_DECLARE_NON_COPYABLE (LinkedListPointer);
  7311. };
  7312. #endif // __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7313. /*** End of inlined file: juce_LinkedListPointer.h ***/
  7314. class XmlElement;
  7315. /** Holds a set of named var objects.
  7316. This can be used as a basic structure to hold a set of var object, which can
  7317. be retrieved by using their identifier.
  7318. */
  7319. class JUCE_API NamedValueSet
  7320. {
  7321. public:
  7322. /** Creates an empty set. */
  7323. NamedValueSet() noexcept;
  7324. /** Creates a copy of another set. */
  7325. NamedValueSet (const NamedValueSet& other);
  7326. /** Replaces this set with a copy of another set. */
  7327. NamedValueSet& operator= (const NamedValueSet& other);
  7328. /** Destructor. */
  7329. ~NamedValueSet();
  7330. bool operator== (const NamedValueSet& other) const;
  7331. bool operator!= (const NamedValueSet& other) const;
  7332. /** Returns the total number of values that the set contains. */
  7333. int size() const noexcept;
  7334. /** Returns the value of a named item.
  7335. If the name isn't found, this will return a void variant.
  7336. @see getProperty
  7337. */
  7338. const var& operator[] (const Identifier& name) const;
  7339. /** Tries to return the named value, but if no such value is found, this will
  7340. instead return the supplied default value.
  7341. */
  7342. const var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  7343. /** Changes or adds a named value.
  7344. @returns true if a value was changed or added; false if the
  7345. value was already set the the value passed-in.
  7346. */
  7347. bool set (const Identifier& name, const var& newValue);
  7348. /** Returns true if the set contains an item with the specified name. */
  7349. bool contains (const Identifier& name) const;
  7350. /** Removes a value from the set.
  7351. @returns true if a value was removed; false if there was no value
  7352. with the name that was given.
  7353. */
  7354. bool remove (const Identifier& name);
  7355. /** Returns the name of the value at a given index.
  7356. The index must be between 0 and size() - 1.
  7357. */
  7358. const Identifier getName (int index) const;
  7359. /** Returns the value of the item at a given index.
  7360. The index must be between 0 and size() - 1.
  7361. */
  7362. const var getValueAt (int index) const;
  7363. /** Removes all values. */
  7364. void clear();
  7365. /** Returns a pointer to the var that holds a named value, or null if there is
  7366. no value with this name.
  7367. Do not use this method unless you really need access to the internal var object
  7368. for some reason - for normal reading and writing always prefer operator[]() and set().
  7369. */
  7370. var* getVarPointer (const Identifier& name) const;
  7371. /** Sets properties to the values of all of an XML element's attributes. */
  7372. void setFromXmlAttributes (const XmlElement& xml);
  7373. /** Sets attributes in an XML element corresponding to each of this object's
  7374. properties.
  7375. */
  7376. void copyToXmlAttributes (XmlElement& xml) const;
  7377. private:
  7378. class NamedValue
  7379. {
  7380. public:
  7381. NamedValue() noexcept;
  7382. NamedValue (const NamedValue&);
  7383. NamedValue (const Identifier& name, const var& value);
  7384. NamedValue& operator= (const NamedValue&);
  7385. bool operator== (const NamedValue& other) const noexcept;
  7386. LinkedListPointer<NamedValue> nextListItem;
  7387. Identifier name;
  7388. var value;
  7389. private:
  7390. JUCE_LEAK_DETECTOR (NamedValue);
  7391. };
  7392. friend class LinkedListPointer<NamedValue>;
  7393. LinkedListPointer<NamedValue> values;
  7394. };
  7395. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  7396. /*** End of inlined file: juce_NamedValueSet.h ***/
  7397. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  7398. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7399. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7400. /**
  7401. Adds reference-counting to an object.
  7402. To add reference-counting to a class, derive it from this class, and
  7403. use the ReferenceCountedObjectPtr class to point to it.
  7404. e.g. @code
  7405. class MyClass : public ReferenceCountedObject
  7406. {
  7407. void foo();
  7408. // This is a neat way of declaring a typedef for a pointer class,
  7409. // rather than typing out the full templated name each time..
  7410. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7411. };
  7412. MyClass::Ptr p = new MyClass();
  7413. MyClass::Ptr p2 = p;
  7414. p = nullptr;
  7415. p2->foo();
  7416. @endcode
  7417. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7418. careful not to delete the object manually.
  7419. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  7420. */
  7421. class JUCE_API ReferenceCountedObject
  7422. {
  7423. public:
  7424. /** Increments the object's reference count.
  7425. This is done automatically by the smart pointer, but is public just
  7426. in case it's needed for nefarious purposes.
  7427. */
  7428. inline void incReferenceCount() noexcept
  7429. {
  7430. ++refCount;
  7431. }
  7432. /** Decreases the object's reference count.
  7433. If the count gets to zero, the object will be deleted.
  7434. */
  7435. inline void decReferenceCount() noexcept
  7436. {
  7437. jassert (getReferenceCount() > 0);
  7438. if (--refCount == 0)
  7439. delete this;
  7440. }
  7441. /** Returns the object's current reference count. */
  7442. inline int getReferenceCount() const noexcept
  7443. {
  7444. return refCount.get();
  7445. }
  7446. protected:
  7447. /** Creates the reference-counted object (with an initial ref count of zero). */
  7448. ReferenceCountedObject()
  7449. {
  7450. }
  7451. /** Destructor. */
  7452. virtual ~ReferenceCountedObject()
  7453. {
  7454. // it's dangerous to delete an object that's still referenced by something else!
  7455. jassert (getReferenceCount() == 0);
  7456. }
  7457. private:
  7458. Atomic <int> refCount;
  7459. };
  7460. /**
  7461. A smart-pointer class which points to a reference-counted object.
  7462. The template parameter specifies the class of the object you want to point to - the easiest
  7463. way to make a class reference-countable is to simply make it inherit from ReferenceCountedObject,
  7464. but if you need to, you could roll your own reference-countable class by implementing a pair of
  7465. mathods called incReferenceCount() and decReferenceCount().
  7466. When using this class, you'll probably want to create a typedef to abbreviate the full
  7467. templated name - e.g.
  7468. @code typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;@endcode
  7469. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7470. */
  7471. template <class ReferenceCountedObjectClass>
  7472. class ReferenceCountedObjectPtr
  7473. {
  7474. public:
  7475. /** Creates a pointer to a null object. */
  7476. inline ReferenceCountedObjectPtr() noexcept
  7477. : referencedObject (nullptr)
  7478. {
  7479. }
  7480. /** Creates a pointer to an object.
  7481. This will increment the object's reference-count if it is non-null.
  7482. */
  7483. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) noexcept
  7484. : referencedObject (refCountedObject)
  7485. {
  7486. if (refCountedObject != nullptr)
  7487. refCountedObject->incReferenceCount();
  7488. }
  7489. /** Copies another pointer.
  7490. This will increment the object's reference-count (if it is non-null).
  7491. */
  7492. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) noexcept
  7493. : referencedObject (other.referencedObject)
  7494. {
  7495. if (referencedObject != nullptr)
  7496. referencedObject->incReferenceCount();
  7497. }
  7498. /** Changes this pointer to point at a different object.
  7499. The reference count of the old object is decremented, and it might be
  7500. deleted if it hits zero. The new object's count is incremented.
  7501. */
  7502. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7503. {
  7504. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7505. if (newObject != referencedObject)
  7506. {
  7507. if (newObject != nullptr)
  7508. newObject->incReferenceCount();
  7509. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7510. referencedObject = newObject;
  7511. if (oldObject != nullptr)
  7512. oldObject->decReferenceCount();
  7513. }
  7514. return *this;
  7515. }
  7516. /** Changes this pointer to point at a different object.
  7517. The reference count of the old object is decremented, and it might be
  7518. deleted if it hits zero. The new object's count is incremented.
  7519. */
  7520. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7521. {
  7522. if (referencedObject != newObject)
  7523. {
  7524. if (newObject != nullptr)
  7525. newObject->incReferenceCount();
  7526. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7527. referencedObject = newObject;
  7528. if (oldObject != nullptr)
  7529. oldObject->decReferenceCount();
  7530. }
  7531. return *this;
  7532. }
  7533. /** Destructor.
  7534. This will decrement the object's reference-count, and may delete it if it
  7535. gets to zero.
  7536. */
  7537. inline ~ReferenceCountedObjectPtr()
  7538. {
  7539. if (referencedObject != nullptr)
  7540. referencedObject->decReferenceCount();
  7541. }
  7542. /** Returns the object that this pointer references.
  7543. The pointer returned may be zero, of course.
  7544. */
  7545. inline operator ReferenceCountedObjectClass*() const noexcept
  7546. {
  7547. return referencedObject;
  7548. }
  7549. // the -> operator is called on the referenced object
  7550. inline ReferenceCountedObjectClass* operator->() const noexcept
  7551. {
  7552. return referencedObject;
  7553. }
  7554. /** Returns the object that this pointer references.
  7555. The pointer returned may be zero, of course.
  7556. */
  7557. inline ReferenceCountedObjectClass* getObject() const noexcept
  7558. {
  7559. return referencedObject;
  7560. }
  7561. private:
  7562. ReferenceCountedObjectClass* referencedObject;
  7563. };
  7564. /** Compares two ReferenceCountedObjectPointers. */
  7565. template <class ReferenceCountedObjectClass>
  7566. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectClass* const object2) noexcept
  7567. {
  7568. return object1.getObject() == object2;
  7569. }
  7570. /** Compares two ReferenceCountedObjectPointers. */
  7571. template <class ReferenceCountedObjectClass>
  7572. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7573. {
  7574. return object1.getObject() == object2.getObject();
  7575. }
  7576. /** Compares two ReferenceCountedObjectPointers. */
  7577. template <class ReferenceCountedObjectClass>
  7578. bool operator== (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7579. {
  7580. return object1 == object2.getObject();
  7581. }
  7582. /** Compares two ReferenceCountedObjectPointers. */
  7583. template <class ReferenceCountedObjectClass>
  7584. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectClass* object2) noexcept
  7585. {
  7586. return object1.getObject() != object2;
  7587. }
  7588. /** Compares two ReferenceCountedObjectPointers. */
  7589. template <class ReferenceCountedObjectClass>
  7590. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7591. {
  7592. return object1.getObject() != object2.getObject();
  7593. }
  7594. /** Compares two ReferenceCountedObjectPointers. */
  7595. template <class ReferenceCountedObjectClass>
  7596. bool operator!= (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7597. {
  7598. return object1 != object2.getObject();
  7599. }
  7600. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7601. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  7602. /**
  7603. Represents a dynamically implemented object.
  7604. This class is primarily intended for wrapping scripting language objects,
  7605. but could be used for other purposes.
  7606. An instance of a DynamicObject can be used to store named properties, and
  7607. by subclassing hasMethod() and invokeMethod(), you can give your object
  7608. methods.
  7609. */
  7610. class JUCE_API DynamicObject : public ReferenceCountedObject
  7611. {
  7612. public:
  7613. DynamicObject();
  7614. /** Destructor. */
  7615. virtual ~DynamicObject();
  7616. /** Returns true if the object has a property with this name.
  7617. Note that if the property is actually a method, this will return false.
  7618. */
  7619. virtual bool hasProperty (const Identifier& propertyName) const;
  7620. /** Returns a named property.
  7621. This returns a void if no such property exists.
  7622. */
  7623. virtual const var getProperty (const Identifier& propertyName) const;
  7624. /** Sets a named property. */
  7625. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  7626. /** Removes a named property. */
  7627. virtual void removeProperty (const Identifier& propertyName);
  7628. /** Checks whether this object has the specified method.
  7629. The default implementation of this just checks whether there's a property
  7630. with this name that's actually a method, but this can be overridden for
  7631. building objects with dynamic invocation.
  7632. */
  7633. virtual bool hasMethod (const Identifier& methodName) const;
  7634. /** Invokes a named method on this object.
  7635. The default implementation looks up the named property, and if it's a method
  7636. call, then it invokes it.
  7637. This method is virtual to allow more dynamic invocation to used for objects
  7638. where the methods may not already be set as properies.
  7639. */
  7640. virtual const var invokeMethod (const Identifier& methodName,
  7641. const var* parameters,
  7642. int numParameters);
  7643. /** Sets up a method.
  7644. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  7645. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  7646. the code easier to read,
  7647. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  7648. @code
  7649. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  7650. @endcode
  7651. */
  7652. void setMethod (const Identifier& methodName,
  7653. var::MethodFunction methodFunction);
  7654. /** Removes all properties and methods from the object. */
  7655. void clear();
  7656. private:
  7657. NamedValueSet properties;
  7658. JUCE_LEAK_DETECTOR (DynamicObject);
  7659. };
  7660. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  7661. /*** End of inlined file: juce_DynamicObject.h ***/
  7662. #endif
  7663. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  7664. #endif
  7665. #ifndef __JUCE_HASHMAP_JUCEHEADER__
  7666. /*** Start of inlined file: juce_HashMap.h ***/
  7667. #ifndef __JUCE_HASHMAP_JUCEHEADER__
  7668. #define __JUCE_HASHMAP_JUCEHEADER__
  7669. /*** Start of inlined file: juce_OwnedArray.h ***/
  7670. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7671. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  7672. /** An array designed for holding objects.
  7673. This holds a list of pointers to objects, and will automatically
  7674. delete the objects when they are removed from the array, or when the
  7675. array is itself deleted.
  7676. Declare it in the form: OwnedArray<MyObjectClass>
  7677. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  7678. After adding objects, they are 'owned' by the array and will be deleted when
  7679. removed or replaced.
  7680. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7681. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7682. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  7683. */
  7684. template <class ObjectClass,
  7685. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7686. class OwnedArray
  7687. {
  7688. public:
  7689. /** Creates an empty array. */
  7690. OwnedArray() noexcept
  7691. : numUsed (0)
  7692. {
  7693. }
  7694. /** Deletes the array and also deletes any objects inside it.
  7695. To get rid of the array without deleting its objects, use its
  7696. clear (false) method before deleting it.
  7697. */
  7698. ~OwnedArray()
  7699. {
  7700. clear (true);
  7701. }
  7702. /** Clears the array, optionally deleting the objects inside it first. */
  7703. void clear (const bool deleteObjects = true)
  7704. {
  7705. const ScopedLockType lock (getLock());
  7706. if (deleteObjects)
  7707. {
  7708. while (numUsed > 0)
  7709. delete data.elements [--numUsed];
  7710. }
  7711. data.setAllocatedSize (0);
  7712. numUsed = 0;
  7713. }
  7714. /** Returns the number of items currently in the array.
  7715. @see operator[]
  7716. */
  7717. inline int size() const noexcept
  7718. {
  7719. return numUsed;
  7720. }
  7721. /** Returns a pointer to the object at this index in the array.
  7722. If the index is out-of-range, this will return a null pointer, (and
  7723. it could be null anyway, because it's ok for the array to hold null
  7724. pointers as well as objects).
  7725. @see getUnchecked
  7726. */
  7727. inline ObjectClass* operator[] (const int index) const noexcept
  7728. {
  7729. const ScopedLockType lock (getLock());
  7730. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  7731. : static_cast <ObjectClass*> (nullptr);
  7732. }
  7733. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7734. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7735. it can be used when you're sure the index if always going to be legal.
  7736. */
  7737. inline ObjectClass* getUnchecked (const int index) const noexcept
  7738. {
  7739. const ScopedLockType lock (getLock());
  7740. jassert (isPositiveAndBelow (index, numUsed));
  7741. return data.elements [index];
  7742. }
  7743. /** Returns a pointer to the first object in the array.
  7744. This will return a null pointer if the array's empty.
  7745. @see getLast
  7746. */
  7747. inline ObjectClass* getFirst() const noexcept
  7748. {
  7749. const ScopedLockType lock (getLock());
  7750. return numUsed > 0 ? data.elements [0]
  7751. : static_cast <ObjectClass*> (nullptr);
  7752. }
  7753. /** Returns a pointer to the last object in the array.
  7754. This will return a null pointer if the array's empty.
  7755. @see getFirst
  7756. */
  7757. inline ObjectClass* getLast() const noexcept
  7758. {
  7759. const ScopedLockType lock (getLock());
  7760. return numUsed > 0 ? data.elements [numUsed - 1]
  7761. : static_cast <ObjectClass*> (nullptr);
  7762. }
  7763. /** Returns a pointer to the actual array data.
  7764. This pointer will only be valid until the next time a non-const method
  7765. is called on the array.
  7766. */
  7767. inline ObjectClass** getRawDataPointer() noexcept
  7768. {
  7769. return data.elements;
  7770. }
  7771. /** Returns a pointer to the first element in the array.
  7772. This method is provided for compatibility with standard C++ iteration mechanisms.
  7773. */
  7774. inline ObjectClass** begin() const noexcept
  7775. {
  7776. return data.elements;
  7777. }
  7778. /** Returns a pointer to the element which follows the last element in the array.
  7779. This method is provided for compatibility with standard C++ iteration mechanisms.
  7780. */
  7781. inline ObjectClass** end() const noexcept
  7782. {
  7783. return data.elements + numUsed;
  7784. }
  7785. /** Finds the index of an object which might be in the array.
  7786. @param objectToLookFor the object to look for
  7787. @returns the index at which the object was found, or -1 if it's not found
  7788. */
  7789. int indexOf (const ObjectClass* const objectToLookFor) const noexcept
  7790. {
  7791. const ScopedLockType lock (getLock());
  7792. ObjectClass* const* e = data.elements.getData();
  7793. ObjectClass* const* const end = e + numUsed;
  7794. for (; e != end; ++e)
  7795. if (objectToLookFor == *e)
  7796. return static_cast <int> (e - data.elements.getData());
  7797. return -1;
  7798. }
  7799. /** Returns true if the array contains a specified object.
  7800. @param objectToLookFor the object to look for
  7801. @returns true if the object is in the array
  7802. */
  7803. bool contains (const ObjectClass* const objectToLookFor) const noexcept
  7804. {
  7805. const ScopedLockType lock (getLock());
  7806. ObjectClass* const* e = data.elements.getData();
  7807. ObjectClass* const* const end = e + numUsed;
  7808. for (; e != end; ++e)
  7809. if (objectToLookFor == *e)
  7810. return true;
  7811. return false;
  7812. }
  7813. /** Appends a new object to the end of the array.
  7814. Note that the this object will be deleted by the OwnedArray when it
  7815. is removed, so be careful not to delete it somewhere else.
  7816. Also be careful not to add the same object to the array more than once,
  7817. as this will obviously cause deletion of dangling pointers.
  7818. @param newObject the new object to add to the array
  7819. @see set, insert, addIfNotAlreadyThere, addSorted
  7820. */
  7821. void add (const ObjectClass* const newObject) noexcept
  7822. {
  7823. const ScopedLockType lock (getLock());
  7824. data.ensureAllocatedSize (numUsed + 1);
  7825. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7826. }
  7827. /** Inserts a new object into the array at the given index.
  7828. Note that the this object will be deleted by the OwnedArray when it
  7829. is removed, so be careful not to delete it somewhere else.
  7830. If the index is less than 0 or greater than the size of the array, the
  7831. element will be added to the end of the array.
  7832. Otherwise, it will be inserted into the array, moving all the later elements
  7833. along to make room.
  7834. Be careful not to add the same object to the array more than once,
  7835. as this will obviously cause deletion of dangling pointers.
  7836. @param indexToInsertAt the index at which the new element should be inserted
  7837. @param newObject the new object to add to the array
  7838. @see add, addSorted, addIfNotAlreadyThere, set
  7839. */
  7840. void insert (int indexToInsertAt,
  7841. const ObjectClass* const newObject) noexcept
  7842. {
  7843. if (indexToInsertAt >= 0)
  7844. {
  7845. const ScopedLockType lock (getLock());
  7846. if (indexToInsertAt > numUsed)
  7847. indexToInsertAt = numUsed;
  7848. data.ensureAllocatedSize (numUsed + 1);
  7849. ObjectClass** const e = data.elements + indexToInsertAt;
  7850. const int numToMove = numUsed - indexToInsertAt;
  7851. if (numToMove > 0)
  7852. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7853. *e = const_cast <ObjectClass*> (newObject);
  7854. ++numUsed;
  7855. }
  7856. else
  7857. {
  7858. add (newObject);
  7859. }
  7860. }
  7861. /** Appends a new object at the end of the array as long as the array doesn't
  7862. already contain it.
  7863. If the array already contains a matching object, nothing will be done.
  7864. @param newObject the new object to add to the array
  7865. */
  7866. void addIfNotAlreadyThere (const ObjectClass* const newObject) noexcept
  7867. {
  7868. const ScopedLockType lock (getLock());
  7869. if (! contains (newObject))
  7870. add (newObject);
  7871. }
  7872. /** Replaces an object in the array with a different one.
  7873. If the index is less than zero, this method does nothing.
  7874. If the index is beyond the end of the array, the new object is added to the end of the array.
  7875. Be careful not to add the same object to the array more than once,
  7876. as this will obviously cause deletion of dangling pointers.
  7877. @param indexToChange the index whose value you want to change
  7878. @param newObject the new value to set for this index.
  7879. @param deleteOldElement whether to delete the object that's being replaced with the new one
  7880. @see add, insert, remove
  7881. */
  7882. void set (const int indexToChange,
  7883. const ObjectClass* const newObject,
  7884. const bool deleteOldElement = true)
  7885. {
  7886. if (indexToChange >= 0)
  7887. {
  7888. ObjectClass* toDelete = nullptr;
  7889. {
  7890. const ScopedLockType lock (getLock());
  7891. if (indexToChange < numUsed)
  7892. {
  7893. if (deleteOldElement)
  7894. {
  7895. toDelete = data.elements [indexToChange];
  7896. if (toDelete == newObject)
  7897. toDelete = nullptr;
  7898. }
  7899. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  7900. }
  7901. else
  7902. {
  7903. data.ensureAllocatedSize (numUsed + 1);
  7904. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7905. }
  7906. }
  7907. delete toDelete; // don't want to use a ScopedPointer here because if the
  7908. // object has a private destructor, both OwnedArray and
  7909. // ScopedPointer would need to be friend classes..
  7910. }
  7911. else
  7912. {
  7913. jassertfalse; // you're trying to set an object at a negative index, which doesn't have
  7914. // any effect - but since the object is not being added, it may be leaking..
  7915. }
  7916. }
  7917. /** Adds elements from another array to the end of this array.
  7918. @param arrayToAddFrom the array from which to copy the elements
  7919. @param startIndex the first element of the other array to start copying from
  7920. @param numElementsToAdd how many elements to add from the other array. If this
  7921. value is negative or greater than the number of available elements,
  7922. all available elements will be copied.
  7923. @see add
  7924. */
  7925. template <class OtherArrayType>
  7926. void addArray (const OtherArrayType& arrayToAddFrom,
  7927. int startIndex = 0,
  7928. int numElementsToAdd = -1)
  7929. {
  7930. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7931. const ScopedLockType lock2 (getLock());
  7932. if (startIndex < 0)
  7933. {
  7934. jassertfalse;
  7935. startIndex = 0;
  7936. }
  7937. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7938. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7939. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7940. while (--numElementsToAdd >= 0)
  7941. {
  7942. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  7943. ++numUsed;
  7944. }
  7945. }
  7946. /** Adds copies of the elements in another array to the end of this array.
  7947. The other array must be either an OwnedArray of a compatible type of object, or an Array
  7948. containing pointers to the same kind of object. The objects involved must provide
  7949. a copy constructor, and this will be used to create new copies of each element, and
  7950. add them to this array.
  7951. @param arrayToAddFrom the array from which to copy the elements
  7952. @param startIndex the first element of the other array to start copying from
  7953. @param numElementsToAdd how many elements to add from the other array. If this
  7954. value is negative or greater than the number of available elements,
  7955. all available elements will be copied.
  7956. @see add
  7957. */
  7958. template <class OtherArrayType>
  7959. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  7960. int startIndex = 0,
  7961. int numElementsToAdd = -1)
  7962. {
  7963. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7964. const ScopedLockType lock2 (getLock());
  7965. if (startIndex < 0)
  7966. {
  7967. jassertfalse;
  7968. startIndex = 0;
  7969. }
  7970. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7971. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7972. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7973. while (--numElementsToAdd >= 0)
  7974. {
  7975. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  7976. ++numUsed;
  7977. }
  7978. }
  7979. /** Inserts a new object into the array assuming that the array is sorted.
  7980. This will use a comparator to find the position at which the new object
  7981. should go. If the array isn't sorted, the behaviour of this
  7982. method will be unpredictable.
  7983. @param comparator the comparator to use to compare the elements - see the sort method
  7984. for details about this object's structure
  7985. @param newObject the new object to insert to the array
  7986. @returns the index at which the new object was added
  7987. @see add, sort, indexOfSorted
  7988. */
  7989. template <class ElementComparator>
  7990. int addSorted (ElementComparator& comparator, ObjectClass* const newObject) noexcept
  7991. {
  7992. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7993. // avoids getting warning messages about the parameter being unused
  7994. const ScopedLockType lock (getLock());
  7995. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  7996. insert (index, newObject);
  7997. return index;
  7998. }
  7999. /** Finds the index of an object in the array, assuming that the array is sorted.
  8000. This will use a comparator to do a binary-chop to find the index of the given
  8001. element, if it exists. If the array isn't sorted, the behaviour of this
  8002. method will be unpredictable.
  8003. @param comparator the comparator to use to compare the elements - see the sort()
  8004. method for details about the form this object should take
  8005. @param objectToLookFor the object to search for
  8006. @returns the index of the element, or -1 if it's not found
  8007. @see addSorted, sort
  8008. */
  8009. template <class ElementComparator>
  8010. int indexOfSorted (ElementComparator& comparator,
  8011. const ObjectClass* const objectToLookFor) const noexcept
  8012. {
  8013. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8014. // avoids getting warning messages about the parameter being unused
  8015. const ScopedLockType lock (getLock());
  8016. int start = 0;
  8017. int end = numUsed;
  8018. for (;;)
  8019. {
  8020. if (start >= end)
  8021. {
  8022. return -1;
  8023. }
  8024. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  8025. {
  8026. return start;
  8027. }
  8028. else
  8029. {
  8030. const int halfway = (start + end) >> 1;
  8031. if (halfway == start)
  8032. return -1;
  8033. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  8034. start = halfway;
  8035. else
  8036. end = halfway;
  8037. }
  8038. }
  8039. }
  8040. /** Removes an object from the array.
  8041. This will remove the object at a given index (optionally also
  8042. deleting it) and move back all the subsequent objects to close the gap.
  8043. If the index passed in is out-of-range, nothing will happen.
  8044. @param indexToRemove the index of the element to remove
  8045. @param deleteObject whether to delete the object that is removed
  8046. @see removeObject, removeRange
  8047. */
  8048. void remove (const int indexToRemove,
  8049. const bool deleteObject = true)
  8050. {
  8051. ObjectClass* toDelete = nullptr;
  8052. {
  8053. const ScopedLockType lock (getLock());
  8054. if (isPositiveAndBelow (indexToRemove, numUsed))
  8055. {
  8056. ObjectClass** const e = data.elements + indexToRemove;
  8057. if (deleteObject)
  8058. toDelete = *e;
  8059. --numUsed;
  8060. const int numToShift = numUsed - indexToRemove;
  8061. if (numToShift > 0)
  8062. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  8063. }
  8064. }
  8065. delete toDelete; // don't want to use a ScopedPointer here because if the
  8066. // object has a private destructor, both OwnedArray and
  8067. // ScopedPointer would need to be friend classes..
  8068. if ((numUsed << 1) < data.numAllocated)
  8069. minimiseStorageOverheads();
  8070. }
  8071. /** Removes and returns an object from the array without deleting it.
  8072. This will remove the object at a given index and return it, moving back all
  8073. the subsequent objects to close the gap. If the index passed in is out-of-range,
  8074. nothing will happen.
  8075. @param indexToRemove the index of the element to remove
  8076. @see remove, removeObject, removeRange
  8077. */
  8078. ObjectClass* removeAndReturn (const int indexToRemove)
  8079. {
  8080. ObjectClass* removedItem = nullptr;
  8081. const ScopedLockType lock (getLock());
  8082. if (isPositiveAndBelow (indexToRemove, numUsed))
  8083. {
  8084. ObjectClass** const e = data.elements + indexToRemove;
  8085. removedItem = *e;
  8086. --numUsed;
  8087. const int numToShift = numUsed - indexToRemove;
  8088. if (numToShift > 0)
  8089. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  8090. if ((numUsed << 1) < data.numAllocated)
  8091. minimiseStorageOverheads();
  8092. }
  8093. return removedItem;
  8094. }
  8095. /** Removes a specified object from the array.
  8096. If the item isn't found, no action is taken.
  8097. @param objectToRemove the object to try to remove
  8098. @param deleteObject whether to delete the object (if it's found)
  8099. @see remove, removeRange
  8100. */
  8101. void removeObject (const ObjectClass* const objectToRemove,
  8102. const bool deleteObject = true)
  8103. {
  8104. const ScopedLockType lock (getLock());
  8105. ObjectClass** const e = data.elements.getData();
  8106. for (int i = 0; i < numUsed; ++i)
  8107. {
  8108. if (objectToRemove == e[i])
  8109. {
  8110. remove (i, deleteObject);
  8111. break;
  8112. }
  8113. }
  8114. }
  8115. /** Removes a range of objects from the array.
  8116. This will remove a set of objects, starting from the given index,
  8117. and move any subsequent elements down to close the gap.
  8118. If the range extends beyond the bounds of the array, it will
  8119. be safely clipped to the size of the array.
  8120. @param startIndex the index of the first object to remove
  8121. @param numberToRemove how many objects should be removed
  8122. @param deleteObjects whether to delete the objects that get removed
  8123. @see remove, removeObject
  8124. */
  8125. void removeRange (int startIndex,
  8126. const int numberToRemove,
  8127. const bool deleteObjects = true)
  8128. {
  8129. const ScopedLockType lock (getLock());
  8130. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  8131. startIndex = jlimit (0, numUsed, startIndex);
  8132. if (endIndex > startIndex)
  8133. {
  8134. if (deleteObjects)
  8135. {
  8136. for (int i = startIndex; i < endIndex; ++i)
  8137. {
  8138. delete data.elements [i];
  8139. data.elements [i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8140. }
  8141. }
  8142. const int rangeSize = endIndex - startIndex;
  8143. ObjectClass** e = data.elements + startIndex;
  8144. int numToShift = numUsed - endIndex;
  8145. numUsed -= rangeSize;
  8146. while (--numToShift >= 0)
  8147. {
  8148. *e = e [rangeSize];
  8149. ++e;
  8150. }
  8151. if ((numUsed << 1) < data.numAllocated)
  8152. minimiseStorageOverheads();
  8153. }
  8154. }
  8155. /** Removes the last n objects from the array.
  8156. @param howManyToRemove how many objects to remove from the end of the array
  8157. @param deleteObjects whether to also delete the objects that are removed
  8158. @see remove, removeObject, removeRange
  8159. */
  8160. void removeLast (int howManyToRemove = 1,
  8161. const bool deleteObjects = true)
  8162. {
  8163. const ScopedLockType lock (getLock());
  8164. if (howManyToRemove >= numUsed)
  8165. clear (deleteObjects);
  8166. else
  8167. removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects);
  8168. }
  8169. /** Swaps a pair of objects in the array.
  8170. If either of the indexes passed in is out-of-range, nothing will happen,
  8171. otherwise the two objects at these positions will be exchanged.
  8172. */
  8173. void swap (const int index1,
  8174. const int index2) noexcept
  8175. {
  8176. const ScopedLockType lock (getLock());
  8177. if (isPositiveAndBelow (index1, numUsed)
  8178. && isPositiveAndBelow (index2, numUsed))
  8179. {
  8180. swapVariables (data.elements [index1],
  8181. data.elements [index2]);
  8182. }
  8183. }
  8184. /** Moves one of the objects to a different position.
  8185. This will move the object to a specified index, shuffling along
  8186. any intervening elements as required.
  8187. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8188. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8189. @param currentIndex the index of the object to be moved. If this isn't a
  8190. valid index, then nothing will be done
  8191. @param newIndex the index at which you'd like this object to end up. If this
  8192. is less than zero, it will be moved to the end of the array
  8193. */
  8194. void move (const int currentIndex,
  8195. int newIndex) noexcept
  8196. {
  8197. if (currentIndex != newIndex)
  8198. {
  8199. const ScopedLockType lock (getLock());
  8200. if (isPositiveAndBelow (currentIndex, numUsed))
  8201. {
  8202. if (! isPositiveAndBelow (newIndex, numUsed))
  8203. newIndex = numUsed - 1;
  8204. ObjectClass* const value = data.elements [currentIndex];
  8205. if (newIndex > currentIndex)
  8206. {
  8207. memmove (data.elements + currentIndex,
  8208. data.elements + currentIndex + 1,
  8209. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8210. }
  8211. else
  8212. {
  8213. memmove (data.elements + newIndex + 1,
  8214. data.elements + newIndex,
  8215. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8216. }
  8217. data.elements [newIndex] = value;
  8218. }
  8219. }
  8220. }
  8221. /** This swaps the contents of this array with those of another array.
  8222. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  8223. because it just swaps their internal pointers.
  8224. */
  8225. void swapWithArray (OwnedArray& otherArray) noexcept
  8226. {
  8227. const ScopedLockType lock1 (getLock());
  8228. const ScopedLockType lock2 (otherArray.getLock());
  8229. data.swapWith (otherArray.data);
  8230. swapVariables (numUsed, otherArray.numUsed);
  8231. }
  8232. /** Reduces the amount of storage being used by the array.
  8233. Arrays typically allocate slightly more storage than they need, and after
  8234. removing elements, they may have quite a lot of unused space allocated.
  8235. This method will reduce the amount of allocated storage to a minimum.
  8236. */
  8237. void minimiseStorageOverheads() noexcept
  8238. {
  8239. const ScopedLockType lock (getLock());
  8240. data.shrinkToNoMoreThan (numUsed);
  8241. }
  8242. /** Increases the array's internal storage to hold a minimum number of elements.
  8243. Calling this before adding a large known number of elements means that
  8244. the array won't have to keep dynamically resizing itself as the elements
  8245. are added, and it'll therefore be more efficient.
  8246. */
  8247. void ensureStorageAllocated (const int minNumElements) noexcept
  8248. {
  8249. const ScopedLockType lock (getLock());
  8250. data.ensureAllocatedSize (minNumElements);
  8251. }
  8252. /** Sorts the elements in the array.
  8253. This will use a comparator object to sort the elements into order. The object
  8254. passed must have a method of the form:
  8255. @code
  8256. int compareElements (ElementType first, ElementType second);
  8257. @endcode
  8258. ..and this method must return:
  8259. - a value of < 0 if the first comes before the second
  8260. - a value of 0 if the two objects are equivalent
  8261. - a value of > 0 if the second comes before the first
  8262. To improve performance, the compareElements() method can be declared as static or const.
  8263. @param comparator the comparator to use for comparing elements.
  8264. @param retainOrderOfEquivalentItems if this is true, then items
  8265. which the comparator says are equivalent will be
  8266. kept in the order in which they currently appear
  8267. in the array. This is slower to perform, but may
  8268. be important in some cases. If it's false, a faster
  8269. algorithm is used, but equivalent elements may be
  8270. rearranged.
  8271. @see sortArray, indexOfSorted
  8272. */
  8273. template <class ElementComparator>
  8274. void sort (ElementComparator& comparator,
  8275. const bool retainOrderOfEquivalentItems = false) const noexcept
  8276. {
  8277. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8278. // avoids getting warning messages about the parameter being unused
  8279. const ScopedLockType lock (getLock());
  8280. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  8281. }
  8282. /** Returns the CriticalSection that locks this array.
  8283. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8284. an object of ScopedLockType as an RAII lock for it.
  8285. */
  8286. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  8287. /** Returns the type of scoped lock to use for locking this array */
  8288. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8289. private:
  8290. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  8291. int numUsed;
  8292. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OwnedArray);
  8293. };
  8294. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  8295. /*** End of inlined file: juce_OwnedArray.h ***/
  8296. /*** Start of inlined file: juce_ScopedPointer.h ***/
  8297. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8298. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8299. /**
  8300. This class holds a pointer which is automatically deleted when this object goes
  8301. out of scope.
  8302. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  8303. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  8304. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  8305. created objects.
  8306. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  8307. to an object. If you use the assignment operator to assign a different object to a
  8308. ScopedPointer, the old one will be automatically deleted.
  8309. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  8310. object to which it points during its lifetime. This means that making a copy of a const
  8311. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  8312. old one.
  8313. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  8314. can use the release() method.
  8315. */
  8316. template <class ObjectType>
  8317. class ScopedPointer
  8318. {
  8319. public:
  8320. /** Creates a ScopedPointer containing a null pointer. */
  8321. inline ScopedPointer() noexcept : object (nullptr)
  8322. {
  8323. }
  8324. /** Creates a ScopedPointer that owns the specified object. */
  8325. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) noexcept
  8326. : object (objectToTakePossessionOf)
  8327. {
  8328. }
  8329. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  8330. Because a pointer can only belong to one ScopedPointer, this transfers
  8331. the pointer from the other object to this one, and the other object is reset to
  8332. be a null pointer.
  8333. */
  8334. ScopedPointer (ScopedPointer& objectToTransferFrom) noexcept
  8335. : object (objectToTransferFrom.object)
  8336. {
  8337. objectToTransferFrom.object = nullptr;
  8338. }
  8339. /** Destructor.
  8340. This will delete the object that this ScopedPointer currently refers to.
  8341. */
  8342. inline ~ScopedPointer() { delete object; }
  8343. /** Changes this ScopedPointer to point to a new object.
  8344. Because a pointer can only belong to one ScopedPointer, this transfers
  8345. the pointer from the other object to this one, and the other object is reset to
  8346. be a null pointer.
  8347. If this ScopedPointer already points to an object, that object
  8348. will first be deleted.
  8349. */
  8350. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  8351. {
  8352. if (this != objectToTransferFrom.getAddress())
  8353. {
  8354. // Two ScopedPointers should never be able to refer to the same object - if
  8355. // this happens, you must have done something dodgy!
  8356. jassert (object == nullptr || object != objectToTransferFrom.object);
  8357. ObjectType* const oldObject = object;
  8358. object = objectToTransferFrom.object;
  8359. objectToTransferFrom.object = nullptr;
  8360. delete oldObject;
  8361. }
  8362. return *this;
  8363. }
  8364. /** Changes this ScopedPointer to point to a new object.
  8365. If this ScopedPointer already points to an object, that object
  8366. will first be deleted.
  8367. The pointer that you pass is may be null.
  8368. */
  8369. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  8370. {
  8371. if (object != newObjectToTakePossessionOf)
  8372. {
  8373. ObjectType* const oldObject = object;
  8374. object = newObjectToTakePossessionOf;
  8375. delete oldObject;
  8376. }
  8377. return *this;
  8378. }
  8379. /** Returns the object that this ScopedPointer refers to. */
  8380. inline operator ObjectType*() const noexcept { return object; }
  8381. /** Returns the object that this ScopedPointer refers to. */
  8382. inline ObjectType& operator*() const noexcept { return *object; }
  8383. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  8384. inline ObjectType* operator->() const noexcept { return object; }
  8385. /** Removes the current object from this ScopedPointer without deleting it.
  8386. This will return the current object, and set the ScopedPointer to a null pointer.
  8387. */
  8388. ObjectType* release() noexcept { ObjectType* const o = object; object = nullptr; return o; }
  8389. /** Swaps this object with that of another ScopedPointer.
  8390. The two objects simply exchange their pointers.
  8391. */
  8392. void swapWith (ScopedPointer <ObjectType>& other) noexcept
  8393. {
  8394. // Two ScopedPointers should never be able to refer to the same object - if
  8395. // this happens, you must have done something dodgy!
  8396. jassert (object != other.object);
  8397. std::swap (object, other.object);
  8398. }
  8399. private:
  8400. ObjectType* object;
  8401. // (Required as an alternative to the overloaded & operator).
  8402. const ScopedPointer* getAddress() const noexcept { return this; }
  8403. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  8404. /* This is private to stop people accidentally copying a const ScopedPointer (the compiler
  8405. would let you do so by implicitly casting the source to its raw object pointer).
  8406. A side effect of this is that you may hit a puzzling compiler error when you write something
  8407. like this:
  8408. ScopedPointer<MyClass> m = new MyClass(); // Compile error: copy constructor is private.
  8409. Even though the compiler would normally ignore the assignment here, it can't do so when the
  8410. copy constructor is private. It's very easy to fis though - just write it like this:
  8411. ScopedPointer<MyClass> m (new MyClass()); // Compiles OK
  8412. It's good practice to always use the latter form when writing your object declarations anyway,
  8413. rather than writing them as assignments and assuming (or hoping) that the compiler will be
  8414. smart enough to replace your construction + assignment with a single constructor.
  8415. */
  8416. ScopedPointer (const ScopedPointer&);
  8417. #endif
  8418. };
  8419. /** Compares a ScopedPointer with another pointer.
  8420. This can be handy for checking whether this is a null pointer.
  8421. */
  8422. template <class ObjectType>
  8423. bool operator== (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  8424. {
  8425. return static_cast <ObjectType*> (pointer1) == pointer2;
  8426. }
  8427. /** Compares a ScopedPointer with another pointer.
  8428. This can be handy for checking whether this is a null pointer.
  8429. */
  8430. template <class ObjectType>
  8431. bool operator!= (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  8432. {
  8433. return static_cast <ObjectType*> (pointer1) != pointer2;
  8434. }
  8435. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8436. /*** End of inlined file: juce_ScopedPointer.h ***/
  8437. /**
  8438. A simple class to generate hash functions for some primitive types, intended for
  8439. use with the HashMap class.
  8440. @see HashMap
  8441. */
  8442. class DefaultHashFunctions
  8443. {
  8444. public:
  8445. /** Generates a simple hash from an integer. */
  8446. static int generateHash (const int key, const int upperLimit) noexcept { return std::abs (key) % upperLimit; }
  8447. /** Generates a simple hash from a string. */
  8448. static int generateHash (const String& key, const int upperLimit) noexcept { return key.hashCode() % upperLimit; }
  8449. /** Generates a simple hash from a variant. */
  8450. static int generateHash (const var& key, const int upperLimit) noexcept { return generateHash (key.toString(), upperLimit); }
  8451. };
  8452. /**
  8453. Holds a set of mappings between some key/value pairs.
  8454. The types of the key and value objects are set as template parameters.
  8455. You can also specify a class to supply a hash function that converts a key value
  8456. into an hashed integer. This class must have the form:
  8457. @code
  8458. struct MyHashGenerator
  8459. {
  8460. static int generateHash (MyKeyType key, int upperLimit)
  8461. {
  8462. // The function must return a value 0 <= x < upperLimit
  8463. return someFunctionOfMyKeyType (key) % upperLimit;
  8464. }
  8465. };
  8466. @endcode
  8467. Like the Array class, the key and value types are expected to be copy-by-value types, so
  8468. if you define them to be pointer types, this class won't delete the objects that they
  8469. point to.
  8470. If you don't supply a class for the HashFunctionToUse template parameter, the
  8471. default one provides some simple mappings for strings and ints.
  8472. @code
  8473. HashMap<int, String> hash;
  8474. hash.set (1, "item1");
  8475. hash.set (2, "item2");
  8476. DBG (hash [1]); // prints "item1"
  8477. DBG (hash [2]); // prints "item2"
  8478. // This iterates the map, printing all of its key -> value pairs..
  8479. for (HashMap<int, String>::Iterator i (hash); i.next();)
  8480. DBG (i.getKey() << " -> " << i.getValue());
  8481. @endcode
  8482. @see CriticalSection, DefaultHashFunctions, NamedValueSet, SortedSet
  8483. */
  8484. template <typename KeyType,
  8485. typename ValueType,
  8486. class HashFunctionToUse = DefaultHashFunctions,
  8487. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8488. class HashMap
  8489. {
  8490. private:
  8491. typedef PARAMETER_TYPE (KeyType) KeyTypeParameter;
  8492. typedef PARAMETER_TYPE (ValueType) ValueTypeParameter;
  8493. public:
  8494. /** Creates an empty hash-map.
  8495. The numberOfSlots parameter specifies the number of hash entries the map will use. This
  8496. will be the "upperLimit" parameter that is passed to your generateHash() function. The number
  8497. of hash slots will grow automatically if necessary, or it can be remapped manually using remapTable().
  8498. */
  8499. HashMap (const int numberOfSlots = defaultHashTableSize)
  8500. : totalNumItems (0)
  8501. {
  8502. slots.insertMultiple (0, nullptr, numberOfSlots);
  8503. }
  8504. /** Destructor. */
  8505. ~HashMap()
  8506. {
  8507. clear();
  8508. }
  8509. /** Removes all values from the map.
  8510. Note that this will clear the content, but won't affect the number of slots (see
  8511. remapTable and getNumSlots).
  8512. */
  8513. void clear()
  8514. {
  8515. const ScopedLockType sl (getLock());
  8516. for (int i = slots.size(); --i >= 0;)
  8517. {
  8518. HashEntry* h = slots.getUnchecked(i);
  8519. while (h != nullptr)
  8520. {
  8521. const ScopedPointer<HashEntry> deleter (h);
  8522. h = h->nextEntry;
  8523. }
  8524. slots.set (i, nullptr);
  8525. }
  8526. totalNumItems = 0;
  8527. }
  8528. /** Returns the current number of items in the map. */
  8529. inline int size() const noexcept
  8530. {
  8531. return totalNumItems;
  8532. }
  8533. /** Returns the value corresponding to a given key.
  8534. If the map doesn't contain the key, a default instance of the value type is returned.
  8535. @param keyToLookFor the key of the item being requested
  8536. */
  8537. inline const ValueType operator[] (KeyTypeParameter keyToLookFor) const
  8538. {
  8539. const ScopedLockType sl (getLock());
  8540. for (const HashEntry* entry = slots [generateHashFor (keyToLookFor)]; entry != nullptr; entry = entry->nextEntry)
  8541. if (entry->key == keyToLookFor)
  8542. return entry->value;
  8543. return ValueType();
  8544. }
  8545. /** Returns true if the map contains an item with the specied key. */
  8546. bool contains (KeyTypeParameter keyToLookFor) const
  8547. {
  8548. const ScopedLockType sl (getLock());
  8549. for (const HashEntry* entry = slots [generateHashFor (keyToLookFor)]; entry != nullptr; entry = entry->nextEntry)
  8550. if (entry->key == keyToLookFor)
  8551. return true;
  8552. return false;
  8553. }
  8554. /** Returns true if the hash contains at least one occurrence of a given value. */
  8555. bool containsValue (ValueTypeParameter valueToLookFor) const
  8556. {
  8557. const ScopedLockType sl (getLock());
  8558. for (int i = getNumSlots(); --i >= 0;)
  8559. for (const HashEntry* entry = slots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  8560. if (entry->value == valueToLookFor)
  8561. return true;
  8562. return false;
  8563. }
  8564. /** Adds or replaces an element in the hash-map.
  8565. If there's already an item with the given key, this will replace its value. Otherwise, a new item
  8566. will be added to the map.
  8567. */
  8568. void set (KeyTypeParameter newKey, ValueTypeParameter newValue)
  8569. {
  8570. const ScopedLockType sl (getLock());
  8571. const int hashIndex = generateHashFor (newKey);
  8572. if (isPositiveAndBelow (hashIndex, getNumSlots()))
  8573. {
  8574. HashEntry* const firstEntry = slots.getUnchecked (hashIndex);
  8575. for (HashEntry* entry = firstEntry; entry != nullptr; entry = entry->nextEntry)
  8576. {
  8577. if (entry->key == newKey)
  8578. {
  8579. entry->value = newValue;
  8580. return;
  8581. }
  8582. }
  8583. slots.set (hashIndex, new HashEntry (newKey, newValue, firstEntry));
  8584. ++totalNumItems;
  8585. if (totalNumItems > (getNumSlots() * 3) / 2)
  8586. remapTable (getNumSlots() * 2);
  8587. }
  8588. }
  8589. /** Removes an item with the given key. */
  8590. void remove (KeyTypeParameter keyToRemove)
  8591. {
  8592. const ScopedLockType sl (getLock());
  8593. const int hashIndex = generateHashFor (keyToRemove);
  8594. HashEntry* entry = slots [hashIndex];
  8595. HashEntry* previous = nullptr;
  8596. while (entry != nullptr)
  8597. {
  8598. if (entry->key == keyToRemove)
  8599. {
  8600. const ScopedPointer<HashEntry> deleter (entry);
  8601. entry = entry->nextEntry;
  8602. if (previous != nullptr)
  8603. previous->nextEntry = entry;
  8604. else
  8605. slots.set (hashIndex, entry);
  8606. --totalNumItems;
  8607. }
  8608. else
  8609. {
  8610. previous = entry;
  8611. entry = entry->nextEntry;
  8612. }
  8613. }
  8614. }
  8615. /** Removes all items with the given value. */
  8616. void removeValue (ValueTypeParameter valueToRemove)
  8617. {
  8618. const ScopedLockType sl (getLock());
  8619. for (int i = getNumSlots(); --i >= 0;)
  8620. {
  8621. HashEntry* entry = slots.getUnchecked(i);
  8622. HashEntry* previous = nullptr;
  8623. while (entry != nullptr)
  8624. {
  8625. if (entry->value == valueToRemove)
  8626. {
  8627. const ScopedPointer<HashEntry> deleter (entry);
  8628. entry = entry->nextEntry;
  8629. if (previous != nullptr)
  8630. previous->nextEntry = entry;
  8631. else
  8632. slots.set (i, entry);
  8633. --totalNumItems;
  8634. }
  8635. else
  8636. {
  8637. previous = entry;
  8638. entry = entry->nextEntry;
  8639. }
  8640. }
  8641. }
  8642. }
  8643. /** Remaps the hash-map to use a different number of slots for its hash function.
  8644. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  8645. @see getNumSlots()
  8646. */
  8647. void remapTable (int newNumberOfSlots)
  8648. {
  8649. HashMap newTable (newNumberOfSlots);
  8650. for (int i = getNumSlots(); --i >= 0;)
  8651. for (const HashEntry* entry = slots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  8652. newTable.set (entry->key, entry->value);
  8653. swapWith (newTable);
  8654. }
  8655. /** Returns the number of slots which are available for hashing.
  8656. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  8657. @see getNumSlots()
  8658. */
  8659. inline int getNumSlots() const noexcept
  8660. {
  8661. return slots.size();
  8662. }
  8663. /** Efficiently swaps the contents of two hash-maps. */
  8664. void swapWith (HashMap& otherHashMap) noexcept
  8665. {
  8666. const ScopedLockType lock1 (getLock());
  8667. const ScopedLockType lock2 (otherHashMap.getLock());
  8668. slots.swapWithArray (otherHashMap.slots);
  8669. std::swap (totalNumItems, otherHashMap.totalNumItems);
  8670. }
  8671. /** Returns the CriticalSection that locks this structure.
  8672. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8673. an object of ScopedLockType as an RAII lock for it.
  8674. */
  8675. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return lock; }
  8676. /** Returns the type of scoped lock to use for locking this array */
  8677. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8678. private:
  8679. class HashEntry
  8680. {
  8681. public:
  8682. HashEntry (KeyTypeParameter key_, ValueTypeParameter value_, HashEntry* const nextEntry_)
  8683. : key (key_), value (value_), nextEntry (nextEntry_)
  8684. {}
  8685. const KeyType key;
  8686. ValueType value;
  8687. HashEntry* nextEntry;
  8688. JUCE_DECLARE_NON_COPYABLE (HashEntry);
  8689. };
  8690. public:
  8691. /** Iterates over the items in a HashMap.
  8692. To use it, repeatedly call next() until it returns false, e.g.
  8693. @code
  8694. HashMap <String, String> myMap;
  8695. HashMap<String, String>::Iterator i (myMap);
  8696. while (i.next())
  8697. {
  8698. DBG (i.getKey() << " -> " << i.getValue());
  8699. }
  8700. @endcode
  8701. The order in which items are iterated bears no resemblence to the order in which
  8702. they were originally added!
  8703. Obviously as soon as you call any non-const methods on the original hash-map, any
  8704. iterators that were created beforehand will cease to be valid, and should not be used.
  8705. @see HashMap
  8706. */
  8707. class Iterator
  8708. {
  8709. public:
  8710. Iterator (const HashMap& hashMapToIterate)
  8711. : hashMap (hashMapToIterate), entry (0), index (0)
  8712. {}
  8713. /** Moves to the next item, if one is available.
  8714. When this returns true, you can get the item's key and value using getKey() and
  8715. getValue(). If it returns false, the iteration has finished and you should stop.
  8716. */
  8717. bool next()
  8718. {
  8719. if (entry != nullptr)
  8720. entry = entry->nextEntry;
  8721. while (entry == nullptr)
  8722. {
  8723. if (index >= hashMap.getNumSlots())
  8724. return false;
  8725. entry = hashMap.slots.getUnchecked (index++);
  8726. }
  8727. return true;
  8728. }
  8729. /** Returns the current item's key.
  8730. This should only be called when a call to next() has just returned true.
  8731. */
  8732. const KeyType getKey() const
  8733. {
  8734. return entry != nullptr ? entry->key : KeyType();
  8735. }
  8736. /** Returns the current item's value.
  8737. This should only be called when a call to next() has just returned true.
  8738. */
  8739. const ValueType getValue() const
  8740. {
  8741. return entry != nullptr ? entry->value : ValueType();
  8742. }
  8743. private:
  8744. const HashMap& hashMap;
  8745. HashEntry* entry;
  8746. int index;
  8747. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Iterator);
  8748. };
  8749. private:
  8750. enum { defaultHashTableSize = 101 };
  8751. friend class Iterator;
  8752. Array <HashEntry*> slots;
  8753. int totalNumItems;
  8754. TypeOfCriticalSectionToUse lock;
  8755. int generateHashFor (KeyTypeParameter key) const
  8756. {
  8757. const int hash = HashFunctionToUse::generateHash (key, getNumSlots());
  8758. jassert (isPositiveAndBelow (hash, getNumSlots())); // your hash function is generating out-of-range numbers!
  8759. return hash;
  8760. }
  8761. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HashMap);
  8762. };
  8763. #endif // __JUCE_HASHMAP_JUCEHEADER__
  8764. /*** End of inlined file: juce_HashMap.h ***/
  8765. #endif
  8766. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  8767. #endif
  8768. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  8769. #endif
  8770. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  8771. #endif
  8772. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8773. /*** Start of inlined file: juce_PropertySet.h ***/
  8774. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8775. #define __JUCE_PROPERTYSET_JUCEHEADER__
  8776. /*** Start of inlined file: juce_StringPairArray.h ***/
  8777. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8778. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8779. /*** Start of inlined file: juce_StringArray.h ***/
  8780. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  8781. #define __JUCE_STRINGARRAY_JUCEHEADER__
  8782. /**
  8783. A special array for holding a list of strings.
  8784. @see String, StringPairArray
  8785. */
  8786. class JUCE_API StringArray
  8787. {
  8788. public:
  8789. /** Creates an empty string array */
  8790. StringArray() noexcept;
  8791. /** Creates a copy of another string array */
  8792. StringArray (const StringArray& other);
  8793. /** Creates an array containing a single string. */
  8794. explicit StringArray (const String& firstValue);
  8795. /** Creates a copy of an array of string literals.
  8796. @param strings an array of strings to add. Null pointers in the array will be
  8797. treated as empty strings
  8798. @param numberOfStrings how many items there are in the array
  8799. */
  8800. StringArray (const char* const* strings, int numberOfStrings);
  8801. /** Creates a copy of a null-terminated array of string literals.
  8802. Each item from the array passed-in is added, until it encounters a null pointer,
  8803. at which point it stops.
  8804. */
  8805. explicit StringArray (const char* const* strings);
  8806. /** Creates a copy of a null-terminated array of string literals.
  8807. Each item from the array passed-in is added, until it encounters a null pointer,
  8808. at which point it stops.
  8809. */
  8810. explicit StringArray (const wchar_t* const* strings);
  8811. /** Creates a copy of an array of string literals.
  8812. @param strings an array of strings to add. Null pointers in the array will be
  8813. treated as empty strings
  8814. @param numberOfStrings how many items there are in the array
  8815. */
  8816. StringArray (const wchar_t* const* strings, int numberOfStrings);
  8817. /** Destructor. */
  8818. ~StringArray();
  8819. /** Copies the contents of another string array into this one */
  8820. StringArray& operator= (const StringArray& other);
  8821. /** Compares two arrays.
  8822. Comparisons are case-sensitive.
  8823. @returns true only if the other array contains exactly the same strings in the same order
  8824. */
  8825. bool operator== (const StringArray& other) const noexcept;
  8826. /** Compares two arrays.
  8827. Comparisons are case-sensitive.
  8828. @returns false if the other array contains exactly the same strings in the same order
  8829. */
  8830. bool operator!= (const StringArray& other) const noexcept;
  8831. /** Returns the number of strings in the array */
  8832. inline int size() const noexcept { return strings.size(); };
  8833. /** Returns one of the strings from the array.
  8834. If the index is out-of-range, an empty string is returned.
  8835. Obviously the reference returned shouldn't be stored for later use, as the
  8836. string it refers to may disappear when the array changes.
  8837. */
  8838. const String& operator[] (int index) const noexcept;
  8839. /** Returns a reference to one of the strings in the array.
  8840. This lets you modify a string in-place in the array, but you must be sure that
  8841. the index is in-range.
  8842. */
  8843. String& getReference (int index) noexcept;
  8844. /** Searches for a string in the array.
  8845. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8846. @returns true if the string is found inside the array
  8847. */
  8848. bool contains (const String& stringToLookFor,
  8849. bool ignoreCase = false) const;
  8850. /** Searches for a string in the array.
  8851. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8852. @param stringToLookFor the string to try to find
  8853. @param ignoreCase whether the comparison should be case-insensitive
  8854. @param startIndex the first index to start searching from
  8855. @returns the index of the first occurrence of the string in this array,
  8856. or -1 if it isn't found.
  8857. */
  8858. int indexOf (const String& stringToLookFor,
  8859. bool ignoreCase = false,
  8860. int startIndex = 0) const;
  8861. /** Appends a string at the end of the array. */
  8862. void add (const String& stringToAdd);
  8863. /** Inserts a string into the array.
  8864. This will insert a string into the array at the given index, moving
  8865. up the other elements to make room for it.
  8866. If the index is less than zero or greater than the size of the array,
  8867. the new string will be added to the end of the array.
  8868. */
  8869. void insert (int index, const String& stringToAdd);
  8870. /** Adds a string to the array as long as it's not already in there.
  8871. The search can optionally be case-insensitive.
  8872. */
  8873. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  8874. /** Replaces one of the strings in the array with another one.
  8875. If the index is higher than the array's size, the new string will be
  8876. added to the end of the array; if it's less than zero nothing happens.
  8877. */
  8878. void set (int index, const String& newString);
  8879. /** Appends some strings from another array to the end of this one.
  8880. @param other the array to add
  8881. @param startIndex the first element of the other array to add
  8882. @param numElementsToAdd the maximum number of elements to add (if this is
  8883. less than zero, they are all added)
  8884. */
  8885. void addArray (const StringArray& other,
  8886. int startIndex = 0,
  8887. int numElementsToAdd = -1);
  8888. /** Breaks up a string into tokens and adds them to this array.
  8889. This will tokenise the given string using whitespace characters as the
  8890. token delimiters, and will add these tokens to the end of the array.
  8891. @returns the number of tokens added
  8892. */
  8893. int addTokens (const String& stringToTokenise,
  8894. bool preserveQuotedStrings);
  8895. /** Breaks up a string into tokens and adds them to this array.
  8896. This will tokenise the given string (using the string passed in to define the
  8897. token delimiters), and will add these tokens to the end of the array.
  8898. @param stringToTokenise the string to tokenise
  8899. @param breakCharacters a string of characters, any of which will be considered
  8900. to be a token delimiter.
  8901. @param quoteCharacters if this string isn't empty, it defines a set of characters
  8902. which are treated as quotes. Any text occurring
  8903. between quotes is not broken up into tokens.
  8904. @returns the number of tokens added
  8905. */
  8906. int addTokens (const String& stringToTokenise,
  8907. const String& breakCharacters,
  8908. const String& quoteCharacters);
  8909. /** Breaks up a string into lines and adds them to this array.
  8910. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  8911. to the array. Line-break characters are omitted from the strings that are added to
  8912. the array.
  8913. */
  8914. int addLines (const String& stringToBreakUp);
  8915. /** Removes all elements from the array. */
  8916. void clear();
  8917. /** Removes a string from the array.
  8918. If the index is out-of-range, no action will be taken.
  8919. */
  8920. void remove (int index);
  8921. /** Finds a string in the array and removes it.
  8922. This will remove the first occurrence of the given string from the array. The
  8923. comparison may be case-insensitive depending on the ignoreCase parameter.
  8924. */
  8925. void removeString (const String& stringToRemove,
  8926. bool ignoreCase = false);
  8927. /** Removes a range of elements from the array.
  8928. This will remove a set of elements, starting from the given index,
  8929. and move subsequent elements down to close the gap.
  8930. If the range extends beyond the bounds of the array, it will
  8931. be safely clipped to the size of the array.
  8932. @param startIndex the index of the first element to remove
  8933. @param numberToRemove how many elements should be removed
  8934. */
  8935. void removeRange (int startIndex, int numberToRemove);
  8936. /** Removes any duplicated elements from the array.
  8937. If any string appears in the array more than once, only the first occurrence of
  8938. it will be retained.
  8939. @param ignoreCase whether to use a case-insensitive comparison
  8940. */
  8941. void removeDuplicates (bool ignoreCase);
  8942. /** Removes empty strings from the array.
  8943. @param removeWhitespaceStrings if true, strings that only contain whitespace
  8944. characters will also be removed
  8945. */
  8946. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  8947. /** Moves one of the strings to a different position.
  8948. This will move the string to a specified index, shuffling along
  8949. any intervening elements as required.
  8950. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8951. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8952. @param currentIndex the index of the value to be moved. If this isn't a
  8953. valid index, then nothing will be done
  8954. @param newIndex the index at which you'd like this value to end up. If this
  8955. is less than zero, the value will be moved to the end
  8956. of the array
  8957. */
  8958. void move (int currentIndex, int newIndex) noexcept;
  8959. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  8960. void trim();
  8961. /** Adds numbers to the strings in the array, to make each string unique.
  8962. This will add numbers to the ends of groups of similar strings.
  8963. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  8964. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  8965. @param appendNumberToFirstInstance whether the first of a group of similar strings
  8966. also has a number appended to it.
  8967. @param preNumberString when adding a number, this string is added before the number.
  8968. If you pass 0, a default string will be used, which adds
  8969. brackets around the number.
  8970. @param postNumberString this string is appended after any numbers that are added.
  8971. If you pass 0, a default string will be used, which adds
  8972. brackets around the number.
  8973. */
  8974. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  8975. bool appendNumberToFirstInstance,
  8976. CharPointer_UTF8 preNumberString = CharPointer_UTF8 (nullptr),
  8977. CharPointer_UTF8 postNumberString = CharPointer_UTF8 (nullptr));
  8978. /** Joins the strings in the array together into one string.
  8979. This will join a range of elements from the array into a string, separating
  8980. them with a given string.
  8981. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  8982. @param separatorString the string to insert between all the strings
  8983. @param startIndex the first element to join
  8984. @param numberOfElements how many elements to join together. If this is less
  8985. than zero, all available elements will be used.
  8986. */
  8987. const String joinIntoString (const String& separatorString,
  8988. int startIndex = 0,
  8989. int numberOfElements = -1) const;
  8990. /** Sorts the array into alphabetical order.
  8991. @param ignoreCase if true, the comparisons used will be case-sensitive.
  8992. */
  8993. void sort (bool ignoreCase);
  8994. /** Reduces the amount of storage being used by the array.
  8995. Arrays typically allocate slightly more storage than they need, and after
  8996. removing elements, they may have quite a lot of unused space allocated.
  8997. This method will reduce the amount of allocated storage to a minimum.
  8998. */
  8999. void minimiseStorageOverheads();
  9000. private:
  9001. Array <String> strings;
  9002. JUCE_LEAK_DETECTOR (StringArray);
  9003. };
  9004. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  9005. /*** End of inlined file: juce_StringArray.h ***/
  9006. /**
  9007. A container for holding a set of strings which are keyed by another string.
  9008. @see StringArray
  9009. */
  9010. class JUCE_API StringPairArray
  9011. {
  9012. public:
  9013. /** Creates an empty array */
  9014. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  9015. /** Creates a copy of another array */
  9016. StringPairArray (const StringPairArray& other);
  9017. /** Destructor. */
  9018. ~StringPairArray();
  9019. /** Copies the contents of another string array into this one */
  9020. StringPairArray& operator= (const StringPairArray& other);
  9021. /** Compares two arrays.
  9022. Comparisons are case-sensitive.
  9023. @returns true only if the other array contains exactly the same strings with the same keys
  9024. */
  9025. bool operator== (const StringPairArray& other) const;
  9026. /** Compares two arrays.
  9027. Comparisons are case-sensitive.
  9028. @returns false if the other array contains exactly the same strings with the same keys
  9029. */
  9030. bool operator!= (const StringPairArray& other) const;
  9031. /** Finds the value corresponding to a key string.
  9032. If no such key is found, this will just return an empty string. To check whether
  9033. a given key actually exists (because it might actually be paired with an empty string), use
  9034. the getAllKeys() method to obtain a list.
  9035. Obviously the reference returned shouldn't be stored for later use, as the
  9036. string it refers to may disappear when the array changes.
  9037. @see getValue
  9038. */
  9039. const String& operator[] (const String& key) const;
  9040. /** Finds the value corresponding to a key string.
  9041. If no such key is found, this will just return the value provided as a default.
  9042. @see operator[]
  9043. */
  9044. const String getValue (const String& key, const String& defaultReturnValue) const;
  9045. /** Returns a list of all keys in the array. */
  9046. const StringArray& getAllKeys() const noexcept { return keys; }
  9047. /** Returns a list of all values in the array. */
  9048. const StringArray& getAllValues() const noexcept { return values; }
  9049. /** Returns the number of strings in the array */
  9050. inline int size() const noexcept { return keys.size(); };
  9051. /** Adds or amends a key/value pair.
  9052. If a value already exists with this key, its value will be overwritten,
  9053. otherwise the key/value pair will be added to the array.
  9054. */
  9055. void set (const String& key, const String& value);
  9056. /** Adds the items from another array to this one.
  9057. This is equivalent to using set() to add each of the pairs from the other array.
  9058. */
  9059. void addArray (const StringPairArray& other);
  9060. /** Removes all elements from the array. */
  9061. void clear();
  9062. /** Removes a string from the array based on its key.
  9063. If the key isn't found, nothing will happen.
  9064. */
  9065. void remove (const String& key);
  9066. /** Removes a string from the array based on its index.
  9067. If the index is out-of-range, no action will be taken.
  9068. */
  9069. void remove (int index);
  9070. /** Indicates whether to use a case-insensitive search when looking up a key string.
  9071. */
  9072. void setIgnoresCase (bool shouldIgnoreCase);
  9073. /** Returns a descriptive string containing the items.
  9074. This is handy for dumping the contents of an array.
  9075. */
  9076. const String getDescription() const;
  9077. /** Reduces the amount of storage being used by the array.
  9078. Arrays typically allocate slightly more storage than they need, and after
  9079. removing elements, they may have quite a lot of unused space allocated.
  9080. This method will reduce the amount of allocated storage to a minimum.
  9081. */
  9082. void minimiseStorageOverheads();
  9083. private:
  9084. StringArray keys, values;
  9085. bool ignoreCase;
  9086. JUCE_LEAK_DETECTOR (StringPairArray);
  9087. };
  9088. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  9089. /*** End of inlined file: juce_StringPairArray.h ***/
  9090. /*** Start of inlined file: juce_XmlElement.h ***/
  9091. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  9092. #define __JUCE_XMLELEMENT_JUCEHEADER__
  9093. /*** Start of inlined file: juce_File.h ***/
  9094. #ifndef __JUCE_FILE_JUCEHEADER__
  9095. #define __JUCE_FILE_JUCEHEADER__
  9096. /*** Start of inlined file: juce_Time.h ***/
  9097. #ifndef __JUCE_TIME_JUCEHEADER__
  9098. #define __JUCE_TIME_JUCEHEADER__
  9099. /*** Start of inlined file: juce_RelativeTime.h ***/
  9100. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  9101. #define __JUCE_RELATIVETIME_JUCEHEADER__
  9102. /** A relative measure of time.
  9103. The time is stored as a number of seconds, at double-precision floating
  9104. point accuracy, and may be positive or negative.
  9105. If you need an absolute time, (i.e. a date + time), see the Time class.
  9106. */
  9107. class JUCE_API RelativeTime
  9108. {
  9109. public:
  9110. /** Creates a RelativeTime.
  9111. @param seconds the number of seconds, which may be +ve or -ve.
  9112. @see milliseconds, minutes, hours, days, weeks
  9113. */
  9114. explicit RelativeTime (double seconds = 0.0) noexcept;
  9115. /** Copies another relative time. */
  9116. RelativeTime (const RelativeTime& other) noexcept;
  9117. /** Copies another relative time. */
  9118. RelativeTime& operator= (const RelativeTime& other) noexcept;
  9119. /** Destructor. */
  9120. ~RelativeTime() noexcept;
  9121. /** Creates a new RelativeTime object representing a number of milliseconds.
  9122. @see minutes, hours, days, weeks
  9123. */
  9124. static const RelativeTime milliseconds (int milliseconds) noexcept;
  9125. /** Creates a new RelativeTime object representing a number of milliseconds.
  9126. @see minutes, hours, days, weeks
  9127. */
  9128. static const RelativeTime milliseconds (int64 milliseconds) noexcept;
  9129. /** Creates a new RelativeTime object representing a number of minutes.
  9130. @see milliseconds, hours, days, weeks
  9131. */
  9132. static const RelativeTime minutes (double numberOfMinutes) noexcept;
  9133. /** Creates a new RelativeTime object representing a number of hours.
  9134. @see milliseconds, minutes, days, weeks
  9135. */
  9136. static const RelativeTime hours (double numberOfHours) noexcept;
  9137. /** Creates a new RelativeTime object representing a number of days.
  9138. @see milliseconds, minutes, hours, weeks
  9139. */
  9140. static const RelativeTime days (double numberOfDays) noexcept;
  9141. /** Creates a new RelativeTime object representing a number of weeks.
  9142. @see milliseconds, minutes, hours, days
  9143. */
  9144. static const RelativeTime weeks (double numberOfWeeks) noexcept;
  9145. /** Returns the number of milliseconds this time represents.
  9146. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  9147. */
  9148. int64 inMilliseconds() const noexcept;
  9149. /** Returns the number of seconds this time represents.
  9150. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  9151. */
  9152. double inSeconds() const noexcept { return seconds; }
  9153. /** Returns the number of minutes this time represents.
  9154. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  9155. */
  9156. double inMinutes() const noexcept;
  9157. /** Returns the number of hours this time represents.
  9158. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  9159. */
  9160. double inHours() const noexcept;
  9161. /** Returns the number of days this time represents.
  9162. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  9163. */
  9164. double inDays() const noexcept;
  9165. /** Returns the number of weeks this time represents.
  9166. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  9167. */
  9168. double inWeeks() const noexcept;
  9169. /** Returns a readable textual description of the time.
  9170. The exact format of the string returned will depend on
  9171. the magnitude of the time - e.g.
  9172. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  9173. so that only the two most significant units are printed.
  9174. The returnValueForZeroTime value is the result that is returned if the
  9175. length is zero. Depending on your application you might want to use this
  9176. to return something more relevant like "empty" or "0 secs", etc.
  9177. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  9178. */
  9179. const String getDescription (const String& returnValueForZeroTime = "0") const;
  9180. /** Adds another RelativeTime to this one. */
  9181. const RelativeTime& operator+= (const RelativeTime& timeToAdd) noexcept;
  9182. /** Subtracts another RelativeTime from this one. */
  9183. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) noexcept;
  9184. /** Adds a number of seconds to this time. */
  9185. const RelativeTime& operator+= (double secondsToAdd) noexcept;
  9186. /** Subtracts a number of seconds from this time. */
  9187. const RelativeTime& operator-= (double secondsToSubtract) noexcept;
  9188. private:
  9189. double seconds;
  9190. };
  9191. /** Compares two RelativeTimes. */
  9192. bool operator== (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9193. /** Compares two RelativeTimes. */
  9194. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9195. /** Compares two RelativeTimes. */
  9196. bool operator> (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9197. /** Compares two RelativeTimes. */
  9198. bool operator< (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9199. /** Compares two RelativeTimes. */
  9200. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9201. /** Compares two RelativeTimes. */
  9202. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9203. /** Adds two RelativeTimes together. */
  9204. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9205. /** Subtracts two RelativeTimes. */
  9206. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9207. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  9208. /*** End of inlined file: juce_RelativeTime.h ***/
  9209. /**
  9210. Holds an absolute date and time.
  9211. Internally, the time is stored at millisecond precision.
  9212. @see RelativeTime
  9213. */
  9214. class JUCE_API Time
  9215. {
  9216. public:
  9217. /** Creates a Time object.
  9218. This default constructor creates a time of 1st January 1970, (which is
  9219. represented internally as 0ms).
  9220. To create a time object representing the current time, use getCurrentTime().
  9221. @see getCurrentTime
  9222. */
  9223. Time() noexcept;
  9224. /** Creates a time based on a number of milliseconds.
  9225. The internal millisecond count is set to 0 (1st January 1970). To create a
  9226. time object set to the current time, use getCurrentTime().
  9227. @param millisecondsSinceEpoch the number of milliseconds since the unix
  9228. 'epoch' (midnight Jan 1st 1970).
  9229. @see getCurrentTime, currentTimeMillis
  9230. */
  9231. explicit Time (int64 millisecondsSinceEpoch) noexcept;
  9232. /** Creates a time from a set of date components.
  9233. The timezone is assumed to be whatever the system is using as its locale.
  9234. @param year the year, in 4-digit format, e.g. 2004
  9235. @param month the month, in the range 0 to 11
  9236. @param day the day of the month, in the range 1 to 31
  9237. @param hours hours in 24-hour clock format, 0 to 23
  9238. @param minutes minutes 0 to 59
  9239. @param seconds seconds 0 to 59
  9240. @param milliseconds milliseconds 0 to 999
  9241. @param useLocalTime if true, encode using the current machine's local time; if
  9242. false, it will always work in GMT.
  9243. */
  9244. Time (int year,
  9245. int month,
  9246. int day,
  9247. int hours,
  9248. int minutes,
  9249. int seconds = 0,
  9250. int milliseconds = 0,
  9251. bool useLocalTime = true) noexcept;
  9252. /** Creates a copy of another Time object. */
  9253. Time (const Time& other) noexcept;
  9254. /** Destructor. */
  9255. ~Time() noexcept;
  9256. /** Copies this time from another one. */
  9257. Time& operator= (const Time& other) noexcept;
  9258. /** Returns a Time object that is set to the current system time.
  9259. @see currentTimeMillis
  9260. */
  9261. static const Time JUCE_CALLTYPE getCurrentTime() noexcept;
  9262. /** Returns the time as a number of milliseconds.
  9263. @returns the number of milliseconds this Time object represents, since
  9264. midnight jan 1st 1970.
  9265. @see getMilliseconds
  9266. */
  9267. int64 toMilliseconds() const noexcept { return millisSinceEpoch; }
  9268. /** Returns the year.
  9269. A 4-digit format is used, e.g. 2004.
  9270. */
  9271. int getYear() const noexcept;
  9272. /** Returns the number of the month.
  9273. The value returned is in the range 0 to 11.
  9274. @see getMonthName
  9275. */
  9276. int getMonth() const noexcept;
  9277. /** Returns the name of the month.
  9278. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  9279. it'll return the long form, e.g. "January"
  9280. @see getMonth
  9281. */
  9282. const String getMonthName (bool threeLetterVersion) const;
  9283. /** Returns the day of the month.
  9284. The value returned is in the range 1 to 31.
  9285. */
  9286. int getDayOfMonth() const noexcept;
  9287. /** Returns the number of the day of the week.
  9288. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  9289. */
  9290. int getDayOfWeek() const noexcept;
  9291. /** Returns the name of the weekday.
  9292. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  9293. false, it'll return the full version, e.g. "Tuesday".
  9294. */
  9295. const String getWeekdayName (bool threeLetterVersion) const;
  9296. /** Returns the number of hours since midnight.
  9297. This is in 24-hour clock format, in the range 0 to 23.
  9298. @see getHoursInAmPmFormat, isAfternoon
  9299. */
  9300. int getHours() const noexcept;
  9301. /** Returns true if the time is in the afternoon.
  9302. So it returns true for "PM", false for "AM".
  9303. @see getHoursInAmPmFormat, getHours
  9304. */
  9305. bool isAfternoon() const noexcept;
  9306. /** Returns the hours in 12-hour clock format.
  9307. This will return a value 1 to 12 - use isAfternoon() to find out
  9308. whether this is in the afternoon or morning.
  9309. @see getHours, isAfternoon
  9310. */
  9311. int getHoursInAmPmFormat() const noexcept;
  9312. /** Returns the number of minutes, 0 to 59. */
  9313. int getMinutes() const noexcept;
  9314. /** Returns the number of seconds, 0 to 59. */
  9315. int getSeconds() const noexcept;
  9316. /** Returns the number of milliseconds, 0 to 999.
  9317. Unlike toMilliseconds(), this just returns the position within the
  9318. current second rather than the total number since the epoch.
  9319. @see toMilliseconds
  9320. */
  9321. int getMilliseconds() const noexcept;
  9322. /** Returns true if the local timezone uses a daylight saving correction. */
  9323. bool isDaylightSavingTime() const noexcept;
  9324. /** Returns a 3-character string to indicate the local timezone. */
  9325. const String getTimeZone() const noexcept;
  9326. /** Quick way of getting a string version of a date and time.
  9327. For a more powerful way of formatting the date and time, see the formatted() method.
  9328. @param includeDate whether to include the date in the string
  9329. @param includeTime whether to include the time in the string
  9330. @param includeSeconds if the time is being included, this provides an option not to include
  9331. the seconds in it
  9332. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  9333. hour notation.
  9334. @see formatted
  9335. */
  9336. const String toString (bool includeDate,
  9337. bool includeTime,
  9338. bool includeSeconds = true,
  9339. bool use24HourClock = false) const noexcept;
  9340. /** Converts this date/time to a string with a user-defined format.
  9341. This uses the C strftime() function to format this time as a string. To save you
  9342. looking it up, these are the escape codes that strftime uses (other codes might
  9343. work on some platforms and not others, but these are the common ones):
  9344. %a is replaced by the locale's abbreviated weekday name.
  9345. %A is replaced by the locale's full weekday name.
  9346. %b is replaced by the locale's abbreviated month name.
  9347. %B is replaced by the locale's full month name.
  9348. %c is replaced by the locale's appropriate date and time representation.
  9349. %d is replaced by the day of the month as a decimal number [01,31].
  9350. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  9351. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  9352. %j is replaced by the day of the year as a decimal number [001,366].
  9353. %m is replaced by the month as a decimal number [01,12].
  9354. %M is replaced by the minute as a decimal number [00,59].
  9355. %p is replaced by the locale's equivalent of either a.m. or p.m.
  9356. %S is replaced by the second as a decimal number [00,61].
  9357. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  9358. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  9359. %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.
  9360. %x is replaced by the locale's appropriate date representation.
  9361. %X is replaced by the locale's appropriate time representation.
  9362. %y is replaced by the year without century as a decimal number [00,99].
  9363. %Y is replaced by the year with century as a decimal number.
  9364. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  9365. %% is replaced by %.
  9366. @see toString
  9367. */
  9368. const String formatted (const String& format) const;
  9369. /** Adds a RelativeTime to this time. */
  9370. Time& operator+= (const RelativeTime& delta);
  9371. /** Subtracts a RelativeTime from this time. */
  9372. Time& operator-= (const RelativeTime& delta);
  9373. /** Tries to set the computer's clock.
  9374. @returns true if this succeeds, although depending on the system, the
  9375. application might not have sufficient privileges to do this.
  9376. */
  9377. bool setSystemTimeToThisTime() const;
  9378. /** Returns the name of a day of the week.
  9379. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  9380. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  9381. false, it'll return the full version, e.g. "Tuesday".
  9382. */
  9383. static const String getWeekdayName (int dayNumber,
  9384. bool threeLetterVersion);
  9385. /** Returns the name of one of the months.
  9386. @param monthNumber the month, 0 to 11
  9387. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  9388. it'll return the long form, e.g. "January"
  9389. */
  9390. static const String getMonthName (int monthNumber,
  9391. bool threeLetterVersion);
  9392. // Static methods for getting system timers directly..
  9393. /** Returns the current system time.
  9394. Returns the number of milliseconds since midnight jan 1st 1970.
  9395. Should be accurate to within a few millisecs, depending on platform,
  9396. hardware, etc.
  9397. */
  9398. static int64 currentTimeMillis() noexcept;
  9399. /** Returns the number of millisecs since a fixed event (usually system startup).
  9400. This returns a monotonically increasing value which it unaffected by changes to the
  9401. system clock. It should be accurate to within a few millisecs, depending on platform,
  9402. hardware, etc.
  9403. @see getApproximateMillisecondCounter
  9404. */
  9405. static uint32 getMillisecondCounter() noexcept;
  9406. /** Returns the number of millisecs since a fixed event (usually system startup).
  9407. This has the same function as getMillisecondCounter(), but returns a more accurate
  9408. value, using a higher-resolution timer if one is available.
  9409. @see getMillisecondCounter
  9410. */
  9411. static double getMillisecondCounterHiRes() noexcept;
  9412. /** Waits until the getMillisecondCounter() reaches a given value.
  9413. This will make the thread sleep as efficiently as it can while it's waiting.
  9414. */
  9415. static void waitForMillisecondCounter (uint32 targetTime) noexcept;
  9416. /** Less-accurate but faster version of getMillisecondCounter().
  9417. This will return the last value that getMillisecondCounter() returned, so doesn't
  9418. need to make a system call, but is less accurate - it shouldn't be more than
  9419. 100ms away from the correct time, though, so is still accurate enough for a
  9420. lot of purposes.
  9421. @see getMillisecondCounter
  9422. */
  9423. static uint32 getApproximateMillisecondCounter() noexcept;
  9424. // High-resolution timers..
  9425. /** Returns the current high-resolution counter's tick-count.
  9426. This is a similar idea to getMillisecondCounter(), but with a higher
  9427. resolution.
  9428. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  9429. secondsToHighResolutionTicks
  9430. */
  9431. static int64 getHighResolutionTicks() noexcept;
  9432. /** Returns the resolution of the high-resolution counter in ticks per second.
  9433. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  9434. secondsToHighResolutionTicks
  9435. */
  9436. static int64 getHighResolutionTicksPerSecond() noexcept;
  9437. /** Converts a number of high-resolution ticks into seconds.
  9438. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  9439. secondsToHighResolutionTicks
  9440. */
  9441. static double highResolutionTicksToSeconds (int64 ticks) noexcept;
  9442. /** Converts a number seconds into high-resolution ticks.
  9443. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  9444. highResolutionTicksToSeconds
  9445. */
  9446. static int64 secondsToHighResolutionTicks (double seconds) noexcept;
  9447. private:
  9448. int64 millisSinceEpoch;
  9449. };
  9450. /** Adds a RelativeTime to a Time. */
  9451. JUCE_API const Time operator+ (const Time& time, const RelativeTime& delta);
  9452. /** Adds a RelativeTime to a Time. */
  9453. JUCE_API const Time operator+ (const RelativeTime& delta, const Time& time);
  9454. /** Subtracts a RelativeTime from a Time. */
  9455. JUCE_API const Time operator- (const Time& time, const RelativeTime& delta);
  9456. /** Returns the relative time difference between two times. */
  9457. JUCE_API const RelativeTime operator- (const Time& time1, const Time& time2);
  9458. /** Compares two Time objects. */
  9459. JUCE_API bool operator== (const Time& time1, const Time& time2);
  9460. /** Compares two Time objects. */
  9461. JUCE_API bool operator!= (const Time& time1, const Time& time2);
  9462. /** Compares two Time objects. */
  9463. JUCE_API bool operator< (const Time& time1, const Time& time2);
  9464. /** Compares two Time objects. */
  9465. JUCE_API bool operator<= (const Time& time1, const Time& time2);
  9466. /** Compares two Time objects. */
  9467. JUCE_API bool operator> (const Time& time1, const Time& time2);
  9468. /** Compares two Time objects. */
  9469. JUCE_API bool operator>= (const Time& time1, const Time& time2);
  9470. #endif // __JUCE_TIME_JUCEHEADER__
  9471. /*** End of inlined file: juce_Time.h ***/
  9472. /*** Start of inlined file: juce_Result.h ***/
  9473. #ifndef __JUCE_RESULT_JUCEHEADER__
  9474. #define __JUCE_RESULT_JUCEHEADER__
  9475. /**
  9476. Represents the 'success' or 'failure' of an operation, and holds an associated
  9477. error message to describe the error when there's a failure.
  9478. E.g.
  9479. @code
  9480. const Result myOperation()
  9481. {
  9482. if (doSomeKindOfFoobar())
  9483. return Result::ok();
  9484. else
  9485. return Result::fail ("foobar didn't work!");
  9486. }
  9487. const Result result (myOperation());
  9488. if (result.wasOk())
  9489. {
  9490. ...it's all good...
  9491. }
  9492. else
  9493. {
  9494. warnUserAboutFailure ("The foobar operation failed! Error message was: "
  9495. + result.getErrorMessage());
  9496. }
  9497. @endcode
  9498. */
  9499. class Result
  9500. {
  9501. public:
  9502. /** Creates and returns a 'successful' result. */
  9503. static const Result ok() noexcept;
  9504. /** Creates a 'failure' result.
  9505. If you pass a blank error message in here, a default "Unknown Error" message
  9506. will be used instead.
  9507. */
  9508. static const Result fail (const String& errorMessage) noexcept;
  9509. /** Returns true if this result indicates a success. */
  9510. bool wasOk() const noexcept;
  9511. /** Returns true if this result indicates a failure.
  9512. You can use getErrorMessage() to retrieve the error message associated
  9513. with the failure.
  9514. */
  9515. bool failed() const noexcept;
  9516. /** Returns true if this result indicates a success.
  9517. This is equivalent to calling wasOk().
  9518. */
  9519. operator bool() const noexcept;
  9520. /** Returns the error message that was set when this result was created.
  9521. For a successful result, this will be an empty string;
  9522. */
  9523. const String getErrorMessage() const noexcept;
  9524. Result (const Result& other);
  9525. Result& operator= (const Result& other);
  9526. bool operator== (const Result& other) const noexcept;
  9527. bool operator!= (const Result& other) const noexcept;
  9528. private:
  9529. String errorMessage;
  9530. explicit Result (const String& errorMessage) noexcept;
  9531. };
  9532. #endif // __JUCE_RESULT_JUCEHEADER__
  9533. /*** End of inlined file: juce_Result.h ***/
  9534. class FileInputStream;
  9535. class FileOutputStream;
  9536. /**
  9537. Represents a local file or directory.
  9538. This class encapsulates the absolute pathname of a file or directory, and
  9539. has methods for finding out about the file and changing its properties.
  9540. To read or write to the file, there are methods for returning an input or
  9541. output stream.
  9542. @see FileInputStream, FileOutputStream
  9543. */
  9544. class JUCE_API File
  9545. {
  9546. public:
  9547. /** Creates an (invalid) file object.
  9548. The file is initially set to an empty path, so getFullPath() will return
  9549. an empty string, and comparing the file to File::nonexistent will return
  9550. true.
  9551. You can use its operator= method to point it at a proper file.
  9552. */
  9553. File() {}
  9554. /** Creates a file from an absolute path.
  9555. If the path supplied is a relative path, it is taken to be relative
  9556. to the current working directory (see File::getCurrentWorkingDirectory()),
  9557. but this isn't a recommended way of creating a file, because you
  9558. never know what the CWD is going to be.
  9559. On the Mac/Linux, the path can include "~" notation for referring to
  9560. user home directories.
  9561. */
  9562. File (const String& path);
  9563. /** Creates a copy of another file object. */
  9564. File (const File& other);
  9565. /** Destructor. */
  9566. ~File() {}
  9567. /** Sets the file based on an absolute pathname.
  9568. If the path supplied is a relative path, it is taken to be relative
  9569. to the current working directory (see File::getCurrentWorkingDirectory()),
  9570. but this isn't a recommended way of creating a file, because you
  9571. never know what the CWD is going to be.
  9572. On the Mac/Linux, the path can include "~" notation for referring to
  9573. user home directories.
  9574. */
  9575. File& operator= (const String& newFilePath);
  9576. /** Copies from another file object. */
  9577. File& operator= (const File& otherFile);
  9578. /** This static constant is used for referring to an 'invalid' file. */
  9579. static const File nonexistent;
  9580. /** Checks whether the file actually exists.
  9581. @returns true if the file exists, either as a file or a directory.
  9582. @see existsAsFile, isDirectory
  9583. */
  9584. bool exists() const;
  9585. /** Checks whether the file exists and is a file rather than a directory.
  9586. @returns true only if this is a real file, false if it's a directory
  9587. or doesn't exist
  9588. @see exists, isDirectory
  9589. */
  9590. bool existsAsFile() const;
  9591. /** Checks whether the file is a directory that exists.
  9592. @returns true only if the file is a directory which actually exists, so
  9593. false if it's a file or doesn't exist at all
  9594. @see exists, existsAsFile
  9595. */
  9596. bool isDirectory() const;
  9597. /** Returns the size of the file in bytes.
  9598. @returns the number of bytes in the file, or 0 if it doesn't exist.
  9599. */
  9600. int64 getSize() const;
  9601. /** Utility function to convert a file size in bytes to a neat string description.
  9602. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  9603. 2000000 would produce "2 MB", etc.
  9604. */
  9605. static const String descriptionOfSizeInBytes (int64 bytes);
  9606. /** Returns the complete, absolute path of this file.
  9607. This includes the filename and all its parent folders. On Windows it'll
  9608. also include the drive letter prefix; on Mac or Linux it'll be a complete
  9609. path starting from the root folder.
  9610. If you just want the file's name, you should use getFileName() or
  9611. getFileNameWithoutExtension().
  9612. @see getFileName, getRelativePathFrom
  9613. */
  9614. const String& getFullPathName() const noexcept { return fullPath; }
  9615. /** Returns the last section of the pathname.
  9616. Returns just the final part of the path - e.g. if the whole path
  9617. is "/moose/fish/foo.txt" this will return "foo.txt".
  9618. For a directory, it returns the final part of the path - e.g. for the
  9619. directory "/moose/fish" it'll return "fish".
  9620. If the filename begins with a dot, it'll return the whole filename, e.g. for
  9621. "/moose/.fish", it'll return ".fish"
  9622. @see getFullPathName, getFileNameWithoutExtension
  9623. */
  9624. const String getFileName() const;
  9625. /** Creates a relative path that refers to a file relatively to a given directory.
  9626. e.g. File ("/moose/foo.txt").getRelativePathFrom (File ("/moose/fish/haddock"))
  9627. would return "../../foo.txt".
  9628. If it's not possible to navigate from one file to the other, an absolute
  9629. path is returned. If the paths are invalid, an empty string may also be
  9630. returned.
  9631. @param directoryToBeRelativeTo the directory which the resultant string will
  9632. be relative to. If this is actually a file rather than
  9633. a directory, its parent directory will be used instead.
  9634. If it doesn't exist, it's assumed to be a directory.
  9635. @see getChildFile, isAbsolutePath
  9636. */
  9637. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  9638. /** Returns the file's extension.
  9639. Returns the file extension of this file, also including the dot.
  9640. e.g. "/moose/fish/foo.txt" would return ".txt"
  9641. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  9642. */
  9643. const String getFileExtension() const;
  9644. /** Checks whether the file has a given extension.
  9645. @param extensionToTest the extension to look for - it doesn't matter whether or
  9646. not this string has a dot at the start, so ".wav" and "wav"
  9647. will have the same effect. The comparison used is
  9648. case-insensitve. To compare with multiple extensions, this
  9649. parameter can contain multiple strings, separated by semi-colons -
  9650. so, for example: hasFileExtension (".jpeg;png;gif") would return
  9651. true if the file has any of those three extensions.
  9652. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  9653. */
  9654. bool hasFileExtension (const String& extensionToTest) const;
  9655. /** Returns a version of this file with a different file extension.
  9656. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  9657. @param newExtension the new extension, either with or without a dot at the start (this
  9658. doesn't make any difference). To get remove a file's extension altogether,
  9659. pass an empty string into this function.
  9660. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  9661. */
  9662. const File withFileExtension (const String& newExtension) const;
  9663. /** Returns the last part of the filename, without its file extension.
  9664. e.g. for "/moose/fish/foo.txt" this will return "foo".
  9665. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  9666. */
  9667. const String getFileNameWithoutExtension() const;
  9668. /** Returns a 32-bit hash-code that identifies this file.
  9669. This is based on the filename. Obviously it's possible, although unlikely, that
  9670. two files will have the same hash-code.
  9671. */
  9672. int hashCode() const;
  9673. /** Returns a 64-bit hash-code that identifies this file.
  9674. This is based on the filename. Obviously it's possible, although unlikely, that
  9675. two files will have the same hash-code.
  9676. */
  9677. int64 hashCode64() const;
  9678. /** Returns a file based on a relative path.
  9679. This will find a child file or directory of the current object.
  9680. e.g.
  9681. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  9682. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  9683. If the string is actually an absolute path, it will be treated as such, e.g.
  9684. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  9685. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  9686. */
  9687. const File getChildFile (String relativePath) const;
  9688. /** Returns a file which is in the same directory as this one.
  9689. This is equivalent to getParentDirectory().getChildFile (name).
  9690. @see getChildFile, getParentDirectory
  9691. */
  9692. const File getSiblingFile (const String& siblingFileName) const;
  9693. /** Returns the directory that contains this file or directory.
  9694. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  9695. */
  9696. const File getParentDirectory() const;
  9697. /** Checks whether a file is somewhere inside a directory.
  9698. Returns true if this file is somewhere inside a subdirectory of the directory
  9699. that is passed in. Neither file actually has to exist, because the function
  9700. just checks the paths for similarities.
  9701. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  9702. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  9703. */
  9704. bool isAChildOf (const File& potentialParentDirectory) const;
  9705. /** Chooses a filename relative to this one that doesn't already exist.
  9706. If this file is a directory, this will return a child file of this
  9707. directory that doesn't exist, by adding numbers to a prefix and suffix until
  9708. it finds one that isn't already there.
  9709. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  9710. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  9711. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  9712. @param prefix the string to use for the filename before the number
  9713. @param suffix the string to add to the filename after the number
  9714. @param putNumbersInBrackets if true, this will create filenames in the
  9715. format "prefix(number)suffix", if false, it will leave the
  9716. brackets out.
  9717. */
  9718. const File getNonexistentChildFile (const String& prefix,
  9719. const String& suffix,
  9720. bool putNumbersInBrackets = true) const;
  9721. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  9722. If this file doesn't exist, this will just return itself, otherwise it
  9723. will return an appropriate sibling that doesn't exist, e.g. if a file
  9724. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  9725. @param putNumbersInBrackets whether to add brackets around the numbers that
  9726. get appended to the new filename.
  9727. */
  9728. const File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  9729. /** Compares the pathnames for two files. */
  9730. bool operator== (const File& otherFile) const;
  9731. /** Compares the pathnames for two files. */
  9732. bool operator!= (const File& otherFile) const;
  9733. /** Compares the pathnames for two files. */
  9734. bool operator< (const File& otherFile) const;
  9735. /** Compares the pathnames for two files. */
  9736. bool operator> (const File& otherFile) const;
  9737. /** Checks whether a file can be created or written to.
  9738. @returns true if it's possible to create and write to this file. If the file
  9739. doesn't already exist, this will check its parent directory to
  9740. see if writing is allowed.
  9741. @see setReadOnly
  9742. */
  9743. bool hasWriteAccess() const;
  9744. /** Changes the write-permission of a file or directory.
  9745. @param shouldBeReadOnly whether to add or remove write-permission
  9746. @param applyRecursively if the file is a directory and this is true, it will
  9747. recurse through all the subfolders changing the permissions
  9748. of all files
  9749. @returns true if it manages to change the file's permissions.
  9750. @see hasWriteAccess
  9751. */
  9752. bool setReadOnly (bool shouldBeReadOnly,
  9753. bool applyRecursively = false) const;
  9754. /** Returns true if this file is a hidden or system file.
  9755. The criteria for deciding whether a file is hidden are platform-dependent.
  9756. */
  9757. bool isHidden() const;
  9758. /** If this file is a link, this returns the file that it points to.
  9759. If this file isn't actually link, it'll just return itself.
  9760. */
  9761. const File getLinkedTarget() const;
  9762. /** Returns the last modification time of this file.
  9763. @returns the time, or an invalid time if the file doesn't exist.
  9764. @see setLastModificationTime, getLastAccessTime, getCreationTime
  9765. */
  9766. const Time getLastModificationTime() const;
  9767. /** Returns the last time this file was accessed.
  9768. @returns the time, or an invalid time if the file doesn't exist.
  9769. @see setLastAccessTime, getLastModificationTime, getCreationTime
  9770. */
  9771. const Time getLastAccessTime() const;
  9772. /** Returns the time that this file was created.
  9773. @returns the time, or an invalid time if the file doesn't exist.
  9774. @see getLastModificationTime, getLastAccessTime
  9775. */
  9776. const Time getCreationTime() const;
  9777. /** Changes the modification time for this file.
  9778. @param newTime the time to apply to the file
  9779. @returns true if it manages to change the file's time.
  9780. @see getLastModificationTime, setLastAccessTime, setCreationTime
  9781. */
  9782. bool setLastModificationTime (const Time& newTime) const;
  9783. /** Changes the last-access time for this file.
  9784. @param newTime the time to apply to the file
  9785. @returns true if it manages to change the file's time.
  9786. @see getLastAccessTime, setLastModificationTime, setCreationTime
  9787. */
  9788. bool setLastAccessTime (const Time& newTime) const;
  9789. /** Changes the creation date for this file.
  9790. @param newTime the time to apply to the file
  9791. @returns true if it manages to change the file's time.
  9792. @see getCreationTime, setLastModificationTime, setLastAccessTime
  9793. */
  9794. bool setCreationTime (const Time& newTime) const;
  9795. /** If possible, this will try to create a version string for the given file.
  9796. The OS may be able to look at the file and give a version for it - e.g. with
  9797. executables, bundles, dlls, etc. If no version is available, this will
  9798. return an empty string.
  9799. */
  9800. const String getVersion() const;
  9801. /** Creates an empty file if it doesn't already exist.
  9802. If the file that this object refers to doesn't exist, this will create a file
  9803. of zero size.
  9804. If it already exists or is a directory, this method will do nothing.
  9805. @returns true if the file has been created (or if it already existed).
  9806. @see createDirectory
  9807. */
  9808. const Result create() const;
  9809. /** Creates a new directory for this filename.
  9810. This will try to create the file as a directory, and fill also create
  9811. any parent directories it needs in order to complete the operation.
  9812. @returns a result to indicate whether the directory was created successfully, or
  9813. an error message if it failed.
  9814. @see create
  9815. */
  9816. const Result createDirectory() const;
  9817. /** Deletes a file.
  9818. If this file is actually a directory, it may not be deleted correctly if it
  9819. contains files. See deleteRecursively() as a better way of deleting directories.
  9820. @returns true if the file has been successfully deleted (or if it didn't exist to
  9821. begin with).
  9822. @see deleteRecursively
  9823. */
  9824. bool deleteFile() const;
  9825. /** Deletes a file or directory and all its subdirectories.
  9826. If this file is a directory, this will try to delete it and all its subfolders. If
  9827. it's just a file, it will just try to delete the file.
  9828. @returns true if the file and all its subfolders have been successfully deleted
  9829. (or if it didn't exist to begin with).
  9830. @see deleteFile
  9831. */
  9832. bool deleteRecursively() const;
  9833. /** Moves this file or folder to the trash.
  9834. @returns true if the operation succeeded. It could fail if the trash is full, or
  9835. if the file is write-protected, so you should check the return value
  9836. and act appropriately.
  9837. */
  9838. bool moveToTrash() const;
  9839. /** Moves or renames a file.
  9840. Tries to move a file to a different location.
  9841. If the target file already exists, this will attempt to delete it first, and
  9842. will fail if this can't be done.
  9843. Note that the destination file isn't the directory to put it in, it's the actual
  9844. filename that you want the new file to have.
  9845. @returns true if the operation succeeds
  9846. */
  9847. bool moveFileTo (const File& targetLocation) const;
  9848. /** Copies a file.
  9849. Tries to copy a file to a different location.
  9850. If the target file already exists, this will attempt to delete it first, and
  9851. will fail if this can't be done.
  9852. @returns true if the operation succeeds
  9853. */
  9854. bool copyFileTo (const File& targetLocation) const;
  9855. /** Copies a directory.
  9856. Tries to copy an entire directory, recursively.
  9857. If this file isn't a directory or if any target files can't be created, this
  9858. will return false.
  9859. @param newDirectory the directory that this one should be copied to. Note that this
  9860. is the name of the actual directory to create, not the directory
  9861. into which the new one should be placed, so there must be enough
  9862. write privileges to create it if it doesn't exist. Any files inside
  9863. it will be overwritten by similarly named ones that are copied.
  9864. */
  9865. bool copyDirectoryTo (const File& newDirectory) const;
  9866. /** Used in file searching, to specify whether to return files, directories, or both.
  9867. */
  9868. enum TypesOfFileToFind
  9869. {
  9870. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  9871. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  9872. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  9873. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  9874. };
  9875. /** Searches inside a directory for files matching a wildcard pattern.
  9876. Assuming that this file is a directory, this method will search it
  9877. for either files or subdirectories whose names match a filename pattern.
  9878. @param results an array to which File objects will be added for the
  9879. files that the search comes up with
  9880. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9881. return files, directories, or both. If the ignoreHiddenFiles flag
  9882. is also added to this value, hidden files won't be returned
  9883. @param searchRecursively if true, all subdirectories will be recursed into to do
  9884. an exhaustive search
  9885. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9886. @returns the number of results that have been found
  9887. @see getNumberOfChildFiles, DirectoryIterator
  9888. */
  9889. int findChildFiles (Array<File>& results,
  9890. int whatToLookFor,
  9891. bool searchRecursively,
  9892. const String& wildCardPattern = "*") const;
  9893. /** Searches inside a directory and counts how many files match a wildcard pattern.
  9894. Assuming that this file is a directory, this method will search it
  9895. for either files or subdirectories whose names match a filename pattern,
  9896. and will return the number of matches found.
  9897. This isn't a recursive call, and will only search this directory, not
  9898. its children.
  9899. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9900. count files, directories, or both. If the ignoreHiddenFiles flag
  9901. is also added to this value, hidden files won't be counted
  9902. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9903. @returns the number of matches found
  9904. @see findChildFiles, DirectoryIterator
  9905. */
  9906. int getNumberOfChildFiles (int whatToLookFor,
  9907. const String& wildCardPattern = "*") const;
  9908. /** Returns true if this file is a directory that contains one or more subdirectories.
  9909. @see isDirectory, findChildFiles
  9910. */
  9911. bool containsSubDirectories() const;
  9912. /** Creates a stream to read from this file.
  9913. @returns a stream that will read from this file (initially positioned at the
  9914. start of the file), or 0 if the file can't be opened for some reason
  9915. @see createOutputStream, loadFileAsData
  9916. */
  9917. FileInputStream* createInputStream() const;
  9918. /** Creates a stream to write to this file.
  9919. If the file exists, the stream that is returned will be positioned ready for
  9920. writing at the end of the file, so you might want to use deleteFile() first
  9921. to write to an empty file.
  9922. @returns a stream that will write to this file (initially positioned at the
  9923. end of the file), or 0 if the file can't be opened for some reason
  9924. @see createInputStream, appendData, appendText
  9925. */
  9926. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  9927. /** Loads a file's contents into memory as a block of binary data.
  9928. Of course, trying to load a very large file into memory will blow up, so
  9929. it's better to check first.
  9930. @param result the data block to which the file's contents should be appended - note
  9931. that if the memory block might already contain some data, you
  9932. might want to clear it first
  9933. @returns true if the file could all be read into memory
  9934. */
  9935. bool loadFileAsData (MemoryBlock& result) const;
  9936. /** Reads a file into memory as a string.
  9937. Attempts to load the entire file as a zero-terminated string.
  9938. This makes use of InputStream::readEntireStreamAsString, which should
  9939. automatically cope with unicode/acsii file formats.
  9940. */
  9941. const String loadFileAsString() const;
  9942. /** Appends a block of binary data to the end of the file.
  9943. This will try to write the given buffer to the end of the file.
  9944. @returns false if it can't write to the file for some reason
  9945. */
  9946. bool appendData (const void* dataToAppend,
  9947. int numberOfBytes) const;
  9948. /** Replaces this file's contents with a given block of data.
  9949. This will delete the file and replace it with the given data.
  9950. A nice feature of this method is that it's safe - instead of deleting
  9951. the file first and then re-writing it, it creates a new temporary file,
  9952. writes the data to that, and then moves the new file to replace the existing
  9953. file. This means that if the power gets pulled out or something crashes,
  9954. you're a lot less likely to end up with a corrupted or unfinished file..
  9955. Returns true if the operation succeeds, or false if it fails.
  9956. @see appendText
  9957. */
  9958. bool replaceWithData (const void* dataToWrite,
  9959. int numberOfBytes) const;
  9960. /** Appends a string to the end of the file.
  9961. This will try to append a text string to the file, as either 16-bit unicode
  9962. or 8-bit characters in the default system encoding.
  9963. It can also write the 'ff fe' unicode header bytes before the text to indicate
  9964. the endianness of the file.
  9965. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  9966. @see replaceWithText
  9967. */
  9968. bool appendText (const String& textToAppend,
  9969. bool asUnicode = false,
  9970. bool writeUnicodeHeaderBytes = false) const;
  9971. /** Replaces this file's contents with a given text string.
  9972. This will delete the file and replace it with the given text.
  9973. A nice feature of this method is that it's safe - instead of deleting
  9974. the file first and then re-writing it, it creates a new temporary file,
  9975. writes the text to that, and then moves the new file to replace the existing
  9976. file. This means that if the power gets pulled out or something crashes,
  9977. you're a lot less likely to end up with an empty file..
  9978. For an explanation of the parameters here, see the appendText() method.
  9979. Returns true if the operation succeeds, or false if it fails.
  9980. @see appendText
  9981. */
  9982. bool replaceWithText (const String& textToWrite,
  9983. bool asUnicode = false,
  9984. bool writeUnicodeHeaderBytes = false) const;
  9985. /** Attempts to scan the contents of this file and compare it to another file, returning
  9986. true if this is possible and they match byte-for-byte.
  9987. */
  9988. bool hasIdenticalContentTo (const File& other) const;
  9989. /** Creates a set of files to represent each file root.
  9990. e.g. on Windows this will create files for "c:\", "d:\" etc according
  9991. to which ones are available. On the Mac/Linux, this will probably
  9992. just add a single entry for "/".
  9993. */
  9994. static void findFileSystemRoots (Array<File>& results);
  9995. /** Finds the name of the drive on which this file lives.
  9996. @returns the volume label of the drive, or an empty string if this isn't possible
  9997. */
  9998. const String getVolumeLabel() const;
  9999. /** Returns the serial number of the volume on which this file lives.
  10000. @returns the serial number, or zero if there's a problem doing this
  10001. */
  10002. int getVolumeSerialNumber() const;
  10003. /** Returns the number of bytes free on the drive that this file lives on.
  10004. @returns the number of bytes free, or 0 if there's a problem finding this out
  10005. @see getVolumeTotalSize
  10006. */
  10007. int64 getBytesFreeOnVolume() const;
  10008. /** Returns the total size of the drive that contains this file.
  10009. @returns the total number of bytes that the volume can hold
  10010. @see getBytesFreeOnVolume
  10011. */
  10012. int64 getVolumeTotalSize() const;
  10013. /** Returns true if this file is on a CD or DVD drive. */
  10014. bool isOnCDRomDrive() const;
  10015. /** Returns true if this file is on a hard disk.
  10016. This will fail if it's a network drive, but will still be true for
  10017. removable hard-disks.
  10018. */
  10019. bool isOnHardDisk() const;
  10020. /** Returns true if this file is on a removable disk drive.
  10021. This might be a usb-drive, a CD-rom, or maybe a network drive.
  10022. */
  10023. bool isOnRemovableDrive() const;
  10024. /** Launches the file as a process.
  10025. - if the file is executable, this will run it.
  10026. - if it's a document of some kind, it will launch the document with its
  10027. default viewer application.
  10028. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  10029. @see revealToUser
  10030. */
  10031. bool startAsProcess (const String& parameters = String::empty) const;
  10032. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  10033. @see startAsProcess
  10034. */
  10035. void revealToUser() const;
  10036. /** A set of types of location that can be passed to the getSpecialLocation() method.
  10037. */
  10038. enum SpecialLocationType
  10039. {
  10040. /** The user's home folder. This is the same as using File ("~"). */
  10041. userHomeDirectory,
  10042. /** The user's default documents folder. On Windows, this might be the user's
  10043. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  10044. doesn't tend to have one of these, so it might just return their home folder.
  10045. */
  10046. userDocumentsDirectory,
  10047. /** The folder that contains the user's desktop objects. */
  10048. userDesktopDirectory,
  10049. /** The folder in which applications store their persistent user-specific settings.
  10050. On Windows, this might be "\Documents and Settings\username\Application Data".
  10051. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  10052. always create your own sub-folder to put them in, to avoid making a mess.
  10053. */
  10054. userApplicationDataDirectory,
  10055. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  10056. of the computer, rather than just the current user.
  10057. On the Mac it'll be "/Library", on Windows, it could be something like
  10058. "\Documents and Settings\All Users\Application Data".
  10059. Depending on the setup, this folder may be read-only.
  10060. */
  10061. commonApplicationDataDirectory,
  10062. /** The folder that should be used for temporary files.
  10063. Always delete them when you're finished, to keep the user's computer tidy!
  10064. */
  10065. tempDirectory,
  10066. /** Returns this application's executable file.
  10067. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  10068. host app.
  10069. On the mac this will return the unix binary, not the package folder - see
  10070. currentApplicationFile for that.
  10071. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  10072. file link, invokedExecutableFile will return the name of the link.
  10073. */
  10074. currentExecutableFile,
  10075. /** Returns this application's location.
  10076. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  10077. host app.
  10078. On the mac this will return the package folder (if it's in one), not the unix binary
  10079. that's inside it - compare with currentExecutableFile.
  10080. */
  10081. currentApplicationFile,
  10082. /** Returns the file that was invoked to launch this executable.
  10083. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  10084. will return the name of the link that was used, whereas currentExecutableFile will return
  10085. the actual location of the target executable.
  10086. */
  10087. invokedExecutableFile,
  10088. /** In a plugin, this will return the path of the host executable. */
  10089. hostApplicationPath,
  10090. /** The directory in which applications normally get installed.
  10091. So on windows, this would be something like "c:\program files", on the
  10092. Mac "/Applications", or "/usr" on linux.
  10093. */
  10094. globalApplicationsDirectory,
  10095. /** The most likely place where a user might store their music files.
  10096. */
  10097. userMusicDirectory,
  10098. /** The most likely place where a user might store their movie files.
  10099. */
  10100. userMoviesDirectory,
  10101. };
  10102. /** Finds the location of a special type of file or directory, such as a home folder or
  10103. documents folder.
  10104. @see SpecialLocationType
  10105. */
  10106. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  10107. /** Returns a temporary file in the system's temp directory.
  10108. This will try to return the name of a non-existent temp file.
  10109. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  10110. */
  10111. static const File createTempFile (const String& fileNameEnding);
  10112. /** Returns the current working directory.
  10113. @see setAsCurrentWorkingDirectory
  10114. */
  10115. static const File getCurrentWorkingDirectory();
  10116. /** Sets the current working directory to be this file.
  10117. For this to work the file must point to a valid directory.
  10118. @returns true if the current directory has been changed.
  10119. @see getCurrentWorkingDirectory
  10120. */
  10121. bool setAsCurrentWorkingDirectory() const;
  10122. /** The system-specific file separator character.
  10123. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  10124. */
  10125. static const juce_wchar separator;
  10126. /** The system-specific file separator character, as a string.
  10127. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  10128. */
  10129. static const String separatorString;
  10130. /** Removes illegal characters from a filename.
  10131. This will return a copy of the given string after removing characters
  10132. that are not allowed in a legal filename, and possibly shortening the
  10133. string if it's too long.
  10134. Because this will remove slashes, don't use it on an absolute pathname.
  10135. @see createLegalPathName
  10136. */
  10137. static const String createLegalFileName (const String& fileNameToFix);
  10138. /** Removes illegal characters from a pathname.
  10139. Similar to createLegalFileName(), but this won't remove slashes, so can
  10140. be used on a complete pathname.
  10141. @see createLegalFileName
  10142. */
  10143. static const String createLegalPathName (const String& pathNameToFix);
  10144. /** Indicates whether filenames are case-sensitive on the current operating system.
  10145. */
  10146. static bool areFileNamesCaseSensitive();
  10147. /** Returns true if the string seems to be a fully-specified absolute path.
  10148. */
  10149. static bool isAbsolutePath (const String& path);
  10150. /** Creates a file that simply contains this string, without doing the sanity-checking
  10151. that the normal constructors do.
  10152. Best to avoid this unless you really know what you're doing.
  10153. */
  10154. static const File createFileWithoutCheckingPath (const String& path);
  10155. /** Adds a separator character to the end of a path if it doesn't already have one. */
  10156. static const String addTrailingSeparator (const String& path);
  10157. private:
  10158. String fullPath;
  10159. // internal way of contructing a file without checking the path
  10160. friend class DirectoryIterator;
  10161. File (const String&, int);
  10162. const String getPathUpToLastSlash() const;
  10163. const Result createDirectoryInternal (const String& fileName) const;
  10164. bool copyInternal (const File& dest) const;
  10165. bool moveInternal (const File& dest) const;
  10166. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  10167. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  10168. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  10169. static const String parseAbsolutePath (const String& path);
  10170. JUCE_LEAK_DETECTOR (File);
  10171. };
  10172. #endif // __JUCE_FILE_JUCEHEADER__
  10173. /*** End of inlined file: juce_File.h ***/
  10174. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  10175. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  10176. will be the name of a pointer to each child element.
  10177. E.g. @code
  10178. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  10179. forEachXmlChildElement (*myParentXml, child)
  10180. {
  10181. if (child->hasTagName ("FOO"))
  10182. doSomethingWithXmlElement (child);
  10183. }
  10184. @endcode
  10185. @see forEachXmlChildElementWithTagName
  10186. */
  10187. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  10188. \
  10189. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  10190. childElementVariableName != 0; \
  10191. childElementVariableName = childElementVariableName->getNextElement())
  10192. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  10193. which have a specified tag.
  10194. This does the same job as the forEachXmlChildElement macro, but only for those
  10195. elements that have a particular tag name.
  10196. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  10197. will be the name of a pointer to each child element. The requiredTagName is the
  10198. tag name to match.
  10199. E.g. @code
  10200. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  10201. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  10202. {
  10203. // the child object is now guaranteed to be a <MYTAG> element..
  10204. doSomethingWithMYTAGElement (child);
  10205. }
  10206. @endcode
  10207. @see forEachXmlChildElement
  10208. */
  10209. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  10210. \
  10211. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  10212. childElementVariableName != 0; \
  10213. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  10214. /** Used to build a tree of elements representing an XML document.
  10215. An XML document can be parsed into a tree of XmlElements, each of which
  10216. represents an XML tag structure, and which may itself contain other
  10217. nested elements.
  10218. An XmlElement can also be converted back into a text document, and has
  10219. lots of useful methods for manipulating its attributes and sub-elements,
  10220. so XmlElements can actually be used as a handy general-purpose data
  10221. structure.
  10222. Here's an example of parsing some elements: @code
  10223. // check we're looking at the right kind of document..
  10224. if (myElement->hasTagName ("ANIMALS"))
  10225. {
  10226. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  10227. forEachXmlChildElement (*myElement, e)
  10228. {
  10229. if (e->hasTagName ("GIRAFFE"))
  10230. {
  10231. // found a giraffe, so use some of its attributes..
  10232. String giraffeName = e->getStringAttribute ("name");
  10233. int giraffeAge = e->getIntAttribute ("age");
  10234. bool isFriendly = e->getBoolAttribute ("friendly");
  10235. }
  10236. }
  10237. }
  10238. @endcode
  10239. And here's an example of how to create an XML document from scratch: @code
  10240. // create an outer node called "ANIMALS"
  10241. XmlElement animalsList ("ANIMALS");
  10242. for (int i = 0; i < numAnimals; ++i)
  10243. {
  10244. // create an inner element..
  10245. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  10246. giraffe->setAttribute ("name", "nigel");
  10247. giraffe->setAttribute ("age", 10);
  10248. giraffe->setAttribute ("friendly", true);
  10249. // ..and add our new element to the parent node
  10250. animalsList.addChildElement (giraffe);
  10251. }
  10252. // now we can turn the whole thing into a text document..
  10253. String myXmlDoc = animalsList.createDocument (String::empty);
  10254. @endcode
  10255. @see XmlDocument
  10256. */
  10257. class JUCE_API XmlElement
  10258. {
  10259. public:
  10260. /** Creates an XmlElement with this tag name. */
  10261. explicit XmlElement (const String& tagName) noexcept;
  10262. /** Creates a (deep) copy of another element. */
  10263. XmlElement (const XmlElement& other);
  10264. /** Creates a (deep) copy of another element. */
  10265. XmlElement& operator= (const XmlElement& other);
  10266. /** Deleting an XmlElement will also delete all its child elements. */
  10267. ~XmlElement() noexcept;
  10268. /** Compares two XmlElements to see if they contain the same text and attiributes.
  10269. The elements are only considered equivalent if they contain the same attiributes
  10270. with the same values, and have the same sub-nodes.
  10271. @param other the other element to compare to
  10272. @param ignoreOrderOfAttributes if true, this means that two elements with the
  10273. same attributes in a different order will be
  10274. considered the same; if false, the attributes must
  10275. be in the same order as well
  10276. */
  10277. bool isEquivalentTo (const XmlElement* other,
  10278. bool ignoreOrderOfAttributes) const noexcept;
  10279. /** Returns an XML text document that represents this element.
  10280. The string returned can be parsed to recreate the same XmlElement that
  10281. was used to create it.
  10282. @param dtdToUse the DTD to add to the document
  10283. @param allOnOneLine if true, this means that the document will not contain any
  10284. linefeeds, so it'll be smaller but not very easy to read.
  10285. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  10286. document
  10287. @param encodingType the character encoding format string to put into the xml
  10288. header
  10289. @param lineWrapLength the line length that will be used before items get placed on
  10290. a new line. This isn't an absolute maximum length, it just
  10291. determines how lists of attributes get broken up
  10292. @see writeToStream, writeToFile
  10293. */
  10294. const String createDocument (const String& dtdToUse,
  10295. bool allOnOneLine = false,
  10296. bool includeXmlHeader = true,
  10297. const String& encodingType = "UTF-8",
  10298. int lineWrapLength = 60) const;
  10299. /** Writes the document to a stream as UTF-8.
  10300. @param output the stream to write to
  10301. @param dtdToUse the DTD to add to the document
  10302. @param allOnOneLine if true, this means that the document will not contain any
  10303. linefeeds, so it'll be smaller but not very easy to read.
  10304. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  10305. document
  10306. @param encodingType the character encoding format string to put into the xml
  10307. header
  10308. @param lineWrapLength the line length that will be used before items get placed on
  10309. a new line. This isn't an absolute maximum length, it just
  10310. determines how lists of attributes get broken up
  10311. @see writeToFile, createDocument
  10312. */
  10313. void writeToStream (OutputStream& output,
  10314. const String& dtdToUse,
  10315. bool allOnOneLine = false,
  10316. bool includeXmlHeader = true,
  10317. const String& encodingType = "UTF-8",
  10318. int lineWrapLength = 60) const;
  10319. /** Writes the element to a file as an XML document.
  10320. To improve safety in case something goes wrong while writing the file, this
  10321. will actually write the document to a new temporary file in the same
  10322. directory as the destination file, and if this succeeds, it will rename this
  10323. new file as the destination file (overwriting any existing file that was there).
  10324. @param destinationFile the file to write to. If this already exists, it will be
  10325. overwritten.
  10326. @param dtdToUse the DTD to add to the document
  10327. @param encodingType the character encoding format string to put into the xml
  10328. header
  10329. @param lineWrapLength the line length that will be used before items get placed on
  10330. a new line. This isn't an absolute maximum length, it just
  10331. determines how lists of attributes get broken up
  10332. @returns true if the file is written successfully; false if something goes wrong
  10333. in the process
  10334. @see createDocument
  10335. */
  10336. bool writeToFile (const File& destinationFile,
  10337. const String& dtdToUse,
  10338. const String& encodingType = "UTF-8",
  10339. int lineWrapLength = 60) const;
  10340. /** Returns this element's tag type name.
  10341. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  10342. "MOOSE".
  10343. @see hasTagName
  10344. */
  10345. inline const String& getTagName() const noexcept { return tagName; }
  10346. /** Tests whether this element has a particular tag name.
  10347. @param possibleTagName the tag name you're comparing it with
  10348. @see getTagName
  10349. */
  10350. bool hasTagName (const String& possibleTagName) const noexcept;
  10351. /** Returns the number of XML attributes this element contains.
  10352. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  10353. return 2.
  10354. */
  10355. int getNumAttributes() const noexcept;
  10356. /** Returns the name of one of the elements attributes.
  10357. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  10358. getAttributeName(1) would return "antlers".
  10359. @see getAttributeValue, getStringAttribute
  10360. */
  10361. const String& getAttributeName (int attributeIndex) const noexcept;
  10362. /** Returns the value of one of the elements attributes.
  10363. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  10364. getAttributeName(1) would return "2".
  10365. @see getAttributeName, getStringAttribute
  10366. */
  10367. const String& getAttributeValue (int attributeIndex) const noexcept;
  10368. // Attribute-handling methods..
  10369. /** Checks whether the element contains an attribute with a certain name. */
  10370. bool hasAttribute (const String& attributeName) const noexcept;
  10371. /** Returns the value of a named attribute.
  10372. @param attributeName the name of the attribute to look up
  10373. */
  10374. const String& getStringAttribute (const String& attributeName) const noexcept;
  10375. /** Returns the value of a named attribute.
  10376. @param attributeName the name of the attribute to look up
  10377. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10378. with this name
  10379. */
  10380. const String getStringAttribute (const String& attributeName,
  10381. const String& defaultReturnValue) const;
  10382. /** Compares the value of a named attribute with a value passed-in.
  10383. @param attributeName the name of the attribute to look up
  10384. @param stringToCompareAgainst the value to compare it with
  10385. @param ignoreCase whether the comparison should be case-insensitive
  10386. @returns true if the value of the attribute is the same as the string passed-in;
  10387. false if it's different (or if no such attribute exists)
  10388. */
  10389. bool compareAttribute (const String& attributeName,
  10390. const String& stringToCompareAgainst,
  10391. bool ignoreCase = false) const noexcept;
  10392. /** Returns the value of a named attribute as an integer.
  10393. This will try to find the attribute and convert it to an integer (using
  10394. the String::getIntValue() method).
  10395. @param attributeName the name of the attribute to look up
  10396. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10397. with this name
  10398. @see setAttribute
  10399. */
  10400. int getIntAttribute (const String& attributeName,
  10401. int defaultReturnValue = 0) const;
  10402. /** Returns the value of a named attribute as floating-point.
  10403. This will try to find the attribute and convert it to an integer (using
  10404. the String::getDoubleValue() method).
  10405. @param attributeName the name of the attribute to look up
  10406. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10407. with this name
  10408. @see setAttribute
  10409. */
  10410. double getDoubleAttribute (const String& attributeName,
  10411. double defaultReturnValue = 0.0) const;
  10412. /** Returns the value of a named attribute as a boolean.
  10413. This will try to find the attribute and interpret it as a boolean. To do this,
  10414. it'll return true if the value is "1", "true", "y", etc, or false for other
  10415. values.
  10416. @param attributeName the name of the attribute to look up
  10417. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10418. with this name
  10419. */
  10420. bool getBoolAttribute (const String& attributeName,
  10421. bool defaultReturnValue = false) const;
  10422. /** Adds a named attribute to the element.
  10423. If the element already contains an attribute with this name, it's value will
  10424. be updated to the new value. If there's no such attribute yet, a new one will
  10425. be added.
  10426. Note that there are other setAttribute() methods that take integers,
  10427. doubles, etc. to make it easy to store numbers.
  10428. @param attributeName the name of the attribute to set
  10429. @param newValue the value to set it to
  10430. @see removeAttribute
  10431. */
  10432. void setAttribute (const String& attributeName,
  10433. const String& newValue);
  10434. /** Adds a named attribute to the element, setting it to an integer value.
  10435. If the element already contains an attribute with this name, it's value will
  10436. be updated to the new value. If there's no such attribute yet, a new one will
  10437. be added.
  10438. Note that there are other setAttribute() methods that take integers,
  10439. doubles, etc. to make it easy to store numbers.
  10440. @param attributeName the name of the attribute to set
  10441. @param newValue the value to set it to
  10442. */
  10443. void setAttribute (const String& attributeName,
  10444. int newValue);
  10445. /** Adds a named attribute to the element, setting it to a floating-point value.
  10446. If the element already contains an attribute with this name, it's value will
  10447. be updated to the new value. If there's no such attribute yet, a new one will
  10448. be added.
  10449. Note that there are other setAttribute() methods that take integers,
  10450. doubles, etc. to make it easy to store numbers.
  10451. @param attributeName the name of the attribute to set
  10452. @param newValue the value to set it to
  10453. */
  10454. void setAttribute (const String& attributeName,
  10455. double newValue);
  10456. /** Removes a named attribute from the element.
  10457. @param attributeName the name of the attribute to remove
  10458. @see removeAllAttributes
  10459. */
  10460. void removeAttribute (const String& attributeName) noexcept;
  10461. /** Removes all attributes from this element.
  10462. */
  10463. void removeAllAttributes() noexcept;
  10464. // Child element methods..
  10465. /** Returns the first of this element's sub-elements.
  10466. see getNextElement() for an example of how to iterate the sub-elements.
  10467. @see forEachXmlChildElement
  10468. */
  10469. XmlElement* getFirstChildElement() const noexcept { return firstChildElement; }
  10470. /** Returns the next of this element's siblings.
  10471. This can be used for iterating an element's sub-elements, e.g.
  10472. @code
  10473. XmlElement* child = myXmlDocument->getFirstChildElement();
  10474. while (child != nullptr)
  10475. {
  10476. ...do stuff with this child..
  10477. child = child->getNextElement();
  10478. }
  10479. @endcode
  10480. Note that when iterating the child elements, some of them might be
  10481. text elements as well as XML tags - use isTextElement() to work this
  10482. out.
  10483. Also, it's much easier and neater to use this method indirectly via the
  10484. forEachXmlChildElement macro.
  10485. @returns the sibling element that follows this one, or zero if this is the last
  10486. element in its parent
  10487. @see getNextElement, isTextElement, forEachXmlChildElement
  10488. */
  10489. inline XmlElement* getNextElement() const noexcept { return nextListItem; }
  10490. /** Returns the next of this element's siblings which has the specified tag
  10491. name.
  10492. This is like getNextElement(), but will scan through the list until it
  10493. finds an element with the given tag name.
  10494. @see getNextElement, forEachXmlChildElementWithTagName
  10495. */
  10496. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  10497. /** Returns the number of sub-elements in this element.
  10498. @see getChildElement
  10499. */
  10500. int getNumChildElements() const noexcept;
  10501. /** Returns the sub-element at a certain index.
  10502. It's not very efficient to iterate the sub-elements by index - see
  10503. getNextElement() for an example of how best to iterate.
  10504. @returns the n'th child of this element, or 0 if the index is out-of-range
  10505. @see getNextElement, isTextElement, getChildByName
  10506. */
  10507. XmlElement* getChildElement (int index) const noexcept;
  10508. /** Returns the first sub-element with a given tag-name.
  10509. @param tagNameToLookFor the tag name of the element you want to find
  10510. @returns the first element with this tag name, or 0 if none is found
  10511. @see getNextElement, isTextElement, getChildElement
  10512. */
  10513. XmlElement* getChildByName (const String& tagNameToLookFor) const noexcept;
  10514. /** Appends an element to this element's list of children.
  10515. Child elements are deleted automatically when their parent is deleted, so
  10516. make sure the object that you pass in will not be deleted by anything else,
  10517. and make sure it's not already the child of another element.
  10518. @see getFirstChildElement, getNextElement, getNumChildElements,
  10519. getChildElement, removeChildElement
  10520. */
  10521. void addChildElement (XmlElement* newChildElement) noexcept;
  10522. /** Inserts an element into this element's list of children.
  10523. Child elements are deleted automatically when their parent is deleted, so
  10524. make sure the object that you pass in will not be deleted by anything else,
  10525. and make sure it's not already the child of another element.
  10526. @param newChildNode the element to add
  10527. @param indexToInsertAt the index at which to insert the new element - if this is
  10528. below zero, it will be added to the end of the list
  10529. @see addChildElement, insertChildElement
  10530. */
  10531. void insertChildElement (XmlElement* newChildNode,
  10532. int indexToInsertAt) noexcept;
  10533. /** Creates a new element with the given name and returns it, after adding it
  10534. as a child element.
  10535. This is a handy method that means that instead of writing this:
  10536. @code
  10537. XmlElement* newElement = new XmlElement ("foobar");
  10538. myParentElement->addChildElement (newElement);
  10539. @endcode
  10540. ..you could just write this:
  10541. @code
  10542. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  10543. @endcode
  10544. */
  10545. XmlElement* createNewChildElement (const String& tagName);
  10546. /** Replaces one of this element's children with another node.
  10547. If the current element passed-in isn't actually a child of this element,
  10548. this will return false and the new one won't be added. Otherwise, the
  10549. existing element will be deleted, replaced with the new one, and it
  10550. will return true.
  10551. */
  10552. bool replaceChildElement (XmlElement* currentChildElement,
  10553. XmlElement* newChildNode) noexcept;
  10554. /** Removes a child element.
  10555. @param childToRemove the child to look for and remove
  10556. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  10557. just remove it
  10558. */
  10559. void removeChildElement (XmlElement* childToRemove,
  10560. bool shouldDeleteTheChild) noexcept;
  10561. /** Deletes all the child elements in the element.
  10562. @see removeChildElement, deleteAllChildElementsWithTagName
  10563. */
  10564. void deleteAllChildElements() noexcept;
  10565. /** Deletes all the child elements with a given tag name.
  10566. @see removeChildElement
  10567. */
  10568. void deleteAllChildElementsWithTagName (const String& tagName) noexcept;
  10569. /** Returns true if the given element is a child of this one. */
  10570. bool containsChildElement (const XmlElement* possibleChild) const noexcept;
  10571. /** Recursively searches all sub-elements to find one that contains the specified
  10572. child element.
  10573. */
  10574. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) noexcept;
  10575. /** Sorts the child elements using a comparator.
  10576. This will use a comparator object to sort the elements into order. The object
  10577. passed must have a method of the form:
  10578. @code
  10579. int compareElements (const XmlElement* first, const XmlElement* second);
  10580. @endcode
  10581. ..and this method must return:
  10582. - a value of < 0 if the first comes before the second
  10583. - a value of 0 if the two objects are equivalent
  10584. - a value of > 0 if the second comes before the first
  10585. To improve performance, the compareElements() method can be declared as static or const.
  10586. @param comparator the comparator to use for comparing elements.
  10587. @param retainOrderOfEquivalentItems if this is true, then items which the comparator
  10588. says are equivalent will be kept in the order in which they
  10589. currently appear in the array. This is slower to perform, but
  10590. may be important in some cases. If it's false, a faster algorithm
  10591. is used, but equivalent elements may be rearranged.
  10592. */
  10593. template <class ElementComparator>
  10594. void sortChildElements (ElementComparator& comparator,
  10595. bool retainOrderOfEquivalentItems = false)
  10596. {
  10597. const int num = getNumChildElements();
  10598. if (num > 1)
  10599. {
  10600. HeapBlock <XmlElement*> elems (num);
  10601. getChildElementsAsArray (elems);
  10602. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  10603. reorderChildElements (elems, num);
  10604. }
  10605. }
  10606. /** Returns true if this element is a section of text.
  10607. Elements can either be an XML tag element or a secton of text, so this
  10608. is used to find out what kind of element this one is.
  10609. @see getAllText, addTextElement, deleteAllTextElements
  10610. */
  10611. bool isTextElement() const noexcept;
  10612. /** Returns the text for a text element.
  10613. Note that if you have an element like this:
  10614. @code<xyz>hello</xyz>@endcode
  10615. then calling getText on the "xyz" element won't return "hello", because that is
  10616. actually stored in a special text sub-element inside the xyz element. To get the
  10617. "hello" string, you could either call getText on the (unnamed) sub-element, or
  10618. use getAllSubText() to do this automatically.
  10619. Note that leading and trailing whitespace will be included in the string - to remove
  10620. if, just call String::trim() on the result.
  10621. @see isTextElement, getAllSubText, getChildElementAllSubText
  10622. */
  10623. const String& getText() const noexcept;
  10624. /** Sets the text in a text element.
  10625. Note that this is only a valid call if this element is a text element. If it's
  10626. not, then no action will be performed. If you're trying to add text inside a normal
  10627. element, you probably want to use addTextElement() instead.
  10628. */
  10629. void setText (const String& newText);
  10630. /** Returns all the text from this element's child nodes.
  10631. This iterates all the child elements and when it finds text elements,
  10632. it concatenates their text into a big string which it returns.
  10633. E.g. @code<xyz>hello <x>there</x> world</xyz>@endcode
  10634. if you called getAllSubText on the "xyz" element, it'd return "hello there world".
  10635. Note that leading and trailing whitespace will be included in the string - to remove
  10636. if, just call String::trim() on the result.
  10637. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  10638. */
  10639. const String getAllSubText() const;
  10640. /** Returns all the sub-text of a named child element.
  10641. If there is a child element with the given tag name, this will return
  10642. all of its sub-text (by calling getAllSubText() on it). If there is
  10643. no such child element, this will return the default string passed-in.
  10644. @see getAllSubText
  10645. */
  10646. const String getChildElementAllSubText (const String& childTagName,
  10647. const String& defaultReturnValue) const;
  10648. /** Appends a section of text to this element.
  10649. @see isTextElement, getText, getAllSubText
  10650. */
  10651. void addTextElement (const String& text);
  10652. /** Removes all the text elements from this element.
  10653. @see isTextElement, getText, getAllSubText, addTextElement
  10654. */
  10655. void deleteAllTextElements() noexcept;
  10656. /** Creates a text element that can be added to a parent element.
  10657. */
  10658. static XmlElement* createTextElement (const String& text);
  10659. private:
  10660. struct XmlAttributeNode
  10661. {
  10662. XmlAttributeNode (const XmlAttributeNode& other) noexcept;
  10663. XmlAttributeNode (const String& name, const String& value) noexcept;
  10664. LinkedListPointer<XmlAttributeNode> nextListItem;
  10665. String name, value;
  10666. bool hasName (const String& name) const noexcept;
  10667. private:
  10668. XmlAttributeNode& operator= (const XmlAttributeNode&);
  10669. };
  10670. friend class XmlDocument;
  10671. friend class LinkedListPointer<XmlAttributeNode>;
  10672. friend class LinkedListPointer <XmlElement>;
  10673. friend class LinkedListPointer <XmlElement>::Appender;
  10674. LinkedListPointer <XmlElement> nextListItem;
  10675. LinkedListPointer <XmlElement> firstChildElement;
  10676. LinkedListPointer <XmlAttributeNode> attributes;
  10677. String tagName;
  10678. XmlElement (int) noexcept;
  10679. void copyChildrenAndAttributesFrom (const XmlElement& other);
  10680. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  10681. void getChildElementsAsArray (XmlElement**) const noexcept;
  10682. void reorderChildElements (XmlElement**, int) noexcept;
  10683. JUCE_LEAK_DETECTOR (XmlElement);
  10684. };
  10685. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  10686. /*** End of inlined file: juce_XmlElement.h ***/
  10687. /**
  10688. A set of named property values, which can be strings, integers, floating point, etc.
  10689. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  10690. to load and save types other than strings.
  10691. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  10692. messages and saves/loads the list from a file.
  10693. */
  10694. class JUCE_API PropertySet
  10695. {
  10696. public:
  10697. /** Creates an empty PropertySet.
  10698. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  10699. case-insensitive way
  10700. */
  10701. PropertySet (bool ignoreCaseOfKeyNames = false);
  10702. /** Creates a copy of another PropertySet.
  10703. */
  10704. PropertySet (const PropertySet& other);
  10705. /** Copies another PropertySet over this one.
  10706. */
  10707. PropertySet& operator= (const PropertySet& other);
  10708. /** Destructor. */
  10709. virtual ~PropertySet();
  10710. /** Returns one of the properties as a string.
  10711. If the value isn't found in this set, then this will look for it in a fallback
  10712. property set (if you've specified one with the setFallbackPropertySet() method),
  10713. and if it can't find one there, it'll return the default value passed-in.
  10714. @param keyName the name of the property to retrieve
  10715. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10716. */
  10717. const String getValue (const String& keyName,
  10718. const String& defaultReturnValue = String::empty) const noexcept;
  10719. /** Returns one of the properties as an integer.
  10720. If the value isn't found in this set, then this will look for it in a fallback
  10721. property set (if you've specified one with the setFallbackPropertySet() method),
  10722. and if it can't find one there, it'll return the default value passed-in.
  10723. @param keyName the name of the property to retrieve
  10724. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10725. */
  10726. int getIntValue (const String& keyName,
  10727. const int defaultReturnValue = 0) const noexcept;
  10728. /** Returns one of the properties as an double.
  10729. If the value isn't found in this set, then this will look for it in a fallback
  10730. property set (if you've specified one with the setFallbackPropertySet() method),
  10731. and if it can't find one there, it'll return the default value passed-in.
  10732. @param keyName the name of the property to retrieve
  10733. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10734. */
  10735. double getDoubleValue (const String& keyName,
  10736. const double defaultReturnValue = 0.0) const noexcept;
  10737. /** Returns one of the properties as an boolean.
  10738. The result will be true if the string found for this key name can be parsed as a non-zero
  10739. integer.
  10740. If the value isn't found in this set, then this will look for it in a fallback
  10741. property set (if you've specified one with the setFallbackPropertySet() method),
  10742. and if it can't find one there, it'll return the default value passed-in.
  10743. @param keyName the name of the property to retrieve
  10744. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10745. */
  10746. bool getBoolValue (const String& keyName,
  10747. const bool defaultReturnValue = false) const noexcept;
  10748. /** Returns one of the properties as an XML element.
  10749. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  10750. key isn't found, or if the entry contains an string that isn't valid XML.
  10751. If the value isn't found in this set, then this will look for it in a fallback
  10752. property set (if you've specified one with the setFallbackPropertySet() method),
  10753. and if it can't find one there, it'll return the default value passed-in.
  10754. @param keyName the name of the property to retrieve
  10755. */
  10756. XmlElement* getXmlValue (const String& keyName) const;
  10757. /** Sets a named property.
  10758. @param keyName the name of the property to set. (This mustn't be an empty string)
  10759. @param value the new value to set it to
  10760. */
  10761. void setValue (const String& keyName, const var& value);
  10762. /** Sets a named property to an XML element.
  10763. @param keyName the name of the property to set. (This mustn't be an empty string)
  10764. @param xml the new element to set it to. If this is zero, the value will be set to
  10765. an empty string
  10766. @see getXmlValue
  10767. */
  10768. void setValue (const String& keyName, const XmlElement* xml);
  10769. /** Deletes a property.
  10770. @param keyName the name of the property to delete. (This mustn't be an empty string)
  10771. */
  10772. void removeValue (const String& keyName);
  10773. /** Returns true if the properies include the given key. */
  10774. bool containsKey (const String& keyName) const noexcept;
  10775. /** Removes all values. */
  10776. void clear();
  10777. /** Returns the keys/value pair array containing all the properties. */
  10778. StringPairArray& getAllProperties() noexcept { return properties; }
  10779. /** Returns the lock used when reading or writing to this set */
  10780. const CriticalSection& getLock() const noexcept { return lock; }
  10781. /** Returns an XML element which encapsulates all the items in this property set.
  10782. The string parameter is the tag name that should be used for the node.
  10783. @see restoreFromXml
  10784. */
  10785. XmlElement* createXml (const String& nodeName) const;
  10786. /** Reloads a set of properties that were previously stored as XML.
  10787. The node passed in must have been created by the createXml() method.
  10788. @see createXml
  10789. */
  10790. void restoreFromXml (const XmlElement& xml);
  10791. /** Sets up a second PopertySet that will be used to look up any values that aren't
  10792. set in this one.
  10793. If you set this up to be a pointer to a second property set, then whenever one
  10794. of the getValue() methods fails to find an entry in this set, it will look up that
  10795. value in the fallback set, and if it finds it, it will return that.
  10796. Make sure that you don't delete the fallback set while it's still being used by
  10797. another set! To remove the fallback set, just call this method with a null pointer.
  10798. @see getFallbackPropertySet
  10799. */
  10800. void setFallbackPropertySet (PropertySet* fallbackProperties) noexcept;
  10801. /** Returns the fallback property set.
  10802. @see setFallbackPropertySet
  10803. */
  10804. PropertySet* getFallbackPropertySet() const noexcept { return fallbackProperties; }
  10805. protected:
  10806. /** Subclasses can override this to be told when one of the properies has been changed. */
  10807. virtual void propertyChanged();
  10808. private:
  10809. StringPairArray properties;
  10810. PropertySet* fallbackProperties;
  10811. CriticalSection lock;
  10812. bool ignoreCaseOfKeys;
  10813. JUCE_LEAK_DETECTOR (PropertySet);
  10814. };
  10815. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  10816. /*** End of inlined file: juce_PropertySet.h ***/
  10817. #endif
  10818. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10819. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  10820. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10821. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10822. /**
  10823. Holds a list of objects derived from ReferenceCountedObject.
  10824. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  10825. and takes care of incrementing and decrementing their ref counts when they
  10826. are added and removed from the array.
  10827. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  10828. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  10829. @see Array, OwnedArray, StringArray
  10830. */
  10831. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  10832. class ReferenceCountedArray
  10833. {
  10834. public:
  10835. typedef ReferenceCountedObjectPtr<ObjectClass> ObjectClassPtr;
  10836. /** Creates an empty array.
  10837. @see ReferenceCountedObject, Array, OwnedArray
  10838. */
  10839. ReferenceCountedArray() noexcept
  10840. : numUsed (0)
  10841. {
  10842. }
  10843. /** Creates a copy of another array */
  10844. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) noexcept
  10845. {
  10846. const ScopedLockType lock (other.getLock());
  10847. numUsed = other.numUsed;
  10848. data.setAllocatedSize (numUsed);
  10849. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  10850. for (int i = numUsed; --i >= 0;)
  10851. if (data.elements[i] != nullptr)
  10852. data.elements[i]->incReferenceCount();
  10853. }
  10854. /** Copies another array into this one.
  10855. Any existing objects in this array will first be released.
  10856. */
  10857. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) noexcept
  10858. {
  10859. if (this != &other)
  10860. {
  10861. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  10862. swapWithArray (otherCopy);
  10863. }
  10864. return *this;
  10865. }
  10866. /** Destructor.
  10867. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  10868. */
  10869. ~ReferenceCountedArray()
  10870. {
  10871. clear();
  10872. }
  10873. /** Removes all objects from the array.
  10874. Any objects in the array that are not referenced from elsewhere will be deleted.
  10875. */
  10876. void clear()
  10877. {
  10878. const ScopedLockType lock (getLock());
  10879. while (numUsed > 0)
  10880. if (data.elements [--numUsed] != nullptr)
  10881. data.elements [numUsed]->decReferenceCount();
  10882. jassert (numUsed == 0);
  10883. data.setAllocatedSize (0);
  10884. }
  10885. /** Returns the current number of objects in the array. */
  10886. inline int size() const noexcept
  10887. {
  10888. return numUsed;
  10889. }
  10890. /** Returns a pointer to the object at this index in the array.
  10891. If the index is out-of-range, this will return a null pointer, (and
  10892. it could be null anyway, because it's ok for the array to hold null
  10893. pointers as well as objects).
  10894. @see getUnchecked
  10895. */
  10896. inline const ObjectClassPtr operator[] (const int index) const noexcept
  10897. {
  10898. const ScopedLockType lock (getLock());
  10899. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  10900. : static_cast <ObjectClass*> (nullptr);
  10901. }
  10902. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  10903. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  10904. it can be used when you're sure the index if always going to be legal.
  10905. */
  10906. inline const ObjectClassPtr getUnchecked (const int index) const noexcept
  10907. {
  10908. const ScopedLockType lock (getLock());
  10909. jassert (isPositiveAndBelow (index, numUsed));
  10910. return data.elements [index];
  10911. }
  10912. /** Returns a pointer to the first object in the array.
  10913. This will return a null pointer if the array's empty.
  10914. @see getLast
  10915. */
  10916. inline const ObjectClassPtr getFirst() const noexcept
  10917. {
  10918. const ScopedLockType lock (getLock());
  10919. return numUsed > 0 ? data.elements [0]
  10920. : static_cast <ObjectClass*> (nullptr);
  10921. }
  10922. /** Returns a pointer to the last object in the array.
  10923. This will return a null pointer if the array's empty.
  10924. @see getFirst
  10925. */
  10926. inline const ObjectClassPtr getLast() const noexcept
  10927. {
  10928. const ScopedLockType lock (getLock());
  10929. return numUsed > 0 ? data.elements [numUsed - 1]
  10930. : static_cast <ObjectClass*> (nullptr);
  10931. }
  10932. /** Returns a pointer to the first element in the array.
  10933. This method is provided for compatibility with standard C++ iteration mechanisms.
  10934. */
  10935. inline ObjectClass** begin() const noexcept
  10936. {
  10937. return data.elements;
  10938. }
  10939. /** Returns a pointer to the element which follows the last element in the array.
  10940. This method is provided for compatibility with standard C++ iteration mechanisms.
  10941. */
  10942. inline ObjectClass** end() const noexcept
  10943. {
  10944. return data.elements + numUsed;
  10945. }
  10946. /** Finds the index of the first occurrence of an object in the array.
  10947. @param objectToLookFor the object to look for
  10948. @returns the index at which the object was found, or -1 if it's not found
  10949. */
  10950. int indexOf (const ObjectClass* const objectToLookFor) const noexcept
  10951. {
  10952. const ScopedLockType lock (getLock());
  10953. ObjectClass** e = data.elements.getData();
  10954. ObjectClass** const end = e + numUsed;
  10955. while (e != end)
  10956. {
  10957. if (objectToLookFor == *e)
  10958. return static_cast <int> (e - data.elements.getData());
  10959. ++e;
  10960. }
  10961. return -1;
  10962. }
  10963. /** Returns true if the array contains a specified object.
  10964. @param objectToLookFor the object to look for
  10965. @returns true if the object is in the array
  10966. */
  10967. bool contains (const ObjectClass* const objectToLookFor) const noexcept
  10968. {
  10969. const ScopedLockType lock (getLock());
  10970. ObjectClass** e = data.elements.getData();
  10971. ObjectClass** const end = e + numUsed;
  10972. while (e != end)
  10973. {
  10974. if (objectToLookFor == *e)
  10975. return true;
  10976. ++e;
  10977. }
  10978. return false;
  10979. }
  10980. /** Appends a new object to the end of the array.
  10981. This will increase the new object's reference count.
  10982. @param newObject the new object to add to the array
  10983. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  10984. */
  10985. void add (ObjectClass* const newObject) noexcept
  10986. {
  10987. const ScopedLockType lock (getLock());
  10988. data.ensureAllocatedSize (numUsed + 1);
  10989. data.elements [numUsed++] = newObject;
  10990. if (newObject != nullptr)
  10991. newObject->incReferenceCount();
  10992. }
  10993. /** Inserts a new object into the array at the given index.
  10994. If the index is less than 0 or greater than the size of the array, the
  10995. element will be added to the end of the array.
  10996. Otherwise, it will be inserted into the array, moving all the later elements
  10997. along to make room.
  10998. This will increase the new object's reference count.
  10999. @param indexToInsertAt the index at which the new element should be inserted
  11000. @param newObject the new object to add to the array
  11001. @see add, addSorted, addIfNotAlreadyThere, set
  11002. */
  11003. void insert (int indexToInsertAt,
  11004. ObjectClass* const newObject) noexcept
  11005. {
  11006. if (indexToInsertAt >= 0)
  11007. {
  11008. const ScopedLockType lock (getLock());
  11009. if (indexToInsertAt > numUsed)
  11010. indexToInsertAt = numUsed;
  11011. data.ensureAllocatedSize (numUsed + 1);
  11012. ObjectClass** const e = data.elements + indexToInsertAt;
  11013. const int numToMove = numUsed - indexToInsertAt;
  11014. if (numToMove > 0)
  11015. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  11016. *e = newObject;
  11017. if (newObject != nullptr)
  11018. newObject->incReferenceCount();
  11019. ++numUsed;
  11020. }
  11021. else
  11022. {
  11023. add (newObject);
  11024. }
  11025. }
  11026. /** Appends a new object at the end of the array as long as the array doesn't
  11027. already contain it.
  11028. If the array already contains a matching object, nothing will be done.
  11029. @param newObject the new object to add to the array
  11030. */
  11031. void addIfNotAlreadyThere (ObjectClass* const newObject) noexcept
  11032. {
  11033. const ScopedLockType lock (getLock());
  11034. if (! contains (newObject))
  11035. add (newObject);
  11036. }
  11037. /** Replaces an object in the array with a different one.
  11038. If the index is less than zero, this method does nothing.
  11039. If the index is beyond the end of the array, the new object is added to the end of the array.
  11040. The object being added has its reference count increased, and if it's replacing
  11041. another object, then that one has its reference count decreased, and may be deleted.
  11042. @param indexToChange the index whose value you want to change
  11043. @param newObject the new value to set for this index.
  11044. @see add, insert, remove
  11045. */
  11046. void set (const int indexToChange,
  11047. ObjectClass* const newObject)
  11048. {
  11049. if (indexToChange >= 0)
  11050. {
  11051. const ScopedLockType lock (getLock());
  11052. if (newObject != nullptr)
  11053. newObject->incReferenceCount();
  11054. if (indexToChange < numUsed)
  11055. {
  11056. if (data.elements [indexToChange] != nullptr)
  11057. data.elements [indexToChange]->decReferenceCount();
  11058. data.elements [indexToChange] = newObject;
  11059. }
  11060. else
  11061. {
  11062. data.ensureAllocatedSize (numUsed + 1);
  11063. data.elements [numUsed++] = newObject;
  11064. }
  11065. }
  11066. }
  11067. /** Adds elements from another array to the end of this array.
  11068. @param arrayToAddFrom the array from which to copy the elements
  11069. @param startIndex the first element of the other array to start copying from
  11070. @param numElementsToAdd how many elements to add from the other array. If this
  11071. value is negative or greater than the number of available elements,
  11072. all available elements will be copied.
  11073. @see add
  11074. */
  11075. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  11076. int startIndex = 0,
  11077. int numElementsToAdd = -1) noexcept
  11078. {
  11079. const ScopedLockType lock1 (arrayToAddFrom.getLock());
  11080. {
  11081. const ScopedLockType lock2 (getLock());
  11082. if (startIndex < 0)
  11083. {
  11084. jassertfalse;
  11085. startIndex = 0;
  11086. }
  11087. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  11088. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  11089. if (numElementsToAdd > 0)
  11090. {
  11091. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  11092. while (--numElementsToAdd >= 0)
  11093. add (arrayToAddFrom.getUnchecked (startIndex++));
  11094. }
  11095. }
  11096. }
  11097. /** Inserts a new object into the array assuming that the array is sorted.
  11098. This will use a comparator to find the position at which the new object
  11099. should go. If the array isn't sorted, the behaviour of this
  11100. method will be unpredictable.
  11101. @param comparator the comparator object to use to compare the elements - see the
  11102. sort() method for details about this object's form
  11103. @param newObject the new object to insert to the array
  11104. @returns the index at which the new object was added
  11105. @see add, sort
  11106. */
  11107. template <class ElementComparator>
  11108. int addSorted (ElementComparator& comparator, ObjectClass* newObject) noexcept
  11109. {
  11110. const ScopedLockType lock (getLock());
  11111. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  11112. insert (index, newObject);
  11113. return index;
  11114. }
  11115. /** Inserts or replaces an object in the array, assuming it is sorted.
  11116. This is similar to addSorted, but if a matching element already exists, then it will be
  11117. replaced by the new one, rather than the new one being added as well.
  11118. */
  11119. template <class ElementComparator>
  11120. void addOrReplaceSorted (ElementComparator& comparator,
  11121. ObjectClass* newObject) noexcept
  11122. {
  11123. const ScopedLockType lock (getLock());
  11124. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  11125. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  11126. set (index - 1, newObject); // replace an existing object that matches
  11127. else
  11128. insert (index, newObject); // no match, so insert the new one
  11129. }
  11130. /** Removes an object from the array.
  11131. This will remove the object at a given index and move back all the
  11132. subsequent objects to close the gap.
  11133. If the index passed in is out-of-range, nothing will happen.
  11134. The object that is removed will have its reference count decreased,
  11135. and may be deleted if not referenced from elsewhere.
  11136. @param indexToRemove the index of the element to remove
  11137. @see removeObject, removeRange
  11138. */
  11139. void remove (const int indexToRemove)
  11140. {
  11141. const ScopedLockType lock (getLock());
  11142. if (isPositiveAndBelow (indexToRemove, numUsed))
  11143. {
  11144. ObjectClass** const e = data.elements + indexToRemove;
  11145. if (*e != nullptr)
  11146. (*e)->decReferenceCount();
  11147. --numUsed;
  11148. const int numberToShift = numUsed - indexToRemove;
  11149. if (numberToShift > 0)
  11150. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  11151. if ((numUsed << 1) < data.numAllocated)
  11152. minimiseStorageOverheads();
  11153. }
  11154. }
  11155. /** Removes and returns an object from the array.
  11156. This will remove the object at a given index and return it, moving back all
  11157. the subsequent objects to close the gap. If the index passed in is out-of-range,
  11158. nothing will happen and a null pointer will be returned.
  11159. @param indexToRemove the index of the element to remove
  11160. @see remove, removeObject, removeRange
  11161. */
  11162. const ObjectClassPtr removeAndReturn (const int indexToRemove)
  11163. {
  11164. ObjectClassPtr removedItem;
  11165. const ScopedLockType lock (getLock());
  11166. if (isPositiveAndBelow (indexToRemove, numUsed))
  11167. {
  11168. ObjectClass** const e = data.elements + indexToRemove;
  11169. if (*e != nullptr)
  11170. {
  11171. removedItem = *e;
  11172. (*e)->decReferenceCount();
  11173. }
  11174. --numUsed;
  11175. const int numberToShift = numUsed - indexToRemove;
  11176. if (numberToShift > 0)
  11177. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  11178. if ((numUsed << 1) < data.numAllocated)
  11179. minimiseStorageOverheads();
  11180. }
  11181. return removedItem;
  11182. }
  11183. /** Removes the first occurrence of a specified object from the array.
  11184. If the item isn't found, no action is taken. If it is found, it is
  11185. removed and has its reference count decreased.
  11186. @param objectToRemove the object to try to remove
  11187. @see remove, removeRange
  11188. */
  11189. void removeObject (ObjectClass* const objectToRemove)
  11190. {
  11191. const ScopedLockType lock (getLock());
  11192. remove (indexOf (objectToRemove));
  11193. }
  11194. /** Removes a range of objects from the array.
  11195. This will remove a set of objects, starting from the given index,
  11196. and move any subsequent elements down to close the gap.
  11197. If the range extends beyond the bounds of the array, it will
  11198. be safely clipped to the size of the array.
  11199. The objects that are removed will have their reference counts decreased,
  11200. and may be deleted if not referenced from elsewhere.
  11201. @param startIndex the index of the first object to remove
  11202. @param numberToRemove how many objects should be removed
  11203. @see remove, removeObject
  11204. */
  11205. void removeRange (const int startIndex,
  11206. const int numberToRemove)
  11207. {
  11208. const ScopedLockType lock (getLock());
  11209. const int start = jlimit (0, numUsed, startIndex);
  11210. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  11211. if (end > start)
  11212. {
  11213. int i;
  11214. for (i = start; i < end; ++i)
  11215. {
  11216. if (data.elements[i] != nullptr)
  11217. {
  11218. data.elements[i]->decReferenceCount();
  11219. data.elements[i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer)
  11220. }
  11221. }
  11222. const int rangeSize = end - start;
  11223. ObjectClass** e = data.elements + start;
  11224. i = numUsed - end;
  11225. numUsed -= rangeSize;
  11226. while (--i >= 0)
  11227. {
  11228. *e = e [rangeSize];
  11229. ++e;
  11230. }
  11231. if ((numUsed << 1) < data.numAllocated)
  11232. minimiseStorageOverheads();
  11233. }
  11234. }
  11235. /** Removes the last n objects from the array.
  11236. The objects that are removed will have their reference counts decreased,
  11237. and may be deleted if not referenced from elsewhere.
  11238. @param howManyToRemove how many objects to remove from the end of the array
  11239. @see remove, removeObject, removeRange
  11240. */
  11241. void removeLast (int howManyToRemove = 1)
  11242. {
  11243. const ScopedLockType lock (getLock());
  11244. if (howManyToRemove > numUsed)
  11245. howManyToRemove = numUsed;
  11246. while (--howManyToRemove >= 0)
  11247. remove (numUsed - 1);
  11248. }
  11249. /** Swaps a pair of objects in the array.
  11250. If either of the indexes passed in is out-of-range, nothing will happen,
  11251. otherwise the two objects at these positions will be exchanged.
  11252. */
  11253. void swap (const int index1,
  11254. const int index2) noexcept
  11255. {
  11256. const ScopedLockType lock (getLock());
  11257. if (isPositiveAndBelow (index1, numUsed)
  11258. && isPositiveAndBelow (index2, numUsed))
  11259. {
  11260. std::swap (data.elements [index1],
  11261. data.elements [index2]);
  11262. }
  11263. }
  11264. /** Moves one of the objects to a different position.
  11265. This will move the object to a specified index, shuffling along
  11266. any intervening elements as required.
  11267. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  11268. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  11269. @param currentIndex the index of the object to be moved. If this isn't a
  11270. valid index, then nothing will be done
  11271. @param newIndex the index at which you'd like this object to end up. If this
  11272. is less than zero, it will be moved to the end of the array
  11273. */
  11274. void move (const int currentIndex,
  11275. int newIndex) noexcept
  11276. {
  11277. if (currentIndex != newIndex)
  11278. {
  11279. const ScopedLockType lock (getLock());
  11280. if (isPositiveAndBelow (currentIndex, numUsed))
  11281. {
  11282. if (! isPositiveAndBelow (newIndex, numUsed))
  11283. newIndex = numUsed - 1;
  11284. ObjectClass* const value = data.elements [currentIndex];
  11285. if (newIndex > currentIndex)
  11286. {
  11287. memmove (data.elements + currentIndex,
  11288. data.elements + currentIndex + 1,
  11289. (newIndex - currentIndex) * sizeof (ObjectClass*));
  11290. }
  11291. else
  11292. {
  11293. memmove (data.elements + newIndex + 1,
  11294. data.elements + newIndex,
  11295. (currentIndex - newIndex) * sizeof (ObjectClass*));
  11296. }
  11297. data.elements [newIndex] = value;
  11298. }
  11299. }
  11300. }
  11301. /** This swaps the contents of this array with those of another array.
  11302. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  11303. because it just swaps their internal pointers.
  11304. */
  11305. void swapWithArray (ReferenceCountedArray& otherArray) noexcept
  11306. {
  11307. const ScopedLockType lock1 (getLock());
  11308. const ScopedLockType lock2 (otherArray.getLock());
  11309. data.swapWith (otherArray.data);
  11310. std::swap (numUsed, otherArray.numUsed);
  11311. }
  11312. /** Compares this array to another one.
  11313. @returns true only if the other array contains the same objects in the same order
  11314. */
  11315. bool operator== (const ReferenceCountedArray& other) const noexcept
  11316. {
  11317. const ScopedLockType lock2 (other.getLock());
  11318. const ScopedLockType lock1 (getLock());
  11319. if (numUsed != other.numUsed)
  11320. return false;
  11321. for (int i = numUsed; --i >= 0;)
  11322. if (data.elements [i] != other.data.elements [i])
  11323. return false;
  11324. return true;
  11325. }
  11326. /** Compares this array to another one.
  11327. @see operator==
  11328. */
  11329. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const noexcept
  11330. {
  11331. return ! operator== (other);
  11332. }
  11333. /** Sorts the elements in the array.
  11334. This will use a comparator object to sort the elements into order. The object
  11335. passed must have a method of the form:
  11336. @code
  11337. int compareElements (ElementType first, ElementType second);
  11338. @endcode
  11339. ..and this method must return:
  11340. - a value of < 0 if the first comes before the second
  11341. - a value of 0 if the two objects are equivalent
  11342. - a value of > 0 if the second comes before the first
  11343. To improve performance, the compareElements() method can be declared as static or const.
  11344. @param comparator the comparator to use for comparing elements.
  11345. @param retainOrderOfEquivalentItems if this is true, then items
  11346. which the comparator says are equivalent will be
  11347. kept in the order in which they currently appear
  11348. in the array. This is slower to perform, but may
  11349. be important in some cases. If it's false, a faster
  11350. algorithm is used, but equivalent elements may be
  11351. rearranged.
  11352. @see sortArray
  11353. */
  11354. template <class ElementComparator>
  11355. void sort (ElementComparator& comparator,
  11356. const bool retainOrderOfEquivalentItems = false) const noexcept
  11357. {
  11358. (void) comparator; // if you pass in an object with a static compareElements() method, this
  11359. // avoids getting warning messages about the parameter being unused
  11360. const ScopedLockType lock (getLock());
  11361. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  11362. }
  11363. /** Reduces the amount of storage being used by the array.
  11364. Arrays typically allocate slightly more storage than they need, and after
  11365. removing elements, they may have quite a lot of unused space allocated.
  11366. This method will reduce the amount of allocated storage to a minimum.
  11367. */
  11368. void minimiseStorageOverheads() noexcept
  11369. {
  11370. const ScopedLockType lock (getLock());
  11371. data.shrinkToNoMoreThan (numUsed);
  11372. }
  11373. /** Returns the CriticalSection that locks this array.
  11374. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  11375. an object of ScopedLockType as an RAII lock for it.
  11376. */
  11377. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  11378. /** Returns the type of scoped lock to use for locking this array */
  11379. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  11380. private:
  11381. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  11382. int numUsed;
  11383. };
  11384. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  11385. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  11386. #endif
  11387. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11388. /*** Start of inlined file: juce_ScopedValueSetter.h ***/
  11389. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11390. #define __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11391. /**
  11392. Helper class providing an RAII-based mechanism for temporarily setting and
  11393. then re-setting a value.
  11394. E.g. @code
  11395. int x = 1;
  11396. {
  11397. ScopedValueSetter setter (x, 2);
  11398. // x is now 2
  11399. }
  11400. // x is now 1 again
  11401. {
  11402. ScopedValueSetter setter (x, 3, 4);
  11403. // x is now 3
  11404. }
  11405. // x is now 4
  11406. @endcode
  11407. */
  11408. template <typename ValueType>
  11409. class ScopedValueSetter
  11410. {
  11411. public:
  11412. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  11413. given new value, and will then reset it to its original value when this object is deleted.
  11414. */
  11415. ScopedValueSetter (ValueType& valueToSet,
  11416. const ValueType& newValue)
  11417. : value (valueToSet),
  11418. originalValue (valueToSet)
  11419. {
  11420. valueToSet = newValue;
  11421. }
  11422. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  11423. given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
  11424. */
  11425. ScopedValueSetter (ValueType& valueToSet,
  11426. const ValueType& newValue,
  11427. const ValueType& valueWhenDeleted)
  11428. : value (valueToSet),
  11429. originalValue (valueWhenDeleted)
  11430. {
  11431. valueToSet = newValue;
  11432. }
  11433. ~ScopedValueSetter()
  11434. {
  11435. value = originalValue;
  11436. }
  11437. private:
  11438. ValueType& value;
  11439. const ValueType originalValue;
  11440. JUCE_DECLARE_NON_COPYABLE (ScopedValueSetter);
  11441. };
  11442. #endif // __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11443. /*** End of inlined file: juce_ScopedValueSetter.h ***/
  11444. #endif
  11445. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  11446. /*** Start of inlined file: juce_SortedSet.h ***/
  11447. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  11448. #define __JUCE_SORTEDSET_JUCEHEADER__
  11449. #if JUCE_MSVC
  11450. #pragma warning (push)
  11451. #pragma warning (disable: 4512)
  11452. #endif
  11453. /**
  11454. Holds a set of unique primitive objects, such as ints or doubles.
  11455. A set can only hold one item with a given value, so if for example it's a
  11456. set of integers, attempting to add the same integer twice will do nothing
  11457. the second time.
  11458. Internally, the list of items is kept sorted (which means that whatever
  11459. kind of primitive type is used must support the ==, <, >, <= and >= operators
  11460. to determine the order), and searching the set for known values is very fast
  11461. because it uses a binary-chop method.
  11462. Note that if you're using a class or struct as the element type, it must be
  11463. capable of being copied or moved with a straightforward memcpy, rather than
  11464. needing construction and destruction code.
  11465. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  11466. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  11467. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  11468. */
  11469. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  11470. class SortedSet
  11471. {
  11472. public:
  11473. /** Creates an empty set. */
  11474. SortedSet() noexcept
  11475. : numUsed (0)
  11476. {
  11477. }
  11478. /** Creates a copy of another set.
  11479. @param other the set to copy
  11480. */
  11481. SortedSet (const SortedSet& other) noexcept
  11482. {
  11483. const ScopedLockType lock (other.getLock());
  11484. numUsed = other.numUsed;
  11485. data.setAllocatedSize (other.numUsed);
  11486. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  11487. }
  11488. /** Destructor. */
  11489. ~SortedSet() noexcept
  11490. {
  11491. }
  11492. /** Copies another set over this one.
  11493. @param other the set to copy
  11494. */
  11495. SortedSet& operator= (const SortedSet& other) noexcept
  11496. {
  11497. if (this != &other)
  11498. {
  11499. const ScopedLockType lock1 (other.getLock());
  11500. const ScopedLockType lock2 (getLock());
  11501. data.ensureAllocatedSize (other.size());
  11502. numUsed = other.numUsed;
  11503. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  11504. minimiseStorageOverheads();
  11505. }
  11506. return *this;
  11507. }
  11508. /** Compares this set to another one.
  11509. Two sets are considered equal if they both contain the same set of
  11510. elements.
  11511. @param other the other set to compare with
  11512. */
  11513. bool operator== (const SortedSet<ElementType>& other) const noexcept
  11514. {
  11515. const ScopedLockType lock (getLock());
  11516. if (numUsed != other.numUsed)
  11517. return false;
  11518. for (int i = numUsed; --i >= 0;)
  11519. if (data.elements[i] != other.data.elements[i])
  11520. return false;
  11521. return true;
  11522. }
  11523. /** Compares this set to another one.
  11524. Two sets are considered equal if they both contain the same set of
  11525. elements.
  11526. @param other the other set to compare with
  11527. */
  11528. bool operator!= (const SortedSet<ElementType>& other) const noexcept
  11529. {
  11530. return ! operator== (other);
  11531. }
  11532. /** Removes all elements from the set.
  11533. This will remove all the elements, and free any storage that the set is
  11534. using. To clear it without freeing the storage, use the clearQuick()
  11535. method instead.
  11536. @see clearQuick
  11537. */
  11538. void clear() noexcept
  11539. {
  11540. const ScopedLockType lock (getLock());
  11541. data.setAllocatedSize (0);
  11542. numUsed = 0;
  11543. }
  11544. /** Removes all elements from the set without freeing the array's allocated storage.
  11545. @see clear
  11546. */
  11547. void clearQuick() noexcept
  11548. {
  11549. const ScopedLockType lock (getLock());
  11550. numUsed = 0;
  11551. }
  11552. /** Returns the current number of elements in the set.
  11553. */
  11554. inline int size() const noexcept
  11555. {
  11556. return numUsed;
  11557. }
  11558. /** Returns one of the elements in the set.
  11559. If the index passed in is beyond the range of valid elements, this
  11560. will return zero.
  11561. If you're certain that the index will always be a valid element, you
  11562. can call getUnchecked() instead, which is faster.
  11563. @param index the index of the element being requested (0 is the first element in the set)
  11564. @see getUnchecked, getFirst, getLast
  11565. */
  11566. inline ElementType operator[] (const int index) const noexcept
  11567. {
  11568. const ScopedLockType lock (getLock());
  11569. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  11570. : ElementType();
  11571. }
  11572. /** Returns one of the elements in the set, without checking the index passed in.
  11573. Unlike the operator[] method, this will try to return an element without
  11574. checking that the index is within the bounds of the set, so should only
  11575. be used when you're confident that it will always be a valid index.
  11576. @param index the index of the element being requested (0 is the first element in the set)
  11577. @see operator[], getFirst, getLast
  11578. */
  11579. inline ElementType getUnchecked (const int index) const noexcept
  11580. {
  11581. const ScopedLockType lock (getLock());
  11582. jassert (isPositiveAndBelow (index, numUsed));
  11583. return data.elements [index];
  11584. }
  11585. /** Returns the first element in the set, or 0 if the set is empty.
  11586. @see operator[], getUnchecked, getLast
  11587. */
  11588. inline ElementType getFirst() const noexcept
  11589. {
  11590. const ScopedLockType lock (getLock());
  11591. return numUsed > 0 ? data.elements [0] : ElementType();
  11592. }
  11593. /** Returns the last element in the set, or 0 if the set is empty.
  11594. @see operator[], getUnchecked, getFirst
  11595. */
  11596. inline ElementType getLast() const noexcept
  11597. {
  11598. const ScopedLockType lock (getLock());
  11599. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  11600. }
  11601. /** Returns a pointer to the first element in the set.
  11602. This method is provided for compatibility with standard C++ iteration mechanisms.
  11603. */
  11604. inline ElementType* begin() const noexcept
  11605. {
  11606. return data.elements;
  11607. }
  11608. /** Returns a pointer to the element which follows the last element in the set.
  11609. This method is provided for compatibility with standard C++ iteration mechanisms.
  11610. */
  11611. inline ElementType* end() const noexcept
  11612. {
  11613. return data.elements + numUsed;
  11614. }
  11615. /** Finds the index of the first element which matches the value passed in.
  11616. This will search the set for the given object, and return the index
  11617. of its first occurrence. If the object isn't found, the method will return -1.
  11618. @param elementToLookFor the value or object to look for
  11619. @returns the index of the object, or -1 if it's not found
  11620. */
  11621. int indexOf (const ElementType elementToLookFor) const noexcept
  11622. {
  11623. const ScopedLockType lock (getLock());
  11624. int start = 0;
  11625. int end = numUsed;
  11626. for (;;)
  11627. {
  11628. if (start >= end)
  11629. {
  11630. return -1;
  11631. }
  11632. else if (elementToLookFor == data.elements [start])
  11633. {
  11634. return start;
  11635. }
  11636. else
  11637. {
  11638. const int halfway = (start + end) >> 1;
  11639. if (halfway == start)
  11640. return -1;
  11641. else if (elementToLookFor >= data.elements [halfway])
  11642. start = halfway;
  11643. else
  11644. end = halfway;
  11645. }
  11646. }
  11647. }
  11648. /** Returns true if the set contains at least one occurrence of an object.
  11649. @param elementToLookFor the value or object to look for
  11650. @returns true if the item is found
  11651. */
  11652. bool contains (const ElementType elementToLookFor) const noexcept
  11653. {
  11654. const ScopedLockType lock (getLock());
  11655. int start = 0;
  11656. int end = numUsed;
  11657. for (;;)
  11658. {
  11659. if (start >= end)
  11660. {
  11661. return false;
  11662. }
  11663. else if (elementToLookFor == data.elements [start])
  11664. {
  11665. return true;
  11666. }
  11667. else
  11668. {
  11669. const int halfway = (start + end) >> 1;
  11670. if (halfway == start)
  11671. return false;
  11672. else if (elementToLookFor >= data.elements [halfway])
  11673. start = halfway;
  11674. else
  11675. end = halfway;
  11676. }
  11677. }
  11678. }
  11679. /** Adds a new element to the set, (as long as it's not already in there).
  11680. @param newElement the new object to add to the set
  11681. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  11682. */
  11683. void add (const ElementType newElement) noexcept
  11684. {
  11685. const ScopedLockType lock (getLock());
  11686. int start = 0;
  11687. int end = numUsed;
  11688. for (;;)
  11689. {
  11690. if (start >= end)
  11691. {
  11692. jassert (start <= end);
  11693. insertInternal (start, newElement);
  11694. break;
  11695. }
  11696. else if (newElement == data.elements [start])
  11697. {
  11698. break;
  11699. }
  11700. else
  11701. {
  11702. const int halfway = (start + end) >> 1;
  11703. if (halfway == start)
  11704. {
  11705. if (newElement >= data.elements [halfway])
  11706. insertInternal (start + 1, newElement);
  11707. else
  11708. insertInternal (start, newElement);
  11709. break;
  11710. }
  11711. else if (newElement >= data.elements [halfway])
  11712. start = halfway;
  11713. else
  11714. end = halfway;
  11715. }
  11716. }
  11717. }
  11718. /** Adds elements from an array to this set.
  11719. @param elementsToAdd the array of elements to add
  11720. @param numElementsToAdd how many elements are in this other array
  11721. @see add
  11722. */
  11723. void addArray (const ElementType* elementsToAdd,
  11724. int numElementsToAdd) noexcept
  11725. {
  11726. const ScopedLockType lock (getLock());
  11727. while (--numElementsToAdd >= 0)
  11728. add (*elementsToAdd++);
  11729. }
  11730. /** Adds elements from another set to this one.
  11731. @param setToAddFrom the set from which to copy the elements
  11732. @param startIndex the first element of the other set to start copying from
  11733. @param numElementsToAdd how many elements to add from the other set. If this
  11734. value is negative or greater than the number of available elements,
  11735. all available elements will be copied.
  11736. @see add
  11737. */
  11738. template <class OtherSetType>
  11739. void addSet (const OtherSetType& setToAddFrom,
  11740. int startIndex = 0,
  11741. int numElementsToAdd = -1) noexcept
  11742. {
  11743. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  11744. {
  11745. const ScopedLockType lock2 (getLock());
  11746. jassert (this != &setToAddFrom);
  11747. if (this != &setToAddFrom)
  11748. {
  11749. if (startIndex < 0)
  11750. {
  11751. jassertfalse;
  11752. startIndex = 0;
  11753. }
  11754. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  11755. numElementsToAdd = setToAddFrom.size() - startIndex;
  11756. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  11757. }
  11758. }
  11759. }
  11760. /** Removes an element from the set.
  11761. This will remove the element at a given index.
  11762. If the index passed in is out-of-range, nothing will happen.
  11763. @param indexToRemove the index of the element to remove
  11764. @returns the element that has been removed
  11765. @see removeValue, removeRange
  11766. */
  11767. ElementType remove (const int indexToRemove) noexcept
  11768. {
  11769. const ScopedLockType lock (getLock());
  11770. if (isPositiveAndBelow (indexToRemove, numUsed))
  11771. {
  11772. --numUsed;
  11773. ElementType* const e = data.elements + indexToRemove;
  11774. ElementType const removed = *e;
  11775. const int numberToShift = numUsed - indexToRemove;
  11776. if (numberToShift > 0)
  11777. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  11778. if ((numUsed << 1) < data.numAllocated)
  11779. minimiseStorageOverheads();
  11780. return removed;
  11781. }
  11782. return ElementType();
  11783. }
  11784. /** Removes an item from the set.
  11785. This will remove the given element from the set, if it's there.
  11786. @param valueToRemove the object to try to remove
  11787. @see remove, removeRange
  11788. */
  11789. void removeValue (const ElementType valueToRemove) noexcept
  11790. {
  11791. const ScopedLockType lock (getLock());
  11792. remove (indexOf (valueToRemove));
  11793. }
  11794. /** Removes any elements which are also in another set.
  11795. @param otherSet the other set in which to look for elements to remove
  11796. @see removeValuesNotIn, remove, removeValue, removeRange
  11797. */
  11798. template <class OtherSetType>
  11799. void removeValuesIn (const OtherSetType& otherSet) noexcept
  11800. {
  11801. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11802. const ScopedLockType lock2 (getLock());
  11803. if (this == &otherSet)
  11804. {
  11805. clear();
  11806. }
  11807. else
  11808. {
  11809. if (otherSet.size() > 0)
  11810. {
  11811. for (int i = numUsed; --i >= 0;)
  11812. if (otherSet.contains (data.elements [i]))
  11813. remove (i);
  11814. }
  11815. }
  11816. }
  11817. /** Removes any elements which are not found in another set.
  11818. Only elements which occur in this other set will be retained.
  11819. @param otherSet the set in which to look for elements NOT to remove
  11820. @see removeValuesIn, remove, removeValue, removeRange
  11821. */
  11822. template <class OtherSetType>
  11823. void removeValuesNotIn (const OtherSetType& otherSet) noexcept
  11824. {
  11825. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11826. const ScopedLockType lock2 (getLock());
  11827. if (this != &otherSet)
  11828. {
  11829. if (otherSet.size() <= 0)
  11830. {
  11831. clear();
  11832. }
  11833. else
  11834. {
  11835. for (int i = numUsed; --i >= 0;)
  11836. if (! otherSet.contains (data.elements [i]))
  11837. remove (i);
  11838. }
  11839. }
  11840. }
  11841. /** Reduces the amount of storage being used by the set.
  11842. Sets typically allocate slightly more storage than they need, and after
  11843. removing elements, they may have quite a lot of unused space allocated.
  11844. This method will reduce the amount of allocated storage to a minimum.
  11845. */
  11846. void minimiseStorageOverheads() noexcept
  11847. {
  11848. const ScopedLockType lock (getLock());
  11849. data.shrinkToNoMoreThan (numUsed);
  11850. }
  11851. /** Returns the CriticalSection that locks this array.
  11852. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  11853. an object of ScopedLockType as an RAII lock for it.
  11854. */
  11855. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  11856. /** Returns the type of scoped lock to use for locking this array */
  11857. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  11858. private:
  11859. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  11860. int numUsed;
  11861. void insertInternal (const int indexToInsertAt, const ElementType newElement) noexcept
  11862. {
  11863. data.ensureAllocatedSize (numUsed + 1);
  11864. ElementType* const insertPos = data.elements + indexToInsertAt;
  11865. const int numberToMove = numUsed - indexToInsertAt;
  11866. if (numberToMove > 0)
  11867. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  11868. *insertPos = newElement;
  11869. ++numUsed;
  11870. }
  11871. };
  11872. #if JUCE_MSVC
  11873. #pragma warning (pop)
  11874. #endif
  11875. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  11876. /*** End of inlined file: juce_SortedSet.h ***/
  11877. #endif
  11878. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11879. /*** Start of inlined file: juce_SparseSet.h ***/
  11880. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11881. #define __JUCE_SPARSESET_JUCEHEADER__
  11882. /*** Start of inlined file: juce_Range.h ***/
  11883. #ifndef __JUCE_RANGE_JUCEHEADER__
  11884. #define __JUCE_RANGE_JUCEHEADER__
  11885. /** A general-purpose range object, that simply represents any linear range with
  11886. a start and end point.
  11887. The templated parameter is expected to be a primitive integer or floating point
  11888. type, though class types could also be used if they behave in a number-like way.
  11889. */
  11890. template <typename ValueType>
  11891. class Range
  11892. {
  11893. public:
  11894. /** Constructs an empty range. */
  11895. Range() noexcept
  11896. : start (ValueType()), end (ValueType())
  11897. {
  11898. }
  11899. /** Constructs a range with given start and end values. */
  11900. Range (const ValueType start_, const ValueType end_) noexcept
  11901. : start (start_), end (jmax (start_, end_))
  11902. {
  11903. }
  11904. /** Constructs a copy of another range. */
  11905. Range (const Range& other) noexcept
  11906. : start (other.start), end (other.end)
  11907. {
  11908. }
  11909. /** Copies another range object. */
  11910. Range& operator= (const Range& other) noexcept
  11911. {
  11912. start = other.start;
  11913. end = other.end;
  11914. return *this;
  11915. }
  11916. /** Destructor. */
  11917. ~Range() noexcept
  11918. {
  11919. }
  11920. /** Returns the range that lies between two positions (in either order). */
  11921. static const Range between (const ValueType position1, const ValueType position2) noexcept
  11922. {
  11923. return (position1 < position2) ? Range (position1, position2)
  11924. : Range (position2, position1);
  11925. }
  11926. /** Returns a range with the specified start position and a length of zero. */
  11927. static const Range emptyRange (const ValueType start) noexcept
  11928. {
  11929. return Range (start, start);
  11930. }
  11931. /** Returns the start of the range. */
  11932. inline ValueType getStart() const noexcept { return start; }
  11933. /** Returns the length of the range. */
  11934. inline ValueType getLength() const noexcept { return end - start; }
  11935. /** Returns the end of the range. */
  11936. inline ValueType getEnd() const noexcept { return end; }
  11937. /** Returns true if the range has a length of zero. */
  11938. inline bool isEmpty() const noexcept { return start == end; }
  11939. /** Changes the start position of the range, leaving the end position unchanged.
  11940. If the new start position is higher than the current end of the range, the end point
  11941. will be pushed along to equal it, leaving an empty range at the new position.
  11942. */
  11943. void setStart (const ValueType newStart) noexcept
  11944. {
  11945. start = newStart;
  11946. if (end < newStart)
  11947. end = newStart;
  11948. }
  11949. /** Returns a range with the same end as this one, but a different start.
  11950. If the new start position is higher than the current end of the range, the end point
  11951. will be pushed along to equal it, returning an empty range at the new position.
  11952. */
  11953. const Range withStart (const ValueType newStart) const noexcept
  11954. {
  11955. return Range (newStart, jmax (newStart, end));
  11956. }
  11957. /** Returns a range with the same length as this one, but moved to have the given start position. */
  11958. const Range movedToStartAt (const ValueType newStart) const noexcept
  11959. {
  11960. return Range (newStart, end + (newStart - start));
  11961. }
  11962. /** Changes the end position of the range, leaving the start unchanged.
  11963. If the new end position is below the current start of the range, the start point
  11964. will be pushed back to equal the new end point.
  11965. */
  11966. void setEnd (const ValueType newEnd) noexcept
  11967. {
  11968. end = newEnd;
  11969. if (newEnd < start)
  11970. start = newEnd;
  11971. }
  11972. /** Returns a range with the same start position as this one, but a different end.
  11973. If the new end position is below the current start of the range, the start point
  11974. will be pushed back to equal the new end point.
  11975. */
  11976. const Range withEnd (const ValueType newEnd) const noexcept
  11977. {
  11978. return Range (jmin (start, newEnd), newEnd);
  11979. }
  11980. /** Returns a range with the same length as this one, but moved to have the given start position. */
  11981. const Range movedToEndAt (const ValueType newEnd) const noexcept
  11982. {
  11983. return Range (start + (newEnd - end), newEnd);
  11984. }
  11985. /** Changes the length of the range.
  11986. Lengths less than zero are treated as zero.
  11987. */
  11988. void setLength (const ValueType newLength) noexcept
  11989. {
  11990. end = start + jmax (ValueType(), newLength);
  11991. }
  11992. /** Returns a range with the same start as this one, but a different length.
  11993. Lengths less than zero are treated as zero.
  11994. */
  11995. const Range withLength (const ValueType newLength) const noexcept
  11996. {
  11997. return Range (start, start + newLength);
  11998. }
  11999. /** Adds an amount to the start and end of the range. */
  12000. inline const Range& operator+= (const ValueType amountToAdd) noexcept
  12001. {
  12002. start += amountToAdd;
  12003. end += amountToAdd;
  12004. return *this;
  12005. }
  12006. /** Subtracts an amount from the start and end of the range. */
  12007. inline const Range& operator-= (const ValueType amountToSubtract) noexcept
  12008. {
  12009. start -= amountToSubtract;
  12010. end -= amountToSubtract;
  12011. return *this;
  12012. }
  12013. /** Returns a range that is equal to this one with an amount added to its
  12014. start and end.
  12015. */
  12016. const Range operator+ (const ValueType amountToAdd) const noexcept
  12017. {
  12018. return Range (start + amountToAdd, end + amountToAdd);
  12019. }
  12020. /** Returns a range that is equal to this one with the specified amount
  12021. subtracted from its start and end. */
  12022. const Range operator- (const ValueType amountToSubtract) const noexcept
  12023. {
  12024. return Range (start - amountToSubtract, end - amountToSubtract);
  12025. }
  12026. bool operator== (const Range& other) const noexcept { return start == other.start && end == other.end; }
  12027. bool operator!= (const Range& other) const noexcept { return start != other.start || end != other.end; }
  12028. /** Returns true if the given position lies inside this range. */
  12029. bool contains (const ValueType position) const noexcept
  12030. {
  12031. return start <= position && position < end;
  12032. }
  12033. /** Returns the nearest value to the one supplied, which lies within the range. */
  12034. ValueType clipValue (const ValueType value) const noexcept
  12035. {
  12036. return jlimit (start, end, value);
  12037. }
  12038. /** Returns true if the given range lies entirely inside this range. */
  12039. bool contains (const Range& other) const noexcept
  12040. {
  12041. return start <= other.start && end >= other.end;
  12042. }
  12043. /** Returns true if the given range intersects this one. */
  12044. bool intersects (const Range& other) const noexcept
  12045. {
  12046. return other.start < end && start < other.end;
  12047. }
  12048. /** Returns the range that is the intersection of the two ranges, or an empty range
  12049. with an undefined start position if they don't overlap. */
  12050. const Range getIntersectionWith (const Range& other) const noexcept
  12051. {
  12052. return Range (jmax (start, other.start),
  12053. jmin (end, other.end));
  12054. }
  12055. /** Returns the smallest range that contains both this one and the other one. */
  12056. const Range getUnionWith (const Range& other) const noexcept
  12057. {
  12058. return Range (jmin (start, other.start),
  12059. jmax (end, other.end));
  12060. }
  12061. /** Returns a given range, after moving it forwards or backwards to fit it
  12062. within this range.
  12063. If the supplied range has a greater length than this one, the return value
  12064. will be this range.
  12065. Otherwise, if the supplied range is smaller than this one, the return value
  12066. will be the new range, shifted forwards or backwards so that it doesn't extend
  12067. beyond this one, but keeping its original length.
  12068. */
  12069. const Range constrainRange (const Range& rangeToConstrain) const noexcept
  12070. {
  12071. const ValueType otherLen = rangeToConstrain.getLength();
  12072. return getLength() <= otherLen
  12073. ? *this
  12074. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  12075. }
  12076. private:
  12077. ValueType start, end;
  12078. };
  12079. #endif // __JUCE_RANGE_JUCEHEADER__
  12080. /*** End of inlined file: juce_Range.h ***/
  12081. /**
  12082. Holds a set of primitive values, storing them as a set of ranges.
  12083. This container acts like an array, but can efficiently hold large continguous
  12084. ranges of values. It's quite a specialised class, mostly useful for things
  12085. like keeping the set of selected rows in a listbox.
  12086. The type used as a template paramter must be an integer type, such as int, short,
  12087. int64, etc.
  12088. */
  12089. template <class Type>
  12090. class SparseSet
  12091. {
  12092. public:
  12093. /** Creates a new empty set. */
  12094. SparseSet()
  12095. {
  12096. }
  12097. /** Creates a copy of another SparseSet. */
  12098. SparseSet (const SparseSet<Type>& other)
  12099. : values (other.values)
  12100. {
  12101. }
  12102. /** Clears the set. */
  12103. void clear()
  12104. {
  12105. values.clear();
  12106. }
  12107. /** Checks whether the set is empty.
  12108. This is much quicker than using (size() == 0).
  12109. */
  12110. bool isEmpty() const noexcept
  12111. {
  12112. return values.size() == 0;
  12113. }
  12114. /** Returns the number of values in the set.
  12115. Because of the way the data is stored, this method can take longer if there
  12116. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  12117. are any items.
  12118. */
  12119. Type size() const
  12120. {
  12121. Type total (0);
  12122. for (int i = 0; i < values.size(); i += 2)
  12123. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  12124. return total;
  12125. }
  12126. /** Returns one of the values in the set.
  12127. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  12128. @returns the value at this index, or 0 if it's out-of-range
  12129. */
  12130. Type operator[] (Type index) const
  12131. {
  12132. for (int i = 0; i < values.size(); i += 2)
  12133. {
  12134. const Type start (values.getUnchecked (i));
  12135. const Type len (values.getUnchecked (i + 1) - start);
  12136. if (index < len)
  12137. return start + index;
  12138. index -= len;
  12139. }
  12140. return Type();
  12141. }
  12142. /** Checks whether a particular value is in the set. */
  12143. bool contains (const Type valueToLookFor) const
  12144. {
  12145. for (int i = 0; i < values.size(); ++i)
  12146. if (valueToLookFor < values.getUnchecked(i))
  12147. return (i & 1) != 0;
  12148. return false;
  12149. }
  12150. /** Returns the number of contiguous blocks of values.
  12151. @see getRange
  12152. */
  12153. int getNumRanges() const noexcept
  12154. {
  12155. return values.size() >> 1;
  12156. }
  12157. /** Returns one of the contiguous ranges of values stored.
  12158. @param rangeIndex the index of the range to look up, between 0
  12159. and (getNumRanges() - 1)
  12160. @see getTotalRange
  12161. */
  12162. const Range<Type> getRange (const int rangeIndex) const
  12163. {
  12164. if (isPositiveAndBelow (rangeIndex, getNumRanges()))
  12165. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  12166. values.getUnchecked ((rangeIndex << 1) + 1));
  12167. else
  12168. return Range<Type>();
  12169. }
  12170. /** Returns the range between the lowest and highest values in the set.
  12171. @see getRange
  12172. */
  12173. const Range<Type> getTotalRange() const
  12174. {
  12175. if (values.size() > 0)
  12176. {
  12177. jassert ((values.size() & 1) == 0);
  12178. return Range<Type> (values.getUnchecked (0),
  12179. values.getUnchecked (values.size() - 1));
  12180. }
  12181. return Range<Type>();
  12182. }
  12183. /** Adds a range of contiguous values to the set.
  12184. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  12185. */
  12186. void addRange (const Range<Type>& range)
  12187. {
  12188. jassert (range.getLength() >= 0);
  12189. if (range.getLength() > 0)
  12190. {
  12191. removeRange (range);
  12192. values.addUsingDefaultSort (range.getStart());
  12193. values.addUsingDefaultSort (range.getEnd());
  12194. simplify();
  12195. }
  12196. }
  12197. /** Removes a range of values from the set.
  12198. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  12199. */
  12200. void removeRange (const Range<Type>& rangeToRemove)
  12201. {
  12202. jassert (rangeToRemove.getLength() >= 0);
  12203. if (rangeToRemove.getLength() > 0
  12204. && values.size() > 0
  12205. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  12206. && values.getUnchecked(0) < rangeToRemove.getEnd())
  12207. {
  12208. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  12209. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  12210. const bool onAtEnd = contains (lastValue);
  12211. for (int i = values.size(); --i >= 0;)
  12212. {
  12213. if (values.getUnchecked(i) <= lastValue)
  12214. {
  12215. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  12216. {
  12217. values.remove (i);
  12218. if (--i < 0)
  12219. break;
  12220. }
  12221. break;
  12222. }
  12223. }
  12224. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  12225. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  12226. simplify();
  12227. }
  12228. }
  12229. /** Does an XOR of the values in a given range. */
  12230. void invertRange (const Range<Type>& range)
  12231. {
  12232. SparseSet newItems;
  12233. newItems.addRange (range);
  12234. int i;
  12235. for (i = getNumRanges(); --i >= 0;)
  12236. newItems.removeRange (getRange (i));
  12237. removeRange (range);
  12238. for (i = newItems.getNumRanges(); --i >= 0;)
  12239. addRange (newItems.getRange(i));
  12240. }
  12241. /** Checks whether any part of a given range overlaps any part of this set. */
  12242. bool overlapsRange (const Range<Type>& range)
  12243. {
  12244. if (range.getLength() > 0)
  12245. {
  12246. for (int i = getNumRanges(); --i >= 0;)
  12247. {
  12248. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  12249. return false;
  12250. if (values.getUnchecked (i << 1) < range.getEnd())
  12251. return true;
  12252. }
  12253. }
  12254. return false;
  12255. }
  12256. /** Checks whether the whole of a given range is contained within this one. */
  12257. bool containsRange (const Range<Type>& range)
  12258. {
  12259. if (range.getLength() > 0)
  12260. {
  12261. for (int i = getNumRanges(); --i >= 0;)
  12262. {
  12263. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  12264. return false;
  12265. if (values.getUnchecked (i << 1) <= range.getStart()
  12266. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  12267. return true;
  12268. }
  12269. }
  12270. return false;
  12271. }
  12272. bool operator== (const SparseSet<Type>& other) noexcept
  12273. {
  12274. return values == other.values;
  12275. }
  12276. bool operator!= (const SparseSet<Type>& other) noexcept
  12277. {
  12278. return values != other.values;
  12279. }
  12280. private:
  12281. // alternating start/end values of ranges of values that are present.
  12282. Array<Type, DummyCriticalSection> values;
  12283. void simplify()
  12284. {
  12285. jassert ((values.size() & 1) == 0);
  12286. for (int i = values.size(); --i > 0;)
  12287. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  12288. values.removeRange (--i, 2);
  12289. }
  12290. };
  12291. #endif // __JUCE_SPARSESET_JUCEHEADER__
  12292. /*** End of inlined file: juce_SparseSet.h ***/
  12293. #endif
  12294. #ifndef __JUCE_VALUE_JUCEHEADER__
  12295. /*** Start of inlined file: juce_Value.h ***/
  12296. #ifndef __JUCE_VALUE_JUCEHEADER__
  12297. #define __JUCE_VALUE_JUCEHEADER__
  12298. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  12299. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  12300. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  12301. /*** Start of inlined file: juce_CallbackMessage.h ***/
  12302. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12303. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12304. /*** Start of inlined file: juce_Message.h ***/
  12305. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  12306. #define __JUCE_MESSAGE_JUCEHEADER__
  12307. class MessageListener;
  12308. class MessageManager;
  12309. /** The base class for objects that can be delivered to a MessageListener.
  12310. The simplest Message object contains a few integer and pointer parameters
  12311. that the user can set, and this is enough for a lot of purposes. For passing more
  12312. complex data, subclasses of Message can also be used.
  12313. @see MessageListener, MessageManager, ActionListener, ChangeListener
  12314. */
  12315. class JUCE_API Message : public ReferenceCountedObject
  12316. {
  12317. public:
  12318. /** Creates an uninitialised message.
  12319. The class's variables will also be left uninitialised.
  12320. */
  12321. Message() noexcept;
  12322. /** Creates a message object, filling in the member variables.
  12323. The corresponding public member variables will be set from the parameters
  12324. passed in.
  12325. */
  12326. Message (int intParameter1,
  12327. int intParameter2,
  12328. int intParameter3,
  12329. void* pointerParameter) noexcept;
  12330. /** Destructor. */
  12331. virtual ~Message();
  12332. // These values can be used for carrying simple data that the application needs to
  12333. // pass around. For more complex messages, just create a subclass.
  12334. int intParameter1; /**< user-defined integer value. */
  12335. int intParameter2; /**< user-defined integer value. */
  12336. int intParameter3; /**< user-defined integer value. */
  12337. void* pointerParameter; /**< user-defined pointer value. */
  12338. /** A typedef for pointers to messages. */
  12339. typedef ReferenceCountedObjectPtr <Message> Ptr;
  12340. private:
  12341. friend class MessageListener;
  12342. friend class MessageManager;
  12343. MessageListener* messageRecipient;
  12344. // Avoid the leak-detector because for plugins, the host can unload our DLL with undelivered
  12345. // messages still in the system event queue. These aren't harmful, but can cause annoying assertions.
  12346. JUCE_DECLARE_NON_COPYABLE (Message);
  12347. };
  12348. #endif // __JUCE_MESSAGE_JUCEHEADER__
  12349. /*** End of inlined file: juce_Message.h ***/
  12350. /**
  12351. A message that calls a custom function when it gets delivered.
  12352. You can use this class to fire off actions that you want to be performed later
  12353. on the message thread.
  12354. Unlike other Message objects, these don't get sent to a MessageListener, you
  12355. just call the post() method to send them, and when they arrive, your
  12356. messageCallback() method will automatically be invoked.
  12357. Always create an instance of a CallbackMessage on the heap, as it will be
  12358. deleted automatically after the message has been delivered.
  12359. @see MessageListener, MessageManager, ActionListener, ChangeListener
  12360. */
  12361. class JUCE_API CallbackMessage : public Message
  12362. {
  12363. public:
  12364. CallbackMessage() noexcept;
  12365. /** Destructor. */
  12366. ~CallbackMessage();
  12367. /** Called when the message is delivered.
  12368. You should implement this method and make it do whatever action you want
  12369. to perform.
  12370. Note that like all other messages, this object will be deleted immediately
  12371. after this method has been invoked.
  12372. */
  12373. virtual void messageCallback() = 0;
  12374. /** Instead of sending this message to a MessageListener, just call this method
  12375. to post it to the event queue.
  12376. After you've called this, this object will belong to the MessageManager,
  12377. which will delete it later. So make sure you don't delete the object yourself,
  12378. call post() more than once, or call post() on a stack-based obect!
  12379. */
  12380. void post();
  12381. private:
  12382. // Avoid the leak-detector because for plugins, the host can unload our DLL with undelivered
  12383. // messages still in the system event queue. These aren't harmful, but can cause annoying assertions.
  12384. JUCE_DECLARE_NON_COPYABLE (CallbackMessage);
  12385. };
  12386. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12387. /*** End of inlined file: juce_CallbackMessage.h ***/
  12388. /**
  12389. Has a callback method that is triggered asynchronously.
  12390. This object allows an asynchronous callback function to be triggered, for
  12391. tasks such as coalescing multiple updates into a single callback later on.
  12392. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  12393. message thread calling handleAsyncUpdate() as soon as it can.
  12394. */
  12395. class JUCE_API AsyncUpdater
  12396. {
  12397. public:
  12398. /** Creates an AsyncUpdater object. */
  12399. AsyncUpdater();
  12400. /** Destructor.
  12401. If there are any pending callbacks when the object is deleted, these are lost.
  12402. */
  12403. virtual ~AsyncUpdater();
  12404. /** Causes the callback to be triggered at a later time.
  12405. This method returns immediately, having made sure that a callback
  12406. to the handleAsyncUpdate() method will occur as soon as possible.
  12407. If an update callback is already pending but hasn't happened yet, calls
  12408. to this method will be ignored.
  12409. It's thread-safe to call this method from any number of threads without
  12410. needing to worry about locking.
  12411. */
  12412. void triggerAsyncUpdate();
  12413. /** This will stop any pending updates from happening.
  12414. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  12415. callback happens, this will cancel the handleAsyncUpdate() callback.
  12416. Note that this method simply cancels the next callback - if a callback is already
  12417. in progress on a different thread, this won't block until it finishes, so there's
  12418. no guarantee that the callback isn't still running when you return from
  12419. */
  12420. void cancelPendingUpdate() noexcept;
  12421. /** If an update has been triggered and is pending, this will invoke it
  12422. synchronously.
  12423. Use this as a kind of "flush" operation - if an update is pending, the
  12424. handleAsyncUpdate() method will be called immediately; if no update is
  12425. pending, then nothing will be done.
  12426. Because this may invoke the callback, this method must only be called on
  12427. the main event thread.
  12428. */
  12429. void handleUpdateNowIfNeeded();
  12430. /** Returns true if there's an update callback in the pipeline. */
  12431. bool isUpdatePending() const noexcept;
  12432. /** Called back to do whatever your class needs to do.
  12433. This method is called by the message thread at the next convenient time
  12434. after the triggerAsyncUpdate() method has been called.
  12435. */
  12436. virtual void handleAsyncUpdate() = 0;
  12437. private:
  12438. ReferenceCountedObjectPtr<CallbackMessage> message;
  12439. Atomic<int>& getDeliveryFlag() const noexcept;
  12440. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncUpdater);
  12441. };
  12442. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  12443. /*** End of inlined file: juce_AsyncUpdater.h ***/
  12444. /*** Start of inlined file: juce_ListenerList.h ***/
  12445. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  12446. #define __JUCE_LISTENERLIST_JUCEHEADER__
  12447. /**
  12448. Holds a set of objects and can invoke a member function callback on each object
  12449. in the set with a single call.
  12450. Use a ListenerList to manage a set of objects which need a callback, and you
  12451. can invoke a member function by simply calling call() or callChecked().
  12452. E.g.
  12453. @code
  12454. class MyListenerType
  12455. {
  12456. public:
  12457. void myCallbackMethod (int foo, bool bar);
  12458. };
  12459. ListenerList <MyListenerType> listeners;
  12460. listeners.add (someCallbackObjects...);
  12461. // This will invoke myCallbackMethod (1234, true) on each of the objects
  12462. // in the list...
  12463. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  12464. @endcode
  12465. If you add or remove listeners from the list during one of the callbacks - i.e. while
  12466. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  12467. will be mistakenly called after they've been removed, but it may mean that some of the
  12468. listeners could be called more than once, or not at all, depending on the list's order.
  12469. Sometimes, there's a chance that invoking one of the callbacks might result in the
  12470. list itself being deleted while it's still iterating - to survive this situation, you can
  12471. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  12472. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  12473. the list will check this after each callback to determine whether it should abort the
  12474. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  12475. which can be used to check when a Component has been deleted. See also
  12476. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  12477. */
  12478. template <class ListenerClass,
  12479. class ArrayType = Array <ListenerClass*> >
  12480. class ListenerList
  12481. {
  12482. // Horrible macros required to support VC6/7..
  12483. #ifndef DOXYGEN
  12484. #if JUCE_VC8_OR_EARLIER
  12485. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  12486. #define LL_PARAM(a) Q##a& param##a
  12487. #else
  12488. #define LL_TEMPLATE(a) typename P##a
  12489. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  12490. #endif
  12491. #endif
  12492. public:
  12493. /** Creates an empty list. */
  12494. ListenerList()
  12495. {
  12496. }
  12497. /** Destructor. */
  12498. ~ListenerList()
  12499. {
  12500. }
  12501. /** Adds a listener to the list.
  12502. A listener can only be added once, so if the listener is already in the list,
  12503. this method has no effect.
  12504. @see remove
  12505. */
  12506. void add (ListenerClass* const listenerToAdd)
  12507. {
  12508. // Listeners can't be null pointers!
  12509. jassert (listenerToAdd != nullptr);
  12510. if (listenerToAdd != nullptr)
  12511. listeners.addIfNotAlreadyThere (listenerToAdd);
  12512. }
  12513. /** Removes a listener from the list.
  12514. If the listener wasn't in the list, this has no effect.
  12515. */
  12516. void remove (ListenerClass* const listenerToRemove)
  12517. {
  12518. // Listeners can't be null pointers!
  12519. jassert (listenerToRemove != nullptr);
  12520. listeners.removeValue (listenerToRemove);
  12521. }
  12522. /** Returns the number of registered listeners. */
  12523. int size() const noexcept
  12524. {
  12525. return listeners.size();
  12526. }
  12527. /** Returns true if any listeners are registered. */
  12528. bool isEmpty() const noexcept
  12529. {
  12530. return listeners.size() == 0;
  12531. }
  12532. /** Clears the list. */
  12533. void clear()
  12534. {
  12535. listeners.clear();
  12536. }
  12537. /** Returns true if the specified listener has been added to the list. */
  12538. bool contains (ListenerClass* const listener) const noexcept
  12539. {
  12540. return listeners.contains (listener);
  12541. }
  12542. /** Calls a member function on each listener in the list, with no parameters. */
  12543. void call (void (ListenerClass::*callbackFunction) ())
  12544. {
  12545. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  12546. }
  12547. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  12548. See the class description for info about writing a bail-out checker. */
  12549. template <class BailOutCheckerType>
  12550. void callChecked (const BailOutCheckerType& bailOutChecker,
  12551. void (ListenerClass::*callbackFunction) ())
  12552. {
  12553. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12554. (iter.getListener()->*callbackFunction) ();
  12555. }
  12556. /** Calls a member function on each listener in the list, with 1 parameter. */
  12557. template <LL_TEMPLATE(1)>
  12558. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  12559. {
  12560. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12561. (iter.getListener()->*callbackFunction) (param1);
  12562. }
  12563. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  12564. See the class description for info about writing a bail-out checker. */
  12565. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  12566. void callChecked (const BailOutCheckerType& bailOutChecker,
  12567. void (ListenerClass::*callbackFunction) (P1),
  12568. LL_PARAM(1))
  12569. {
  12570. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12571. (iter.getListener()->*callbackFunction) (param1);
  12572. }
  12573. /** Calls a member function on each listener in the list, with 2 parameters. */
  12574. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  12575. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  12576. LL_PARAM(1), LL_PARAM(2))
  12577. {
  12578. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12579. (iter.getListener()->*callbackFunction) (param1, param2);
  12580. }
  12581. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  12582. See the class description for info about writing a bail-out checker. */
  12583. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  12584. void callChecked (const BailOutCheckerType& bailOutChecker,
  12585. void (ListenerClass::*callbackFunction) (P1, P2),
  12586. LL_PARAM(1), LL_PARAM(2))
  12587. {
  12588. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12589. (iter.getListener()->*callbackFunction) (param1, param2);
  12590. }
  12591. /** Calls a member function on each listener in the list, with 3 parameters. */
  12592. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  12593. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  12594. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  12595. {
  12596. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12597. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  12598. }
  12599. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  12600. See the class description for info about writing a bail-out checker. */
  12601. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  12602. void callChecked (const BailOutCheckerType& bailOutChecker,
  12603. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  12604. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  12605. {
  12606. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12607. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  12608. }
  12609. /** Calls a member function on each listener in the list, with 4 parameters. */
  12610. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  12611. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  12612. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  12613. {
  12614. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12615. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  12616. }
  12617. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  12618. See the class description for info about writing a bail-out checker. */
  12619. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  12620. void callChecked (const BailOutCheckerType& bailOutChecker,
  12621. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  12622. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  12623. {
  12624. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12625. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  12626. }
  12627. /** Calls a member function on each listener in the list, with 5 parameters. */
  12628. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  12629. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  12630. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  12631. {
  12632. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12633. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  12634. }
  12635. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  12636. See the class description for info about writing a bail-out checker. */
  12637. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  12638. void callChecked (const BailOutCheckerType& bailOutChecker,
  12639. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  12640. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  12641. {
  12642. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12643. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  12644. }
  12645. /** A dummy bail-out checker that always returns false.
  12646. See the ListenerList notes for more info about bail-out checkers.
  12647. */
  12648. class DummyBailOutChecker
  12649. {
  12650. public:
  12651. inline bool shouldBailOut() const noexcept { return false; }
  12652. };
  12653. /** Iterates the listeners in a ListenerList. */
  12654. template <class BailOutCheckerType, class ListType>
  12655. class Iterator
  12656. {
  12657. public:
  12658. Iterator (const ListType& list_)
  12659. : list (list_), index (list_.size())
  12660. {}
  12661. ~Iterator() {}
  12662. bool next()
  12663. {
  12664. if (index <= 0)
  12665. return false;
  12666. const int listSize = list.size();
  12667. if (--index < listSize)
  12668. return true;
  12669. index = listSize - 1;
  12670. return index >= 0;
  12671. }
  12672. bool next (const BailOutCheckerType& bailOutChecker)
  12673. {
  12674. return (! bailOutChecker.shouldBailOut()) && next();
  12675. }
  12676. typename ListType::ListenerType* getListener() const noexcept
  12677. {
  12678. return list.getListeners().getUnchecked (index);
  12679. }
  12680. private:
  12681. const ListType& list;
  12682. int index;
  12683. JUCE_DECLARE_NON_COPYABLE (Iterator);
  12684. };
  12685. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  12686. typedef ListenerClass ListenerType;
  12687. const ArrayType& getListeners() const noexcept { return listeners; }
  12688. private:
  12689. ArrayType listeners;
  12690. JUCE_DECLARE_NON_COPYABLE (ListenerList);
  12691. #undef LL_TEMPLATE
  12692. #undef LL_PARAM
  12693. };
  12694. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  12695. /*** End of inlined file: juce_ListenerList.h ***/
  12696. /**
  12697. Represents a shared variant value.
  12698. A Value object contains a reference to a var object, and can get and set its value.
  12699. Listeners can be attached to be told when the value is changed.
  12700. The Value class is a wrapper around a shared, reference-counted underlying data
  12701. object - this means that multiple Value objects can all refer to the same piece of
  12702. data, allowing all of them to be notified when any of them changes it.
  12703. When you create a Value with its default constructor, it acts as a wrapper around a
  12704. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  12705. you can map the Value onto any kind of underlying data.
  12706. */
  12707. class JUCE_API Value
  12708. {
  12709. public:
  12710. /** Creates an empty Value, containing a void var. */
  12711. Value();
  12712. /** Creates a Value that refers to the same value as another one.
  12713. Note that this doesn't make a copy of the other value - both this and the other
  12714. Value will share the same underlying value, so that when either one alters it, both
  12715. will see it change.
  12716. */
  12717. Value (const Value& other);
  12718. /** Creates a Value that is set to the specified value. */
  12719. explicit Value (const var& initialValue);
  12720. /** Destructor. */
  12721. ~Value();
  12722. /** Returns the current value. */
  12723. const var getValue() const;
  12724. /** Returns the current value. */
  12725. operator const var() const;
  12726. /** Returns the value as a string.
  12727. This is alternative to writing things like "myValue.getValue().toString()".
  12728. */
  12729. const String toString() const;
  12730. /** Sets the current value.
  12731. You can also use operator= to set the value.
  12732. If there are any listeners registered, they will be notified of the
  12733. change asynchronously.
  12734. */
  12735. void setValue (const var& newValue);
  12736. /** Sets the current value.
  12737. This is the same as calling setValue().
  12738. If there are any listeners registered, they will be notified of the
  12739. change asynchronously.
  12740. */
  12741. Value& operator= (const var& newValue);
  12742. /** Makes this object refer to the same underlying ValueSource as another one.
  12743. Once this object has been connected to another one, changing either one
  12744. will update the other.
  12745. Existing listeners will still be registered after you call this method, and
  12746. they'll continue to receive messages when the new value changes.
  12747. */
  12748. void referTo (const Value& valueToReferTo);
  12749. /** Returns true if this value and the other one are references to the same value.
  12750. */
  12751. bool refersToSameSourceAs (const Value& other) const;
  12752. /** Compares two values.
  12753. This is a compare-by-value comparison, so is effectively the same as
  12754. saying (this->getValue() == other.getValue()).
  12755. */
  12756. bool operator== (const Value& other) const;
  12757. /** Compares two values.
  12758. This is a compare-by-value comparison, so is effectively the same as
  12759. saying (this->getValue() != other.getValue()).
  12760. */
  12761. bool operator!= (const Value& other) const;
  12762. /** Receives callbacks when a Value object changes.
  12763. @see Value::addListener
  12764. */
  12765. class JUCE_API Listener
  12766. {
  12767. public:
  12768. Listener() {}
  12769. virtual ~Listener() {}
  12770. /** Called when a Value object is changed.
  12771. Note that the Value object passed as a parameter may not be exactly the same
  12772. object that you registered the listener with - it might be a copy that refers
  12773. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  12774. */
  12775. virtual void valueChanged (Value& value) = 0;
  12776. };
  12777. /** Adds a listener to receive callbacks when the value changes.
  12778. The listener is added to this specific Value object, and not to the shared
  12779. object that it refers to. When this object is deleted, all the listeners will
  12780. be lost, even if other references to the same Value still exist. So when you're
  12781. adding a listener, make sure that you add it to a ValueTree instance that will last
  12782. for as long as you need the listener. In general, you'd never want to add a listener
  12783. to a local stack-based ValueTree, but more likely to one that's a member variable.
  12784. @see removeListener
  12785. */
  12786. void addListener (Listener* listener);
  12787. /** Removes a listener that was previously added with addListener(). */
  12788. void removeListener (Listener* listener);
  12789. /**
  12790. Used internally by the Value class as the base class for its shared value objects.
  12791. The Value class is essentially a reference-counted pointer to a shared instance
  12792. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  12793. ValueSource classes to allow Value objects to represent your own custom data items.
  12794. */
  12795. class JUCE_API ValueSource : public ReferenceCountedObject,
  12796. public AsyncUpdater
  12797. {
  12798. public:
  12799. ValueSource();
  12800. virtual ~ValueSource();
  12801. /** Returns the current value of this object. */
  12802. virtual const var getValue() const = 0;
  12803. /** Changes the current value.
  12804. This must also trigger a change message if the value actually changes.
  12805. */
  12806. virtual void setValue (const var& newValue) = 0;
  12807. /** Delivers a change message to all the listeners that are registered with
  12808. this value.
  12809. If dispatchSynchronously is true, the method will call all the listeners
  12810. before returning; otherwise it'll dispatch a message and make the call later.
  12811. */
  12812. void sendChangeMessage (bool dispatchSynchronously);
  12813. protected:
  12814. friend class Value;
  12815. SortedSet <Value*> valuesWithListeners;
  12816. void handleAsyncUpdate();
  12817. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueSource);
  12818. };
  12819. /** Creates a Value object that uses this valueSource object as its underlying data. */
  12820. explicit Value (ValueSource* valueSource);
  12821. /** Returns the ValueSource that this value is referring to. */
  12822. ValueSource& getValueSource() noexcept { return *value; }
  12823. private:
  12824. friend class ValueSource;
  12825. ReferenceCountedObjectPtr <ValueSource> value;
  12826. ListenerList <Listener> listeners;
  12827. void callListeners();
  12828. // This is disallowed to avoid confusion about whether it should
  12829. // do a by-value or by-reference copy.
  12830. Value& operator= (const Value& other);
  12831. };
  12832. /** Writes a Value to an OutputStream as a UTF8 string. */
  12833. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  12834. /** This typedef is just for compatibility with old code - newer code should use the Value::Listener class directly. */
  12835. typedef Value::Listener ValueListener;
  12836. #endif // __JUCE_VALUE_JUCEHEADER__
  12837. /*** End of inlined file: juce_Value.h ***/
  12838. #endif
  12839. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12840. /*** Start of inlined file: juce_ValueTree.h ***/
  12841. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12842. #define __JUCE_VALUETREE_JUCEHEADER__
  12843. /*** Start of inlined file: juce_UndoManager.h ***/
  12844. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  12845. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  12846. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  12847. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12848. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12849. /*** Start of inlined file: juce_ChangeListener.h ***/
  12850. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  12851. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  12852. class ChangeBroadcaster;
  12853. /**
  12854. Receives change event callbacks that are sent out by a ChangeBroadcaster.
  12855. A ChangeBroadcaster keeps a set of listeners to which it broadcasts a message when
  12856. the ChangeBroadcaster::sendChangeMessage() method is called. A subclass of
  12857. ChangeListener is used to receive these callbacks.
  12858. Note that the major difference between an ActionListener and a ChangeListener
  12859. is that for a ChangeListener, multiple changes will be coalesced into fewer
  12860. callbacks, but ActionListeners perform one callback for every event posted.
  12861. @see ChangeBroadcaster, ActionListener
  12862. */
  12863. class JUCE_API ChangeListener
  12864. {
  12865. public:
  12866. /** Destructor. */
  12867. virtual ~ChangeListener() {}
  12868. /** Your subclass should implement this method to receive the callback.
  12869. @param source the ChangeBroadcaster that triggered the callback.
  12870. */
  12871. virtual void changeListenerCallback (ChangeBroadcaster* source) = 0;
  12872. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  12873. // This method's signature has changed to take a ChangeBroadcaster parameter - please update your code!
  12874. private: virtual int changeListenerCallback (void*) { return 0; }
  12875. #endif
  12876. };
  12877. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  12878. /*** End of inlined file: juce_ChangeListener.h ***/
  12879. /**
  12880. Holds a list of ChangeListeners, and sends messages to them when instructed.
  12881. @see ChangeListener
  12882. */
  12883. class JUCE_API ChangeBroadcaster
  12884. {
  12885. public:
  12886. /** Creates an ChangeBroadcaster. */
  12887. ChangeBroadcaster() noexcept;
  12888. /** Destructor. */
  12889. virtual ~ChangeBroadcaster();
  12890. /** Registers a listener to receive change callbacks from this broadcaster.
  12891. Trying to add a listener that's already on the list will have no effect.
  12892. */
  12893. void addChangeListener (ChangeListener* listener);
  12894. /** Unregisters a listener from the list.
  12895. If the listener isn't on the list, this won't have any effect.
  12896. */
  12897. void removeChangeListener (ChangeListener* listener);
  12898. /** Removes all listeners from the list. */
  12899. void removeAllChangeListeners();
  12900. /** Causes an asynchronous change message to be sent to all the registered listeners.
  12901. The message will be delivered asynchronously by the main message thread, so this
  12902. method will return immediately. To call the listeners synchronously use
  12903. sendSynchronousChangeMessage().
  12904. */
  12905. void sendChangeMessage();
  12906. /** Sends a synchronous change message to all the registered listeners.
  12907. This will immediately call all the listeners that are registered. For thread-safety
  12908. reasons, you must only call this method on the main message thread.
  12909. @see dispatchPendingMessages
  12910. */
  12911. void sendSynchronousChangeMessage();
  12912. /** If a change message has been sent but not yet dispatched, this will call
  12913. sendSynchronousChangeMessage() to make the callback immediately.
  12914. For thread-safety reasons, you must only call this method on the main message thread.
  12915. */
  12916. void dispatchPendingMessages();
  12917. private:
  12918. class ChangeBroadcasterCallback : public AsyncUpdater
  12919. {
  12920. public:
  12921. ChangeBroadcasterCallback();
  12922. void handleAsyncUpdate();
  12923. ChangeBroadcaster* owner;
  12924. };
  12925. friend class ChangeBroadcasterCallback;
  12926. ChangeBroadcasterCallback callback;
  12927. ListenerList <ChangeListener> changeListeners;
  12928. void callListeners();
  12929. JUCE_DECLARE_NON_COPYABLE (ChangeBroadcaster);
  12930. };
  12931. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12932. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  12933. /*** Start of inlined file: juce_UndoableAction.h ***/
  12934. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  12935. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  12936. /**
  12937. Used by the UndoManager class to store an action which can be done
  12938. and undone.
  12939. @see UndoManager
  12940. */
  12941. class JUCE_API UndoableAction
  12942. {
  12943. protected:
  12944. /** Creates an action. */
  12945. UndoableAction() noexcept {}
  12946. public:
  12947. /** Destructor. */
  12948. virtual ~UndoableAction() {}
  12949. /** Overridden by a subclass to perform the action.
  12950. This method is called by the UndoManager, and shouldn't be used directly by
  12951. applications.
  12952. Be careful not to make any calls in a perform() method that could call
  12953. recursively back into the UndoManager::perform() method
  12954. @returns true if the action could be performed.
  12955. @see UndoManager::perform
  12956. */
  12957. virtual bool perform() = 0;
  12958. /** Overridden by a subclass to undo the action.
  12959. This method is called by the UndoManager, and shouldn't be used directly by
  12960. applications.
  12961. Be careful not to make any calls in an undo() method that could call
  12962. recursively back into the UndoManager::perform() method
  12963. @returns true if the action could be undone without any errors.
  12964. @see UndoManager::perform
  12965. */
  12966. virtual bool undo() = 0;
  12967. /** Returns a value to indicate how much memory this object takes up.
  12968. Because the UndoManager keeps a list of UndoableActions, this is used
  12969. to work out how much space each one will take up, so that the UndoManager
  12970. can work out how many to keep.
  12971. The default value returned here is 10 - units are arbitrary and
  12972. don't have to be accurate.
  12973. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  12974. UndoManager::setMaxNumberOfStoredUnits
  12975. */
  12976. virtual int getSizeInUnits() { return 10; }
  12977. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  12978. If possible, this method should create and return a single action that does the same job as
  12979. this one followed by the supplied action.
  12980. If it's not possible to merge the two actions, the method should return zero.
  12981. */
  12982. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return nullptr; }
  12983. };
  12984. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  12985. /*** End of inlined file: juce_UndoableAction.h ***/
  12986. /**
  12987. Manages a list of undo/redo commands.
  12988. An UndoManager object keeps a list of past actions and can use these actions
  12989. to move backwards and forwards through an undo history.
  12990. To use it, create subclasses of UndoableAction which perform all the
  12991. actions you need, then when you need to actually perform an action, create one
  12992. and pass it to the UndoManager's perform() method.
  12993. The manager also uses the concept of 'transactions' to group the actions
  12994. together - all actions performed between calls to beginNewTransaction() are
  12995. grouped together and are all undone/redone as a group.
  12996. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  12997. when actions are performed or undone.
  12998. @see UndoableAction
  12999. */
  13000. class JUCE_API UndoManager : public ChangeBroadcaster
  13001. {
  13002. public:
  13003. /** Creates an UndoManager.
  13004. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  13005. to indicate how much storage it takes up
  13006. (UndoableAction::getSizeInUnits()), so this
  13007. lets you specify the maximum total number of
  13008. units that the undomanager is allowed to
  13009. keep in memory before letting the older actions
  13010. drop off the end of the list.
  13011. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  13012. that will be kept, even if this involves exceeding
  13013. the amount of space specified in maxNumberOfUnitsToKeep
  13014. */
  13015. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  13016. int minimumTransactionsToKeep = 30);
  13017. /** Destructor. */
  13018. ~UndoManager();
  13019. /** Deletes all stored actions in the list. */
  13020. void clearUndoHistory();
  13021. /** Returns the current amount of space to use for storing UndoableAction objects.
  13022. @see setMaxNumberOfStoredUnits
  13023. */
  13024. int getNumberOfUnitsTakenUpByStoredCommands() const;
  13025. /** Sets the amount of space that can be used for storing UndoableAction objects.
  13026. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  13027. to indicate how much storage it takes up
  13028. (UndoableAction::getSizeInUnits()), so this
  13029. lets you specify the maximum total number of
  13030. units that the undomanager is allowed to
  13031. keep in memory before letting the older actions
  13032. drop off the end of the list.
  13033. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  13034. that will be kept, even if this involves exceeding
  13035. the amount of space specified in maxNumberOfUnitsToKeep
  13036. @see getNumberOfUnitsTakenUpByStoredCommands
  13037. */
  13038. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  13039. int minimumTransactionsToKeep);
  13040. /** Performs an action and adds it to the undo history list.
  13041. @param action the action to perform - this will be deleted by the UndoManager
  13042. when no longer needed
  13043. @param actionName if this string is non-empty, the current transaction will be
  13044. given this name; if it's empty, the current transaction name will
  13045. be left unchanged. See setCurrentTransactionName()
  13046. @returns true if the command succeeds - see UndoableAction::perform
  13047. @see beginNewTransaction
  13048. */
  13049. bool perform (UndoableAction* action,
  13050. const String& actionName = String::empty);
  13051. /** Starts a new group of actions that together will be treated as a single transaction.
  13052. All actions that are passed to the perform() method between calls to this
  13053. method are grouped together and undone/redone together by a single call to
  13054. undo() or redo().
  13055. @param actionName a description of the transaction that is about to be
  13056. performed
  13057. */
  13058. void beginNewTransaction (const String& actionName = String::empty);
  13059. /** Changes the name stored for the current transaction.
  13060. Each transaction is given a name when the beginNewTransaction() method is
  13061. called, but this can be used to change that name without starting a new
  13062. transaction.
  13063. */
  13064. void setCurrentTransactionName (const String& newName);
  13065. /** Returns true if there's at least one action in the list to undo.
  13066. @see getUndoDescription, undo, canRedo
  13067. */
  13068. bool canUndo() const;
  13069. /** Returns the description of the transaction that would be next to get undone.
  13070. The description returned is the one that was passed into beginNewTransaction
  13071. before the set of actions was performed.
  13072. @see undo
  13073. */
  13074. const String getUndoDescription() const;
  13075. /** Tries to roll-back the last transaction.
  13076. @returns true if the transaction can be undone, and false if it fails, or
  13077. if there aren't any transactions to undo
  13078. */
  13079. bool undo();
  13080. /** Tries to roll-back any actions that were added to the current transaction.
  13081. This will perform an undo() only if there are some actions in the undo list
  13082. that were added after the last call to beginNewTransaction().
  13083. This is useful because it lets you call beginNewTransaction(), then
  13084. perform an operation which may or may not actually perform some actions, and
  13085. then call this method to get rid of any actions that might have been done
  13086. without it rolling back the previous transaction if nothing was actually
  13087. done.
  13088. @returns true if any actions were undone.
  13089. */
  13090. bool undoCurrentTransactionOnly();
  13091. /** Returns a list of the UndoableAction objects that have been performed during the
  13092. transaction that is currently open.
  13093. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  13094. were to be called now.
  13095. The first item in the list is the earliest action performed.
  13096. */
  13097. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  13098. /** Returns the number of UndoableAction objects that have been performed during the
  13099. transaction that is currently open.
  13100. @see getActionsInCurrentTransaction
  13101. */
  13102. int getNumActionsInCurrentTransaction() const;
  13103. /** Returns true if there's at least one action in the list to redo.
  13104. @see getRedoDescription, redo, canUndo
  13105. */
  13106. bool canRedo() const;
  13107. /** Returns the description of the transaction that would be next to get redone.
  13108. The description returned is the one that was passed into beginNewTransaction
  13109. before the set of actions was performed.
  13110. @see redo
  13111. */
  13112. const String getRedoDescription() const;
  13113. /** Tries to redo the last transaction that was undone.
  13114. @returns true if the transaction can be redone, and false if it fails, or
  13115. if there aren't any transactions to redo
  13116. */
  13117. bool redo();
  13118. private:
  13119. OwnedArray <OwnedArray <UndoableAction> > transactions;
  13120. StringArray transactionNames;
  13121. String currentTransactionName;
  13122. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  13123. bool newTransaction, reentrancyCheck;
  13124. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UndoManager);
  13125. };
  13126. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  13127. /*** End of inlined file: juce_UndoManager.h ***/
  13128. /**
  13129. A powerful tree structure that can be used to hold free-form data, and which can
  13130. handle its own undo and redo behaviour.
  13131. A ValueTree contains a list of named properties as var objects, and also holds
  13132. any number of sub-trees.
  13133. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  13134. they're simply a lightweight reference to a shared data container. Creating a copy
  13135. of another ValueTree simply creates a new reference to the same underlying object - to
  13136. make a separate, deep copy of a tree you should explicitly call createCopy().
  13137. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  13138. and much of the structure of a ValueTree is similar to an XmlElement tree.
  13139. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  13140. contain text elements, the conversion works well and makes a good serialisation
  13141. format. They can also be serialised to a binary format, which is very fast and compact.
  13142. All the methods that change data take an optional UndoManager, which will be used
  13143. to track any changes to the object. For this to work, you have to be careful to
  13144. consistently always use the same UndoManager for all operations to any node inside
  13145. the tree.
  13146. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  13147. one tree to another, be careful to always remove it first, before adding it. This
  13148. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  13149. assertions if you try to do anything dangerous, but there are still plenty of ways it
  13150. could go wrong.
  13151. Listeners can be added to a ValueTree to be told when properies change and when
  13152. nodes are added or removed.
  13153. @see var, XmlElement
  13154. */
  13155. class JUCE_API ValueTree
  13156. {
  13157. public:
  13158. /** Creates an empty, invalid ValueTree.
  13159. A ValueTree that is created with this constructor can't actually be used for anything,
  13160. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  13161. To create a real one, use the constructor that takes a string.
  13162. @see ValueTree::invalid
  13163. */
  13164. ValueTree() noexcept;
  13165. /** Creates an empty ValueTree with the given type name.
  13166. Like an XmlElement, each ValueTree node has a type, which you can access with
  13167. getType() and hasType().
  13168. */
  13169. explicit ValueTree (const Identifier& type);
  13170. /** Creates a reference to another ValueTree. */
  13171. ValueTree (const ValueTree& other);
  13172. /** Makes this object reference another node. */
  13173. ValueTree& operator= (const ValueTree& other);
  13174. /** Destructor. */
  13175. ~ValueTree();
  13176. /** Returns true if both this and the other tree node refer to the same underlying structure.
  13177. Note that this isn't a value comparison - two independently-created trees which
  13178. contain identical data are not considered equal.
  13179. */
  13180. bool operator== (const ValueTree& other) const noexcept;
  13181. /** Returns true if this and the other node refer to different underlying structures.
  13182. Note that this isn't a value comparison - two independently-created trees which
  13183. contain identical data are not considered equal.
  13184. */
  13185. bool operator!= (const ValueTree& other) const noexcept;
  13186. /** Performs a deep comparison between the properties and children of two trees.
  13187. If all the properties and children of the two trees are the same (recursively), this
  13188. returns true.
  13189. The normal operator==() only checks whether two trees refer to the same shared data
  13190. structure, so use this method if you need to do a proper value comparison.
  13191. */
  13192. bool isEquivalentTo (const ValueTree& other) const;
  13193. /** Returns true if this node refers to some valid data.
  13194. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  13195. call to getChild().
  13196. */
  13197. bool isValid() const { return object != nullptr; }
  13198. /** Returns a deep copy of this tree and all its sub-nodes. */
  13199. ValueTree createCopy() const;
  13200. /** Returns the type of this node.
  13201. The type is specified when the ValueTree is created.
  13202. @see hasType
  13203. */
  13204. const Identifier getType() const;
  13205. /** Returns true if the node has this type.
  13206. The comparison is case-sensitive.
  13207. */
  13208. bool hasType (const Identifier& typeName) const;
  13209. /** Returns the value of a named property.
  13210. If no such property has been set, this will return a void variant.
  13211. You can also use operator[] to get a property.
  13212. @see var, setProperty, hasProperty
  13213. */
  13214. const var& getProperty (const Identifier& name) const;
  13215. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  13216. If no such property has been set, this will return the value of defaultReturnValue.
  13217. You can also use operator[] and getProperty to get a property.
  13218. @see var, getProperty, setProperty, hasProperty
  13219. */
  13220. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  13221. /** Returns the value of a named property.
  13222. If no such property has been set, this will return a void variant. This is the same as
  13223. calling getProperty().
  13224. @see getProperty
  13225. */
  13226. const var& operator[] (const Identifier& name) const;
  13227. /** Changes a named property of the node.
  13228. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13229. so that this change can be undone.
  13230. @see var, getProperty, removeProperty
  13231. */
  13232. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  13233. /** Returns true if the node contains a named property. */
  13234. bool hasProperty (const Identifier& name) const;
  13235. /** Removes a property from the node.
  13236. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13237. so that this change can be undone.
  13238. */
  13239. void removeProperty (const Identifier& name, UndoManager* undoManager);
  13240. /** Removes all properties from the node.
  13241. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13242. so that this change can be undone.
  13243. */
  13244. void removeAllProperties (UndoManager* undoManager);
  13245. /** Returns the total number of properties that the node contains.
  13246. @see getProperty.
  13247. */
  13248. int getNumProperties() const;
  13249. /** Returns the identifier of the property with a given index.
  13250. @see getNumProperties
  13251. */
  13252. const Identifier getPropertyName (int index) const;
  13253. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  13254. The Value object will maintain a reference to this tree, and will use the undo manager when
  13255. it needs to change the value. Attaching a Value::Listener to the value object will provide
  13256. callbacks whenever the property changes.
  13257. */
  13258. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  13259. /** Returns the number of child nodes belonging to this one.
  13260. @see getChild
  13261. */
  13262. int getNumChildren() const;
  13263. /** Returns one of this node's child nodes.
  13264. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  13265. whether a node is valid).
  13266. */
  13267. ValueTree getChild (int index) const;
  13268. /** Returns the first child node with the speficied type name.
  13269. If no such node is found, it'll return an invalid node. (See isValid() to find out
  13270. whether a node is valid).
  13271. @see getOrCreateChildWithName
  13272. */
  13273. ValueTree getChildWithName (const Identifier& type) const;
  13274. /** Returns the first child node with the speficied type name, creating and adding
  13275. a child with this name if there wasn't already one there.
  13276. The only time this will return an invalid object is when the object that you're calling
  13277. the method on is itself invalid.
  13278. @see getChildWithName
  13279. */
  13280. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  13281. /** Looks for the first child node that has the speficied property value.
  13282. This will scan the child nodes in order, until it finds one that has property that matches
  13283. the specified value.
  13284. If no such node is found, it'll return an invalid node. (See isValid() to find out
  13285. whether a node is valid).
  13286. */
  13287. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  13288. /** Adds a child to this node.
  13289. Make sure that the child is removed from any former parent node before calling this, or
  13290. you'll hit an assertion.
  13291. If the index is < 0 or greater than the current number of child nodes, the new node will
  13292. be added at the end of the list.
  13293. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13294. so that this change can be undone.
  13295. */
  13296. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  13297. /** Removes the specified child from this node's child-list.
  13298. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13299. so that this change can be undone.
  13300. */
  13301. void removeChild (const ValueTree& child, UndoManager* undoManager);
  13302. /** Removes a child from this node's child-list.
  13303. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13304. so that this change can be undone.
  13305. */
  13306. void removeChild (int childIndex, UndoManager* undoManager);
  13307. /** Removes all child-nodes from this node.
  13308. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13309. so that this change can be undone.
  13310. */
  13311. void removeAllChildren (UndoManager* undoManager);
  13312. /** Moves one of the children to a different index.
  13313. This will move the child to a specified index, shuffling along any intervening
  13314. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  13315. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  13316. @param currentIndex the index of the item to be moved. If this isn't a
  13317. valid index, then nothing will be done
  13318. @param newIndex the index at which you'd like this item to end up. If this
  13319. is less than zero, the value will be moved to the end
  13320. of the list
  13321. @param undoManager the optional UndoManager to use to store this transaction
  13322. */
  13323. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  13324. /** Returns true if this node is anywhere below the specified parent node.
  13325. This returns true if the node is a child-of-a-child, as well as a direct child.
  13326. */
  13327. bool isAChildOf (const ValueTree& possibleParent) const;
  13328. /** Returns the index of a child item in this parent.
  13329. If the child isn't found, this returns -1.
  13330. */
  13331. int indexOf (const ValueTree& child) const;
  13332. /** Returns the parent node that contains this one.
  13333. If the node has no parent, this will return an invalid node. (See isValid() to find out
  13334. whether a node is valid).
  13335. */
  13336. ValueTree getParent() const;
  13337. /** Returns one of this node's siblings in its parent's child list.
  13338. The delta specifies how far to move through the list, so a value of 1 would return the node
  13339. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  13340. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  13341. */
  13342. ValueTree getSibling (int delta) const;
  13343. /** Creates an XmlElement that holds a complete image of this node and all its children.
  13344. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  13345. be used to recreate a similar node by calling fromXml()
  13346. @see fromXml
  13347. */
  13348. XmlElement* createXml() const;
  13349. /** Tries to recreate a node from its XML representation.
  13350. This isn't designed to cope with random XML data - for a sensible result, it should only
  13351. be fed XML that was created by the createXml() method.
  13352. */
  13353. static ValueTree fromXml (const XmlElement& xml);
  13354. /** Stores this tree (and all its children) in a binary format.
  13355. Once written, the data can be read back with readFromStream().
  13356. It's much faster to load/save your tree in binary form than as XML, but
  13357. obviously isn't human-readable.
  13358. */
  13359. void writeToStream (OutputStream& output);
  13360. /** Reloads a tree from a stream that was written with writeToStream(). */
  13361. static ValueTree readFromStream (InputStream& input);
  13362. /** Reloads a tree from a data block that was written with writeToStream(). */
  13363. static ValueTree readFromData (const void* data, size_t numBytes);
  13364. /** Listener class for events that happen to a ValueTree.
  13365. To get events from a ValueTree, make your class implement this interface, and use
  13366. ValueTree::addListener() and ValueTree::removeListener() to register it.
  13367. */
  13368. class JUCE_API Listener
  13369. {
  13370. public:
  13371. /** Destructor. */
  13372. virtual ~Listener() {}
  13373. /** This method is called when a property of this node (or of one of its sub-nodes) has
  13374. changed.
  13375. The tree parameter indicates which tree has had its property changed, and the property
  13376. parameter indicates the property.
  13377. Note that when you register a listener to a tree, it will receive this callback for
  13378. property changes in that tree, and also for any of its children, (recursively, at any depth).
  13379. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13380. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  13381. */
  13382. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  13383. const Identifier& property) = 0;
  13384. /** This method is called when a child sub-tree is added.
  13385. Note that when you register a listener to a tree, it will receive this callback for
  13386. child changes in both that tree and any of its children, (recursively, at any depth).
  13387. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13388. just check the parentTree parameter to make sure it's the one that you're interested in.
  13389. */
  13390. virtual void valueTreeChildAdded (ValueTree& parentTree,
  13391. ValueTree& childWhichHasBeenAdded) = 0;
  13392. /** This method is called when a child sub-tree is removed.
  13393. Note that when you register a listener to a tree, it will receive this callback for
  13394. child changes in both that tree and any of its children, (recursively, at any depth).
  13395. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13396. just check the parentTree parameter to make sure it's the one that you're interested in.
  13397. */
  13398. virtual void valueTreeChildRemoved (ValueTree& parentTree,
  13399. ValueTree& childWhichHasBeenRemoved) = 0;
  13400. /** This method is called when a tree's children have been re-shuffled.
  13401. Note that when you register a listener to a tree, it will receive this callback for
  13402. child changes in both that tree and any of its children, (recursively, at any depth).
  13403. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13404. just check the parameter to make sure it's the tree that you're interested in.
  13405. */
  13406. virtual void valueTreeChildOrderChanged (ValueTree& parentTreeWhoseChildrenHaveMoved) = 0;
  13407. /** This method is called when a tree has been added or removed from a parent node.
  13408. This callback happens when the tree to which the listener was registered is added or
  13409. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  13410. the listener is registered, and not to any of its children.
  13411. */
  13412. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  13413. };
  13414. /** Adds a listener to receive callbacks when this node is changed.
  13415. The listener is added to this specific ValueTree object, and not to the shared
  13416. object that it refers to. When this object is deleted, all the listeners will
  13417. be lost, even if other references to the same ValueTree still exist. And if you
  13418. use the operator= to make this refer to a different ValueTree, any listeners will
  13419. begin listening to changes to the new tree instead of the old one.
  13420. When you're adding a listener, make sure that you add it to a ValueTree instance that
  13421. will last for as long as you need the listener. In general, you'd never want to add a
  13422. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  13423. @see removeListener
  13424. */
  13425. void addListener (Listener* listener);
  13426. /** Removes a listener that was previously added with addListener(). */
  13427. void removeListener (Listener* listener);
  13428. /** This method uses a comparator object to sort the tree's children into order.
  13429. The object provided must have a method of the form:
  13430. @code
  13431. int compareElements (const ValueTree& first, const ValueTree& second);
  13432. @endcode
  13433. ..and this method must return:
  13434. - a value of < 0 if the first comes before the second
  13435. - a value of 0 if the two objects are equivalent
  13436. - a value of > 0 if the second comes before the first
  13437. To improve performance, the compareElements() method can be declared as static or const.
  13438. @param comparator the comparator to use for comparing elements.
  13439. @param undoManager optional UndoManager for storing the changes
  13440. @param retainOrderOfEquivalentItems if this is true, then items which the comparator says are
  13441. equivalent will be kept in the order in which they currently appear in the array.
  13442. This is slower to perform, but may be important in some cases. If it's false, a
  13443. faster algorithm is used, but equivalent elements may be rearranged.
  13444. */
  13445. template <typename ElementComparator>
  13446. void sort (ElementComparator& comparator, UndoManager* undoManager, bool retainOrderOfEquivalentItems)
  13447. {
  13448. if (object != nullptr)
  13449. {
  13450. ReferenceCountedArray <SharedObject> sortedList (object->children);
  13451. ComparatorAdapter <ElementComparator> adapter (comparator);
  13452. sortedList.sort (adapter, retainOrderOfEquivalentItems);
  13453. object->reorderChildren (sortedList, undoManager);
  13454. }
  13455. }
  13456. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  13457. This invalid object is equivalent to ValueTree created with its default constructor.
  13458. */
  13459. static const ValueTree invalid;
  13460. private:
  13461. class SetPropertyAction;
  13462. friend class SetPropertyAction;
  13463. class AddOrRemoveChildAction;
  13464. friend class AddOrRemoveChildAction;
  13465. class MoveChildAction;
  13466. friend class MoveChildAction;
  13467. class JUCE_API SharedObject : public ReferenceCountedObject
  13468. {
  13469. public:
  13470. explicit SharedObject (const Identifier& type);
  13471. SharedObject (const SharedObject& other);
  13472. ~SharedObject();
  13473. const Identifier type;
  13474. NamedValueSet properties;
  13475. ReferenceCountedArray <SharedObject> children;
  13476. SortedSet <ValueTree*> valueTreesWithListeners;
  13477. SharedObject* parent;
  13478. void sendPropertyChangeMessage (const Identifier& property);
  13479. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  13480. void sendChildAddedMessage (ValueTree& parent, ValueTree& child);
  13481. void sendChildAddedMessage (ValueTree child);
  13482. void sendChildRemovedMessage (ValueTree& parent, ValueTree& child);
  13483. void sendChildRemovedMessage (ValueTree child);
  13484. void sendChildOrderChangedMessage (ValueTree& parent);
  13485. void sendChildOrderChangedMessage();
  13486. void sendParentChangeMessage();
  13487. const var& getProperty (const Identifier& name) const;
  13488. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  13489. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  13490. bool hasProperty (const Identifier& name) const;
  13491. void removeProperty (const Identifier& name, UndoManager*);
  13492. void removeAllProperties (UndoManager*);
  13493. bool isAChildOf (const SharedObject* possibleParent) const;
  13494. int indexOf (const ValueTree& child) const;
  13495. ValueTree getChildWithName (const Identifier& type) const;
  13496. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  13497. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  13498. void addChild (SharedObject* child, int index, UndoManager*);
  13499. void removeChild (int childIndex, UndoManager*);
  13500. void removeAllChildren (UndoManager*);
  13501. void moveChild (int currentIndex, int newIndex, UndoManager*);
  13502. void reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager*);
  13503. bool isEquivalentTo (const SharedObject& other) const;
  13504. XmlElement* createXml() const;
  13505. private:
  13506. SharedObject& operator= (const SharedObject&);
  13507. JUCE_LEAK_DETECTOR (SharedObject);
  13508. };
  13509. template <typename ElementComparator>
  13510. class ComparatorAdapter
  13511. {
  13512. public:
  13513. ComparatorAdapter (ElementComparator& comparator_) noexcept : comparator (comparator_) {}
  13514. int compareElements (SharedObject* const first, SharedObject* const second)
  13515. {
  13516. return comparator.compareElements (ValueTree (first), ValueTree (second));
  13517. }
  13518. private:
  13519. ElementComparator& comparator;
  13520. JUCE_DECLARE_NON_COPYABLE (ComparatorAdapter);
  13521. };
  13522. friend class SharedObject;
  13523. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  13524. SharedObjectPtr object;
  13525. ListenerList <Listener> listeners;
  13526. #if JUCE_MSVC && ! DOXYGEN
  13527. public: // (workaround for VC6)
  13528. #endif
  13529. explicit ValueTree (SharedObject*);
  13530. };
  13531. #endif // __JUCE_VALUETREE_JUCEHEADER__
  13532. /*** End of inlined file: juce_ValueTree.h ***/
  13533. #endif
  13534. #ifndef __JUCE_VARIANT_JUCEHEADER__
  13535. #endif
  13536. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  13537. /*** Start of inlined file: juce_FileLogger.h ***/
  13538. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  13539. #define __JUCE_FILELOGGER_JUCEHEADER__
  13540. /**
  13541. A simple implemenation of a Logger that writes to a file.
  13542. @see Logger
  13543. */
  13544. class JUCE_API FileLogger : public Logger
  13545. {
  13546. public:
  13547. /** Creates a FileLogger for a given file.
  13548. @param fileToWriteTo the file that to use - new messages will be appended
  13549. to the file. If the file doesn't exist, it will be created,
  13550. along with any parent directories that are needed.
  13551. @param welcomeMessage when opened, the logger will write a header to the log, along
  13552. with the current date and time, and this welcome message
  13553. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  13554. but is larger than this number of bytes, then the start of the
  13555. file will be truncated to keep the size down. This prevents a log
  13556. file getting ridiculously large over time. The file will be truncated
  13557. at a new-line boundary. If this value is less than zero, no size limit
  13558. will be imposed; if it's zero, the file will always be deleted. Note that
  13559. the size is only checked once when this object is created - any logging
  13560. that is done later will be appended without any checking
  13561. */
  13562. FileLogger (const File& fileToWriteTo,
  13563. const String& welcomeMessage,
  13564. const int maxInitialFileSizeBytes = 128 * 1024);
  13565. /** Destructor. */
  13566. ~FileLogger();
  13567. void logMessage (const String& message);
  13568. const File getLogFile() const { return logFile; }
  13569. /** Helper function to create a log file in the correct place for this platform.
  13570. On Windows this will return a logger with a path such as:
  13571. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  13572. On the Mac it'll create something like:
  13573. ~/Library/Logs/[logFileName]
  13574. The method might return 0 if the file can't be created for some reason.
  13575. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  13576. it's best to use the something like the name of your application here.
  13577. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  13578. call it "log.txt" because if it goes in a directory with logs
  13579. from other applications (as it will do on the Mac) then no-one
  13580. will know which one is yours!
  13581. @param welcomeMessage a message that will be written to the log when it's opened.
  13582. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  13583. */
  13584. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  13585. const String& logFileName,
  13586. const String& welcomeMessage,
  13587. const int maxInitialFileSizeBytes = 128 * 1024);
  13588. private:
  13589. File logFile;
  13590. CriticalSection logLock;
  13591. void trimFileSize (int maxFileSizeBytes) const;
  13592. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileLogger);
  13593. };
  13594. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  13595. /*** End of inlined file: juce_FileLogger.h ***/
  13596. #endif
  13597. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  13598. /*** Start of inlined file: juce_Initialisation.h ***/
  13599. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  13600. #define __JUCE_INITIALISATION_JUCEHEADER__
  13601. /** Initialises Juce's GUI classes.
  13602. If you're embedding Juce into an application that uses its own event-loop rather
  13603. than using the START_JUCE_APPLICATION macro, call this function before making any
  13604. Juce calls, to make sure things are initialised correctly.
  13605. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  13606. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  13607. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  13608. */
  13609. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
  13610. /** Clears up any static data being used by Juce's GUI classes.
  13611. If you're embedding Juce into an application that uses its own event-loop rather
  13612. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  13613. code to clean up any juce objects that might be lying around.
  13614. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  13615. */
  13616. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  13617. /** Initialises the core parts of Juce.
  13618. If you're embedding Juce into either a command-line program, call this function
  13619. at the start of your main() function to make sure that Juce is initialised correctly.
  13620. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  13621. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  13622. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  13623. */
  13624. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI();
  13625. /** Clears up any static data being used by Juce's non-gui core classes.
  13626. If you're embedding Juce into either a command-line program, call this function
  13627. at the end of your main() function if you want to make sure any Juce objects are
  13628. cleaned up correctly.
  13629. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  13630. */
  13631. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI();
  13632. /** A utility object that helps you initialise and shutdown Juce correctly
  13633. using an RAII pattern.
  13634. When an instance of this class is created, it calls initialiseJuce_NonGUI(),
  13635. and when it's deleted, it calls shutdownJuce_NonGUI(), which lets you easily
  13636. make sure that these functions are matched correctly.
  13637. This class is particularly handy to use at the beginning of a console app's
  13638. main() function, because it'll take care of shutting down whenever you return
  13639. from the main() call.
  13640. @see ScopedJuceInitialiser_GUI
  13641. */
  13642. class ScopedJuceInitialiser_NonGUI
  13643. {
  13644. public:
  13645. /** The constructor simply calls initialiseJuce_NonGUI(). */
  13646. ScopedJuceInitialiser_NonGUI() { initialiseJuce_NonGUI(); }
  13647. /** The destructor simply calls shutdownJuce_NonGUI(). */
  13648. ~ScopedJuceInitialiser_NonGUI() { shutdownJuce_NonGUI(); }
  13649. };
  13650. /** A utility object that helps you initialise and shutdown Juce correctly
  13651. using an RAII pattern.
  13652. When an instance of this class is created, it calls initialiseJuce_GUI(),
  13653. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  13654. make sure that these functions are matched correctly.
  13655. This class is particularly handy to use at the beginning of a console app's
  13656. main() function, because it'll take care of shutting down whenever you return
  13657. from the main() call.
  13658. @see ScopedJuceInitialiser_NonGUI
  13659. */
  13660. class ScopedJuceInitialiser_GUI
  13661. {
  13662. public:
  13663. /** The constructor simply calls initialiseJuce_GUI(). */
  13664. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  13665. /** The destructor simply calls shutdownJuce_GUI(). */
  13666. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  13667. };
  13668. /*
  13669. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  13670. AppSubClass is the name of a class derived from JUCEApplication.
  13671. See the JUCEApplication class documentation (juce_Application.h) for more details.
  13672. */
  13673. #if JUCE_ANDROID
  13674. #define START_JUCE_APPLICATION(AppClass) \
  13675. JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); }
  13676. #elif defined (JUCE_GCC) || defined (__MWERKS__)
  13677. #define START_JUCE_APPLICATION(AppClass) \
  13678. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13679. int main (int argc, char* argv[]) \
  13680. { \
  13681. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13682. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv); \
  13683. }
  13684. #elif JUCE_WINDOWS
  13685. #ifdef _CONSOLE
  13686. #define START_JUCE_APPLICATION(AppClass) \
  13687. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13688. int main (int, char* argv[]) \
  13689. { \
  13690. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13691. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13692. }
  13693. #elif ! defined (_AFXDLL)
  13694. #ifdef _WINDOWS_
  13695. #define START_JUCE_APPLICATION(AppClass) \
  13696. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13697. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  13698. { \
  13699. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13700. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13701. }
  13702. #else
  13703. #define START_JUCE_APPLICATION(AppClass) \
  13704. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13705. int __stdcall WinMain (int, int, const char*, int) \
  13706. { \
  13707. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13708. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13709. }
  13710. #endif
  13711. #endif
  13712. #endif
  13713. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  13714. /*** End of inlined file: juce_Initialisation.h ***/
  13715. #endif
  13716. #ifndef __JUCE_LOGGER_JUCEHEADER__
  13717. #endif
  13718. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13719. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  13720. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13721. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13722. /** A timer for measuring performance of code and dumping the results to a file.
  13723. e.g. @code
  13724. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  13725. for (;;)
  13726. {
  13727. pc.start();
  13728. doSomethingFishy();
  13729. pc.stop();
  13730. }
  13731. @endcode
  13732. In this example, the time of each period between calling start/stop will be
  13733. measured and averaged over 50 runs, and the results printed to a file
  13734. every 50 times round the loop.
  13735. */
  13736. class JUCE_API PerformanceCounter
  13737. {
  13738. public:
  13739. /** Creates a PerformanceCounter object.
  13740. @param counterName the name used when printing out the statistics
  13741. @param runsPerPrintout the number of start/stop iterations before calling
  13742. printStatistics()
  13743. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  13744. the results are just written to the debugger output
  13745. */
  13746. PerformanceCounter (const String& counterName,
  13747. int runsPerPrintout = 100,
  13748. const File& loggingFile = File::nonexistent);
  13749. /** Destructor. */
  13750. ~PerformanceCounter();
  13751. /** Starts timing.
  13752. @see stop
  13753. */
  13754. void start();
  13755. /** Stops timing and prints out the results.
  13756. The number of iterations before doing a printout of the
  13757. results is set in the constructor.
  13758. @see start
  13759. */
  13760. void stop();
  13761. /** Dumps the current metrics to the debugger output and to a file.
  13762. As well as using Logger::outputDebugString to print the results,
  13763. this will write then to the file specified in the constructor (if
  13764. this was valid).
  13765. */
  13766. void printStatistics();
  13767. private:
  13768. String name;
  13769. int numRuns, runsPerPrint;
  13770. double totalTime;
  13771. int64 started;
  13772. File outputFile;
  13773. };
  13774. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13775. /*** End of inlined file: juce_PerformanceCounter.h ***/
  13776. #endif
  13777. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  13778. #endif
  13779. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13780. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  13781. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13782. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13783. /**
  13784. A collection of miscellaneous platform-specific utilities.
  13785. */
  13786. class JUCE_API PlatformUtilities
  13787. {
  13788. public:
  13789. /** Plays the operating system's default alert 'beep' sound. */
  13790. static void beep();
  13791. /** Tries to launch the system's default reader for a given file or URL. */
  13792. static bool openDocument (const String& documentURL, const String& parameters);
  13793. /** Tries to launch the system's default email app to let the user create an email.
  13794. */
  13795. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  13796. const String& emailSubject,
  13797. const String& bodyText,
  13798. const StringArray& filesToAttach);
  13799. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  13800. /** MAC ONLY - Turns a Core CF String into a juce one. */
  13801. static const String cfStringToJuceString (CFStringRef cfString);
  13802. /** MAC ONLY - Turns a juce string into a Core CF one. */
  13803. static CFStringRef juceStringToCFString (const String& s);
  13804. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  13805. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  13806. /** MAC ONLY - Turns an FSRef into a juce string path. */
  13807. static const String makePathFromFSRef (FSRef* file);
  13808. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  13809. their precomposed equivalents.
  13810. */
  13811. static const String convertToPrecomposedUnicode (const String& s);
  13812. /** MAC ONLY - Gets the type of a file from the file's resources. */
  13813. static OSType getTypeOfFile (const String& filename);
  13814. /** MAC ONLY - Returns true if this file is actually a bundle. */
  13815. static bool isBundle (const String& filename);
  13816. /** MAC ONLY - Adds an item to the dock */
  13817. static void addItemToDock (const File& file);
  13818. /** MAC ONLY - Returns the current OS version number.
  13819. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  13820. */
  13821. static int getOSXMinorVersionNumber();
  13822. #endif
  13823. #if JUCE_WINDOWS || DOXYGEN
  13824. // Some registry helper functions:
  13825. /** WIN32 ONLY - Returns a string from the registry.
  13826. The path is a string for the entire path of a value in the registry,
  13827. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  13828. */
  13829. static const String getRegistryValue (const String& regValuePath,
  13830. const String& defaultValue = String::empty);
  13831. /** WIN32 ONLY - Sets a registry value as a string.
  13832. This will take care of creating any groups needed to get to the given
  13833. registry value.
  13834. */
  13835. static void setRegistryValue (const String& regValuePath,
  13836. const String& value);
  13837. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  13838. static bool registryValueExists (const String& regValuePath);
  13839. /** WIN32 ONLY - Deletes a registry value. */
  13840. static void deleteRegistryValue (const String& regValuePath);
  13841. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  13842. static void deleteRegistryKey (const String& regKeyPath);
  13843. /** WIN32 ONLY - Creates a file association in the registry.
  13844. This lets you set the exe that should be launched by a given file extension.
  13845. @param fileExtension the file extension to associate, including the
  13846. initial dot, e.g. ".txt"
  13847. @param symbolicDescription a space-free short token to identify the file type
  13848. @param fullDescription a human-readable description of the file type
  13849. @param targetExecutable the executable that should be launched
  13850. @param iconResourceNumber the icon that gets displayed for the file type will be
  13851. found by looking up this resource number in the
  13852. executable. Pass 0 here to not use an icon
  13853. */
  13854. static void registerFileAssociation (const String& fileExtension,
  13855. const String& symbolicDescription,
  13856. const String& fullDescription,
  13857. const File& targetExecutable,
  13858. int iconResourceNumber);
  13859. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  13860. In a normal Juce application this will be set to the module handle
  13861. of the application executable.
  13862. If you're writing a DLL using Juce and plan to use any Juce messaging or
  13863. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  13864. to set the correct module handle in your DllMain() function, because
  13865. the win32 system relies on the correct instance handle when opening windows.
  13866. */
  13867. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() noexcept;
  13868. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  13869. @see getCurrentModuleInstanceHandle()
  13870. */
  13871. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) noexcept;
  13872. /** WIN32 ONLY - Gets the command-line params as a string.
  13873. This is needed to avoid unicode problems with the argc type params.
  13874. */
  13875. static const String JUCE_CALLTYPE getCurrentCommandLineParams();
  13876. #endif
  13877. /** Clears the floating point unit's flags.
  13878. Only has an effect under win32, currently.
  13879. */
  13880. static void fpuReset();
  13881. #if JUCE_LINUX || JUCE_WINDOWS
  13882. /** Loads a dynamically-linked library into the process's address space.
  13883. @param pathOrFilename the platform-dependent name and search path
  13884. @returns a handle which can be used by getProcedureEntryPoint(), or
  13885. zero if it fails.
  13886. @see freeDynamicLibrary, getProcedureEntryPoint
  13887. */
  13888. static void* loadDynamicLibrary (const String& pathOrFilename);
  13889. /** Frees a dynamically-linked library.
  13890. @param libraryHandle a handle created by loadDynamicLibrary
  13891. @see loadDynamicLibrary, getProcedureEntryPoint
  13892. */
  13893. static void freeDynamicLibrary (void* libraryHandle);
  13894. /** Finds a procedure call in a dynamically-linked library.
  13895. @param libraryHandle a library handle returned by loadDynamicLibrary
  13896. @param procedureName the name of the procedure call to try to load
  13897. @returns a pointer to the function if found, or 0 if it fails
  13898. @see loadDynamicLibrary
  13899. */
  13900. static void* getProcedureEntryPoint (void* libraryHandle,
  13901. const String& procedureName);
  13902. #endif
  13903. private:
  13904. PlatformUtilities();
  13905. JUCE_DECLARE_NON_COPYABLE (PlatformUtilities);
  13906. };
  13907. #if JUCE_MAC || JUCE_IOS
  13908. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object using RAII.
  13909. */
  13910. class JUCE_API ScopedAutoReleasePool
  13911. {
  13912. public:
  13913. ScopedAutoReleasePool();
  13914. ~ScopedAutoReleasePool();
  13915. private:
  13916. void* pool;
  13917. JUCE_DECLARE_NON_COPYABLE (ScopedAutoReleasePool);
  13918. };
  13919. #define JUCE_AUTORELEASEPOOL const JUCE_NAMESPACE::ScopedAutoReleasePool pool;
  13920. #else
  13921. #define JUCE_AUTORELEASEPOOL
  13922. #endif
  13923. #if JUCE_LINUX
  13924. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  13925. using an RAII approach.
  13926. */
  13927. class ScopedXLock
  13928. {
  13929. public:
  13930. /** Creating a ScopedXLock object locks the X display.
  13931. This uses XLockDisplay() to grab the display that Juce is using.
  13932. */
  13933. ScopedXLock();
  13934. /** Deleting a ScopedXLock object unlocks the X display.
  13935. This calls XUnlockDisplay() to release the lock.
  13936. */
  13937. ~ScopedXLock();
  13938. };
  13939. #endif
  13940. #if JUCE_MAC
  13941. /**
  13942. A wrapper class for picking up events from an Apple IR remote control device.
  13943. To use it, just create a subclass of this class, implementing the buttonPressed()
  13944. callback, then call start() and stop() to start or stop receiving events.
  13945. */
  13946. class JUCE_API AppleRemoteDevice
  13947. {
  13948. public:
  13949. AppleRemoteDevice();
  13950. virtual ~AppleRemoteDevice();
  13951. /** The set of buttons that may be pressed.
  13952. @see buttonPressed
  13953. */
  13954. enum ButtonType
  13955. {
  13956. menuButton = 0, /**< The menu button (if it's held for a short time). */
  13957. playButton, /**< The play button. */
  13958. plusButton, /**< The plus or volume-up button. */
  13959. minusButton, /**< The minus or volume-down button. */
  13960. rightButton, /**< The right button (if it's held for a short time). */
  13961. leftButton, /**< The left button (if it's held for a short time). */
  13962. rightButton_Long, /**< The right button (if it's held for a long time). */
  13963. leftButton_Long, /**< The menu button (if it's held for a long time). */
  13964. menuButton_Long, /**< The menu button (if it's held for a long time). */
  13965. playButtonSleepMode,
  13966. switched
  13967. };
  13968. /** Override this method to receive the callback about a button press.
  13969. The callback will happen on the application's message thread.
  13970. Some buttons trigger matching up and down events, in which the isDown parameter
  13971. will be true and then false. Others only send a single event when the
  13972. button is pressed.
  13973. */
  13974. virtual void buttonPressed (ButtonType buttonId, bool isDown) = 0;
  13975. /** Starts the device running and responding to events.
  13976. Returns true if it managed to open the device.
  13977. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  13978. and will not be available to any other part of the system. If
  13979. false, it will be shared with other apps.
  13980. @see stop
  13981. */
  13982. bool start (bool inExclusiveMode);
  13983. /** Stops the device running.
  13984. @see start
  13985. */
  13986. void stop();
  13987. /** Returns true if the device has been started successfully.
  13988. */
  13989. bool isActive() const;
  13990. /** Returns the ID number of the remote, if it has sent one.
  13991. */
  13992. int getRemoteId() const { return remoteId; }
  13993. /** @internal */
  13994. void handleCallbackInternal();
  13995. private:
  13996. void* device;
  13997. void* queue;
  13998. int remoteId;
  13999. bool open (bool openInExclusiveMode);
  14000. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AppleRemoteDevice);
  14001. };
  14002. #endif
  14003. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  14004. /*** End of inlined file: juce_PlatformUtilities.h ***/
  14005. #endif
  14006. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  14007. #endif
  14008. #ifndef __JUCE_RESULT_JUCEHEADER__
  14009. #endif
  14010. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  14011. /*** Start of inlined file: juce_Singleton.h ***/
  14012. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  14013. #define __JUCE_SINGLETON_JUCEHEADER__
  14014. /**
  14015. Macro to declare member variables and methods for a singleton class.
  14016. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  14017. to the class's definition.
  14018. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  14019. implementation code.
  14020. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  14021. destructor, in case it is deleted by other means than deleteInstance()
  14022. Clients can then call the static method MyClass::getInstance() to get a pointer
  14023. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  14024. no instance currently exists.
  14025. e.g. @code
  14026. class MySingleton
  14027. {
  14028. public:
  14029. MySingleton()
  14030. {
  14031. }
  14032. ~MySingleton()
  14033. {
  14034. // this ensures that no dangling pointers are left when the
  14035. // singleton is deleted.
  14036. clearSingletonInstance();
  14037. }
  14038. juce_DeclareSingleton (MySingleton, false)
  14039. };
  14040. juce_ImplementSingleton (MySingleton)
  14041. // example of usage:
  14042. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  14043. ...
  14044. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  14045. @endcode
  14046. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  14047. than once during the process's lifetime - i.e. after you've created and deleted the
  14048. object, getInstance() will refuse to create another one. This can be useful to stop
  14049. objects being accidentally re-created during your app's shutdown code.
  14050. If you know that your object will only be created and deleted by a single thread, you
  14051. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  14052. of this one.
  14053. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  14054. */
  14055. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  14056. \
  14057. static classname* _singletonInstance; \
  14058. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  14059. \
  14060. static classname* JUCE_CALLTYPE getInstance() \
  14061. { \
  14062. if (_singletonInstance == nullptr) \
  14063. {\
  14064. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  14065. \
  14066. if (_singletonInstance == nullptr) \
  14067. { \
  14068. static bool alreadyInside = false; \
  14069. static bool createdOnceAlready = false; \
  14070. \
  14071. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  14072. jassert (! problem); \
  14073. if (! problem) \
  14074. { \
  14075. createdOnceAlready = true; \
  14076. alreadyInside = true; \
  14077. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  14078. alreadyInside = false; \
  14079. \
  14080. _singletonInstance = newObject; \
  14081. } \
  14082. } \
  14083. } \
  14084. \
  14085. return _singletonInstance; \
  14086. } \
  14087. \
  14088. static inline classname* JUCE_CALLTYPE getInstanceWithoutCreating() noexcept\
  14089. { \
  14090. return _singletonInstance; \
  14091. } \
  14092. \
  14093. static void JUCE_CALLTYPE deleteInstance() \
  14094. { \
  14095. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  14096. if (_singletonInstance != nullptr) \
  14097. { \
  14098. classname* const old = _singletonInstance; \
  14099. _singletonInstance = nullptr; \
  14100. delete old; \
  14101. } \
  14102. } \
  14103. \
  14104. void clearSingletonInstance() noexcept\
  14105. { \
  14106. if (_singletonInstance == this) \
  14107. _singletonInstance = nullptr; \
  14108. }
  14109. /** This is a counterpart to the juce_DeclareSingleton macro.
  14110. After adding the juce_DeclareSingleton to the class definition, this macro has
  14111. to be used in the cpp file.
  14112. */
  14113. #define juce_ImplementSingleton(classname) \
  14114. \
  14115. classname* classname::_singletonInstance = nullptr; \
  14116. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  14117. /**
  14118. Macro to declare member variables and methods for a singleton class.
  14119. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  14120. section to make access to it thread-safe. If you know that your object will
  14121. only ever be created or deleted by a single thread, then this is a
  14122. more efficient version to use.
  14123. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  14124. than once during the process's lifetime - i.e. after you've created and deleted the
  14125. object, getInstance() will refuse to create another one. This can be useful to stop
  14126. objects being accidentally re-created during your app's shutdown code.
  14127. See the documentation for juce_DeclareSingleton for more information about
  14128. how to use it, the only difference being that you have to use
  14129. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  14130. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  14131. */
  14132. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  14133. \
  14134. static classname* _singletonInstance; \
  14135. \
  14136. static classname* getInstance() \
  14137. { \
  14138. if (_singletonInstance == nullptr) \
  14139. { \
  14140. static bool alreadyInside = false; \
  14141. static bool createdOnceAlready = false; \
  14142. \
  14143. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  14144. jassert (! problem); \
  14145. if (! problem) \
  14146. { \
  14147. createdOnceAlready = true; \
  14148. alreadyInside = true; \
  14149. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  14150. alreadyInside = false; \
  14151. \
  14152. _singletonInstance = newObject; \
  14153. } \
  14154. } \
  14155. \
  14156. return _singletonInstance; \
  14157. } \
  14158. \
  14159. static inline classname* getInstanceWithoutCreating() noexcept\
  14160. { \
  14161. return _singletonInstance; \
  14162. } \
  14163. \
  14164. static void deleteInstance() \
  14165. { \
  14166. if (_singletonInstance != nullptr) \
  14167. { \
  14168. classname* const old = _singletonInstance; \
  14169. _singletonInstance = nullptr; \
  14170. delete old; \
  14171. } \
  14172. } \
  14173. \
  14174. void clearSingletonInstance() noexcept\
  14175. { \
  14176. if (_singletonInstance == this) \
  14177. _singletonInstance = nullptr; \
  14178. }
  14179. /**
  14180. Macro to declare member variables and methods for a singleton class.
  14181. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  14182. for recursion or repeated instantiation. It's intended for use as a lightweight
  14183. version of a singleton, where you're using it in very straightforward
  14184. circumstances and don't need the extra checking.
  14185. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  14186. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  14187. See the documentation for juce_DeclareSingleton for more information about
  14188. how to use it, the only difference being that you have to use
  14189. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  14190. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  14191. */
  14192. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  14193. \
  14194. static classname* _singletonInstance; \
  14195. \
  14196. static classname* getInstance() \
  14197. { \
  14198. if (_singletonInstance == nullptr) \
  14199. _singletonInstance = new classname(); \
  14200. \
  14201. return _singletonInstance; \
  14202. } \
  14203. \
  14204. static inline classname* getInstanceWithoutCreating() noexcept\
  14205. { \
  14206. return _singletonInstance; \
  14207. } \
  14208. \
  14209. static void deleteInstance() \
  14210. { \
  14211. if (_singletonInstance != nullptr) \
  14212. { \
  14213. classname* const old = _singletonInstance; \
  14214. _singletonInstance = nullptr; \
  14215. delete old; \
  14216. } \
  14217. } \
  14218. \
  14219. void clearSingletonInstance() noexcept\
  14220. { \
  14221. if (_singletonInstance == this) \
  14222. _singletonInstance = nullptr; \
  14223. }
  14224. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  14225. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  14226. to the class definition, this macro has to be used somewhere in the cpp file.
  14227. */
  14228. #define juce_ImplementSingleton_SingleThreaded(classname) \
  14229. \
  14230. classname* classname::_singletonInstance = nullptr;
  14231. #endif // __JUCE_SINGLETON_JUCEHEADER__
  14232. /*** End of inlined file: juce_Singleton.h ***/
  14233. #endif
  14234. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  14235. #endif
  14236. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  14237. /*** Start of inlined file: juce_SystemStats.h ***/
  14238. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  14239. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  14240. /**
  14241. Contains methods for finding out about the current hardware and OS configuration.
  14242. */
  14243. class JUCE_API SystemStats
  14244. {
  14245. public:
  14246. /** Returns the current version of JUCE,
  14247. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  14248. */
  14249. static const String getJUCEVersion();
  14250. /** The set of possible results of the getOperatingSystemType() method.
  14251. */
  14252. enum OperatingSystemType
  14253. {
  14254. UnknownOS = 0,
  14255. MacOSX = 0x1000,
  14256. Linux = 0x2000,
  14257. Android = 0x3000,
  14258. Win95 = 0x4001,
  14259. Win98 = 0x4002,
  14260. WinNT351 = 0x4103,
  14261. WinNT40 = 0x4104,
  14262. Win2000 = 0x4105,
  14263. WinXP = 0x4106,
  14264. WinVista = 0x4107,
  14265. Windows7 = 0x4108,
  14266. Windows = 0x4000, /**< To test whether any version of Windows is running,
  14267. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  14268. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  14269. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  14270. };
  14271. /** Returns the type of operating system we're running on.
  14272. @returns one of the values from the OperatingSystemType enum.
  14273. @see getOperatingSystemName
  14274. */
  14275. static OperatingSystemType getOperatingSystemType();
  14276. /** Returns the name of the type of operating system we're running on.
  14277. @returns a string describing the OS type.
  14278. @see getOperatingSystemType
  14279. */
  14280. static const String getOperatingSystemName();
  14281. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  14282. */
  14283. static bool isOperatingSystem64Bit();
  14284. /** Returns the current user's name, if available.
  14285. @see getFullUserName()
  14286. */
  14287. static const String getLogonName();
  14288. /** Returns the current user's full name, if available.
  14289. On some OSes, this may just return the same value as getLogonName().
  14290. @see getLogonName()
  14291. */
  14292. static const String getFullUserName();
  14293. /** Returns the host-name of the computer. */
  14294. static const String getComputerName();
  14295. // CPU and memory information..
  14296. /** Returns the approximate CPU speed.
  14297. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  14298. what year you're reading this...)
  14299. */
  14300. static int getCpuSpeedInMegaherz();
  14301. /** Returns a string to indicate the CPU vendor.
  14302. Might not be known on some systems.
  14303. */
  14304. static const String getCpuVendor();
  14305. /** Checks whether Intel MMX instructions are available. */
  14306. static bool hasMMX() noexcept { return cpuFlags.hasMMX; }
  14307. /** Checks whether Intel SSE instructions are available. */
  14308. static bool hasSSE() noexcept { return cpuFlags.hasSSE; }
  14309. /** Checks whether Intel SSE2 instructions are available. */
  14310. static bool hasSSE2() noexcept { return cpuFlags.hasSSE2; }
  14311. /** Checks whether AMD 3DNOW instructions are available. */
  14312. static bool has3DNow() noexcept { return cpuFlags.has3DNow; }
  14313. /** Returns the number of CPUs. */
  14314. static int getNumCpus() noexcept { return cpuFlags.numCpus; }
  14315. /** Finds out how much RAM is in the machine.
  14316. @returns the approximate number of megabytes of memory, or zero if
  14317. something goes wrong when finding out.
  14318. */
  14319. static int getMemorySizeInMegabytes();
  14320. /** Returns the system page-size.
  14321. This is only used by programmers with beards.
  14322. */
  14323. static int getPageSize();
  14324. // not-for-public-use platform-specific method gets called at startup to initialise things.
  14325. static void initialiseStats();
  14326. private:
  14327. struct CPUFlags
  14328. {
  14329. int numCpus;
  14330. bool hasMMX : 1;
  14331. bool hasSSE : 1;
  14332. bool hasSSE2 : 1;
  14333. bool has3DNow : 1;
  14334. };
  14335. static CPUFlags cpuFlags;
  14336. SystemStats();
  14337. JUCE_DECLARE_NON_COPYABLE (SystemStats);
  14338. };
  14339. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  14340. /*** End of inlined file: juce_SystemStats.h ***/
  14341. #endif
  14342. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  14343. #endif
  14344. #ifndef __JUCE_TIME_JUCEHEADER__
  14345. #endif
  14346. #ifndef __JUCE_UUID_JUCEHEADER__
  14347. /*** Start of inlined file: juce_Uuid.h ***/
  14348. #ifndef __JUCE_UUID_JUCEHEADER__
  14349. #define __JUCE_UUID_JUCEHEADER__
  14350. /**
  14351. A universally unique 128-bit identifier.
  14352. This class generates very random unique numbers based on the system time
  14353. and MAC addresses if any are available. It's extremely unlikely that two identical
  14354. UUIDs would ever be created by chance.
  14355. The class includes methods for saving the ID as a string or as raw binary data.
  14356. */
  14357. class JUCE_API Uuid
  14358. {
  14359. public:
  14360. /** Creates a new unique ID. */
  14361. Uuid();
  14362. /** Destructor. */
  14363. ~Uuid() noexcept;
  14364. /** Creates a copy of another UUID. */
  14365. Uuid (const Uuid& other);
  14366. /** Copies another UUID. */
  14367. Uuid& operator= (const Uuid& other);
  14368. /** Returns true if the ID is zero. */
  14369. bool isNull() const noexcept;
  14370. /** Compares two UUIDs. */
  14371. bool operator== (const Uuid& other) const;
  14372. /** Compares two UUIDs. */
  14373. bool operator!= (const Uuid& other) const;
  14374. /** Returns a stringified version of this UUID.
  14375. A Uuid object can later be reconstructed from this string using operator= or
  14376. the constructor that takes a string parameter.
  14377. @returns a 32 character hex string.
  14378. */
  14379. const String toString() const;
  14380. /** Creates an ID from an encoded string version.
  14381. @see toString
  14382. */
  14383. Uuid (const String& uuidString);
  14384. /** Copies from a stringified UUID.
  14385. The string passed in should be one that was created with the toString() method.
  14386. */
  14387. Uuid& operator= (const String& uuidString);
  14388. /** Returns a pointer to the internal binary representation of the ID.
  14389. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  14390. the constructor or operator= method that takes an array of uint8s.
  14391. */
  14392. const uint8* getRawData() const noexcept { return value.asBytes; }
  14393. /** Creates a UUID from a 16-byte array.
  14394. @see getRawData
  14395. */
  14396. Uuid (const uint8* rawData);
  14397. /** Sets this UUID from 16-bytes of raw data. */
  14398. Uuid& operator= (const uint8* rawData);
  14399. private:
  14400. #ifndef DOXYGEN
  14401. union
  14402. {
  14403. uint8 asBytes [16];
  14404. int asInt[4];
  14405. int64 asInt64[2];
  14406. } value;
  14407. #endif
  14408. JUCE_LEAK_DETECTOR (Uuid);
  14409. };
  14410. #endif // __JUCE_UUID_JUCEHEADER__
  14411. /*** End of inlined file: juce_Uuid.h ***/
  14412. #endif
  14413. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  14414. /*** Start of inlined file: juce_BlowFish.h ***/
  14415. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  14416. #define __JUCE_BLOWFISH_JUCEHEADER__
  14417. /**
  14418. BlowFish encryption class.
  14419. */
  14420. class JUCE_API BlowFish
  14421. {
  14422. public:
  14423. /** Creates an object that can encode/decode based on the specified key.
  14424. The key data can be up to 72 bytes long.
  14425. */
  14426. BlowFish (const void* keyData, int keyBytes);
  14427. /** Creates a copy of another blowfish object. */
  14428. BlowFish (const BlowFish& other);
  14429. /** Copies another blowfish object. */
  14430. BlowFish& operator= (const BlowFish& other);
  14431. /** Destructor. */
  14432. ~BlowFish();
  14433. /** Encrypts a pair of 32-bit integers. */
  14434. void encrypt (uint32& data1, uint32& data2) const noexcept;
  14435. /** Decrypts a pair of 32-bit integers. */
  14436. void decrypt (uint32& data1, uint32& data2) const noexcept;
  14437. private:
  14438. uint32 p[18];
  14439. HeapBlock <uint32> s[4];
  14440. uint32 F (uint32 x) const noexcept;
  14441. JUCE_LEAK_DETECTOR (BlowFish);
  14442. };
  14443. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  14444. /*** End of inlined file: juce_BlowFish.h ***/
  14445. #endif
  14446. #ifndef __JUCE_MD5_JUCEHEADER__
  14447. /*** Start of inlined file: juce_MD5.h ***/
  14448. #ifndef __JUCE_MD5_JUCEHEADER__
  14449. #define __JUCE_MD5_JUCEHEADER__
  14450. /**
  14451. MD5 checksum class.
  14452. Create one of these with a block of source data or a string, and it calculates the
  14453. MD5 checksum of that data.
  14454. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  14455. */
  14456. class JUCE_API MD5
  14457. {
  14458. public:
  14459. /** Creates a null MD5 object. */
  14460. MD5();
  14461. /** Creates a copy of another MD5. */
  14462. MD5 (const MD5& other);
  14463. /** Copies another MD5. */
  14464. MD5& operator= (const MD5& other);
  14465. /** Creates a checksum for a block of binary data. */
  14466. explicit MD5 (const MemoryBlock& data);
  14467. /** Creates a checksum for a block of binary data. */
  14468. MD5 (const void* data, size_t numBytes);
  14469. /** Creates a checksum for a string.
  14470. Note that this operates on the string as a block of unicode characters, so the
  14471. result you get will differ from the value you'd get if the string was treated
  14472. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  14473. of this method with a checksum created by a different framework, which may have
  14474. used a different encoding.
  14475. */
  14476. explicit MD5 (const String& text);
  14477. /** Creates a checksum for the input from a stream.
  14478. This will read up to the given number of bytes from the stream, and produce the
  14479. checksum of that. If the number of bytes to read is negative, it'll read
  14480. until the stream is exhausted.
  14481. */
  14482. MD5 (InputStream& input, int64 numBytesToRead = -1);
  14483. /** Creates a checksum for a file. */
  14484. explicit MD5 (const File& file);
  14485. /** Destructor. */
  14486. ~MD5();
  14487. /** Returns the checksum as a 16-byte block of data. */
  14488. const MemoryBlock getRawChecksumData() const;
  14489. /** Returns the checksum as a 32-digit hex string. */
  14490. const String toHexString() const;
  14491. /** Compares this to another MD5. */
  14492. bool operator== (const MD5& other) const;
  14493. /** Compares this to another MD5. */
  14494. bool operator!= (const MD5& other) const;
  14495. private:
  14496. uint8 result [16];
  14497. struct ProcessContext
  14498. {
  14499. uint8 buffer [64];
  14500. uint32 state [4];
  14501. uint32 count [2];
  14502. ProcessContext();
  14503. void processBlock (const void* data, size_t dataSize);
  14504. void transform (const void* buffer);
  14505. void finish (void* result);
  14506. };
  14507. void processStream (InputStream& input, int64 numBytesToRead);
  14508. JUCE_LEAK_DETECTOR (MD5);
  14509. };
  14510. #endif // __JUCE_MD5_JUCEHEADER__
  14511. /*** End of inlined file: juce_MD5.h ***/
  14512. #endif
  14513. #ifndef __JUCE_PRIMES_JUCEHEADER__
  14514. /*** Start of inlined file: juce_Primes.h ***/
  14515. #ifndef __JUCE_PRIMES_JUCEHEADER__
  14516. #define __JUCE_PRIMES_JUCEHEADER__
  14517. /*** Start of inlined file: juce_BigInteger.h ***/
  14518. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  14519. #define __JUCE_BIGINTEGER_JUCEHEADER__
  14520. class MemoryBlock;
  14521. /**
  14522. An arbitrarily large integer class.
  14523. A BigInteger can be used in a similar way to a normal integer, but has no size
  14524. limit (except for memory and performance constraints).
  14525. Negative values are possible, but the value isn't stored as 2s-complement, so
  14526. be careful if you use negative values and look at the values of individual bits.
  14527. */
  14528. class JUCE_API BigInteger
  14529. {
  14530. public:
  14531. /** Creates an empty BigInteger */
  14532. BigInteger();
  14533. /** Creates a BigInteger containing an integer value in its low bits.
  14534. The low 32 bits of the number are initialised with this value.
  14535. */
  14536. BigInteger (uint32 value);
  14537. /** Creates a BigInteger containing an integer value in its low bits.
  14538. The low 32 bits of the number are initialised with the absolute value
  14539. passed in, and its sign is set to reflect the sign of the number.
  14540. */
  14541. BigInteger (int32 value);
  14542. /** Creates a BigInteger containing an integer value in its low bits.
  14543. The low 64 bits of the number are initialised with the absolute value
  14544. passed in, and its sign is set to reflect the sign of the number.
  14545. */
  14546. BigInteger (int64 value);
  14547. /** Creates a copy of another BigInteger. */
  14548. BigInteger (const BigInteger& other);
  14549. /** Destructor. */
  14550. ~BigInteger();
  14551. /** Copies another BigInteger onto this one. */
  14552. BigInteger& operator= (const BigInteger& other);
  14553. /** Swaps the internal contents of this with another object. */
  14554. void swapWith (BigInteger& other) noexcept;
  14555. /** Returns the value of a specified bit in the number.
  14556. If the index is out-of-range, the result will be false.
  14557. */
  14558. bool operator[] (int bit) const noexcept;
  14559. /** Returns true if no bits are set. */
  14560. bool isZero() const noexcept;
  14561. /** Returns true if the value is 1. */
  14562. bool isOne() const noexcept;
  14563. /** Attempts to get the lowest bits of the value as an integer.
  14564. If the value is bigger than the integer limits, this will return only the lower bits.
  14565. */
  14566. int toInteger() const noexcept;
  14567. /** Resets the value to 0. */
  14568. void clear();
  14569. /** Clears a particular bit in the number. */
  14570. void clearBit (int bitNumber) noexcept;
  14571. /** Sets a specified bit to 1. */
  14572. void setBit (int bitNumber);
  14573. /** Sets or clears a specified bit. */
  14574. void setBit (int bitNumber, bool shouldBeSet);
  14575. /** Sets a range of bits to be either on or off.
  14576. @param startBit the first bit to change
  14577. @param numBits the number of bits to change
  14578. @param shouldBeSet whether to turn these bits on or off
  14579. */
  14580. void setRange (int startBit, int numBits, bool shouldBeSet);
  14581. /** Inserts a bit an a given position, shifting up any bits above it. */
  14582. void insertBit (int bitNumber, bool shouldBeSet);
  14583. /** Returns a range of bits as a new BigInteger.
  14584. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  14585. @see getBitRangeAsInt
  14586. */
  14587. const BigInteger getBitRange (int startBit, int numBits) const;
  14588. /** Returns a range of bits as an integer value.
  14589. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  14590. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  14591. getBitRange().
  14592. */
  14593. int getBitRangeAsInt (int startBit, int numBits) const noexcept;
  14594. /** Sets a range of bits to an integer value.
  14595. Copies the given integer onto a range of bits, starting at startBit,
  14596. and using up to numBits of the available bits.
  14597. */
  14598. void setBitRangeAsInt (int startBit, int numBits, uint32 valueToSet);
  14599. /** Shifts a section of bits left or right.
  14600. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  14601. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  14602. */
  14603. void shiftBits (int howManyBitsLeft, int startBit);
  14604. /** Returns the total number of set bits in the value. */
  14605. int countNumberOfSetBits() const noexcept;
  14606. /** Looks for the index of the next set bit after a given starting point.
  14607. This searches from startIndex (inclusive) upwards for the first set bit,
  14608. and returns its index. If no set bits are found, it returns -1.
  14609. */
  14610. int findNextSetBit (int startIndex = 0) const noexcept;
  14611. /** Looks for the index of the next clear bit after a given starting point.
  14612. This searches from startIndex (inclusive) upwards for the first clear bit,
  14613. and returns its index.
  14614. */
  14615. int findNextClearBit (int startIndex = 0) const noexcept;
  14616. /** Returns the index of the highest set bit in the number.
  14617. If the value is zero, this will return -1.
  14618. */
  14619. int getHighestBit() const noexcept;
  14620. // All the standard arithmetic ops...
  14621. BigInteger& operator+= (const BigInteger& other);
  14622. BigInteger& operator-= (const BigInteger& other);
  14623. BigInteger& operator*= (const BigInteger& other);
  14624. BigInteger& operator/= (const BigInteger& other);
  14625. BigInteger& operator|= (const BigInteger& other);
  14626. BigInteger& operator&= (const BigInteger& other);
  14627. BigInteger& operator^= (const BigInteger& other);
  14628. BigInteger& operator%= (const BigInteger& other);
  14629. BigInteger& operator<<= (int numBitsToShift);
  14630. BigInteger& operator>>= (int numBitsToShift);
  14631. BigInteger& operator++();
  14632. BigInteger& operator--();
  14633. const BigInteger operator++ (int);
  14634. const BigInteger operator-- (int);
  14635. const BigInteger operator-() const;
  14636. const BigInteger operator+ (const BigInteger& other) const;
  14637. const BigInteger operator- (const BigInteger& other) const;
  14638. const BigInteger operator* (const BigInteger& other) const;
  14639. const BigInteger operator/ (const BigInteger& other) const;
  14640. const BigInteger operator| (const BigInteger& other) const;
  14641. const BigInteger operator& (const BigInteger& other) const;
  14642. const BigInteger operator^ (const BigInteger& other) const;
  14643. const BigInteger operator% (const BigInteger& other) const;
  14644. const BigInteger operator<< (int numBitsToShift) const;
  14645. const BigInteger operator>> (int numBitsToShift) const;
  14646. bool operator== (const BigInteger& other) const noexcept;
  14647. bool operator!= (const BigInteger& other) const noexcept;
  14648. bool operator< (const BigInteger& other) const noexcept;
  14649. bool operator<= (const BigInteger& other) const noexcept;
  14650. bool operator> (const BigInteger& other) const noexcept;
  14651. bool operator>= (const BigInteger& other) const noexcept;
  14652. /** Does a signed comparison of two BigIntegers.
  14653. Return values are:
  14654. - 0 if the numbers are the same
  14655. - < 0 if this number is smaller than the other
  14656. - > 0 if this number is bigger than the other
  14657. */
  14658. int compare (const BigInteger& other) const noexcept;
  14659. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  14660. Return values are:
  14661. - 0 if the numbers are the same
  14662. - < 0 if this number is smaller than the other
  14663. - > 0 if this number is bigger than the other
  14664. */
  14665. int compareAbsolute (const BigInteger& other) const noexcept;
  14666. /** Divides this value by another one and returns the remainder.
  14667. This number is divided by other, leaving the quotient in this number,
  14668. with the remainder being copied to the other BigInteger passed in.
  14669. */
  14670. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  14671. /** Returns the largest value that will divide both this value and the one passed-in.
  14672. */
  14673. const BigInteger findGreatestCommonDivisor (BigInteger other) const;
  14674. /** Performs a combined exponent and modulo operation.
  14675. This BigInteger's value becomes (this ^ exponent) % modulus.
  14676. */
  14677. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  14678. /** Performs an inverse modulo on the value.
  14679. i.e. the result is (this ^ -1) mod (modulus).
  14680. */
  14681. void inverseModulo (const BigInteger& modulus);
  14682. /** Returns true if the value is less than zero.
  14683. @see setNegative, negate
  14684. */
  14685. bool isNegative() const noexcept;
  14686. /** Changes the sign of the number to be positive or negative.
  14687. @see isNegative, negate
  14688. */
  14689. void setNegative (bool shouldBeNegative) noexcept;
  14690. /** Inverts the sign of the number.
  14691. @see isNegative, setNegative
  14692. */
  14693. void negate() noexcept;
  14694. /** Converts the number to a string.
  14695. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14696. If minimumNumCharacters is greater than 0, the returned string will be
  14697. padded with leading zeros to reach at least that length.
  14698. */
  14699. const String toString (int base, int minimumNumCharacters = 1) const;
  14700. /** Reads the numeric value from a string.
  14701. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14702. Any invalid characters will be ignored.
  14703. */
  14704. void parseString (const String& text, int base);
  14705. /** Turns the number into a block of binary data.
  14706. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14707. of the number, and so on.
  14708. @see loadFromMemoryBlock
  14709. */
  14710. const MemoryBlock toMemoryBlock() const;
  14711. /** Converts a block of raw data into a number.
  14712. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14713. of the number, and so on.
  14714. @see toMemoryBlock
  14715. */
  14716. void loadFromMemoryBlock (const MemoryBlock& data);
  14717. private:
  14718. HeapBlock <uint32> values;
  14719. int numValues, highestBit;
  14720. bool negative;
  14721. void ensureSize (int numVals);
  14722. static const BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  14723. static inline int bitToIndex (const int bit) noexcept { return bit >> 5; }
  14724. static inline uint32 bitToMask (const int bit) noexcept { return 1 << (bit & 31); }
  14725. JUCE_LEAK_DETECTOR (BigInteger);
  14726. };
  14727. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  14728. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  14729. #ifndef DOXYGEN
  14730. // For backwards compatibility, BitArray is defined as an alias for BigInteger.
  14731. typedef BigInteger BitArray;
  14732. #endif
  14733. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  14734. /*** End of inlined file: juce_BigInteger.h ***/
  14735. /**
  14736. Prime number creation class.
  14737. This class contains static methods for generating and testing prime numbers.
  14738. @see BigInteger
  14739. */
  14740. class JUCE_API Primes
  14741. {
  14742. public:
  14743. /** Creates a random prime number with a given bit-length.
  14744. The certainty parameter specifies how many iterations to use when testing
  14745. for primality. A safe value might be anything over about 20-30.
  14746. The randomSeeds parameter lets you optionally pass it a set of values with
  14747. which to seed the random number generation, improving the security of the
  14748. keys generated.
  14749. */
  14750. static const BigInteger createProbablePrime (int bitLength,
  14751. int certainty,
  14752. const int* randomSeeds = 0,
  14753. int numRandomSeeds = 0);
  14754. /** Tests a number to see if it's prime.
  14755. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  14756. whether the number is prime.
  14757. The certainty parameter specifies how many iterations to use when testing - a
  14758. safe value might be anything over about 20-30.
  14759. */
  14760. static bool isProbablyPrime (const BigInteger& number, int certainty);
  14761. private:
  14762. Primes();
  14763. JUCE_DECLARE_NON_COPYABLE (Primes);
  14764. };
  14765. #endif // __JUCE_PRIMES_JUCEHEADER__
  14766. /*** End of inlined file: juce_Primes.h ***/
  14767. #endif
  14768. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14769. /*** Start of inlined file: juce_RSAKey.h ***/
  14770. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14771. #define __JUCE_RSAKEY_JUCEHEADER__
  14772. /**
  14773. RSA public/private key-pair encryption class.
  14774. An object of this type makes up one half of a public/private RSA key pair. Use the
  14775. createKeyPair() method to create a matching pair for encoding/decoding.
  14776. */
  14777. class JUCE_API RSAKey
  14778. {
  14779. public:
  14780. /** Creates a null key object.
  14781. Initialise a pair of objects for use with the createKeyPair() method.
  14782. */
  14783. RSAKey();
  14784. /** Loads a key from an encoded string representation.
  14785. This reloads a key from a string created by the toString() method.
  14786. */
  14787. explicit RSAKey (const String& stringRepresentation);
  14788. /** Destructor. */
  14789. ~RSAKey();
  14790. bool operator== (const RSAKey& other) const noexcept;
  14791. bool operator!= (const RSAKey& other) const noexcept;
  14792. /** Turns the key into a string representation.
  14793. This can be reloaded using the constructor that takes a string.
  14794. */
  14795. const String toString() const;
  14796. /** Encodes or decodes a value.
  14797. Call this on the public key object to encode some data, then use the matching
  14798. private key object to decode it.
  14799. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  14800. initialised correctly.
  14801. NOTE: This method dumbly applies this key to this data. If you encode some data
  14802. and then try to decode it with a key that doesn't match, this method will still
  14803. happily do its job and return true, but the result won't be what you were expecting.
  14804. It's your responsibility to check that the result is what you wanted.
  14805. */
  14806. bool applyToValue (BigInteger& value) const;
  14807. /** Creates a public/private key-pair.
  14808. Each key will perform one-way encryption that can only be reversed by
  14809. using the other key.
  14810. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  14811. sizes are more secure, but this method will take longer to execute.
  14812. The randomSeeds parameter lets you optionally pass it a set of values with
  14813. which to seed the random number generation, improving the security of the
  14814. keys generated. If you supply these, make sure you provide more than 2 values,
  14815. and the more your provide, the better the security.
  14816. */
  14817. static void createKeyPair (RSAKey& publicKey,
  14818. RSAKey& privateKey,
  14819. int numBits,
  14820. const int* randomSeeds = nullptr,
  14821. int numRandomSeeds = 0);
  14822. protected:
  14823. BigInteger part1, part2;
  14824. private:
  14825. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q);
  14826. JUCE_LEAK_DETECTOR (RSAKey);
  14827. };
  14828. #endif // __JUCE_RSAKEY_JUCEHEADER__
  14829. /*** End of inlined file: juce_RSAKey.h ***/
  14830. #endif
  14831. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14832. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  14833. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14834. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14835. /**
  14836. Searches through a the files in a directory, returning each file that is found.
  14837. A DirectoryIterator will search through a directory and its subdirectories using
  14838. a wildcard filepattern match.
  14839. If you may be finding a large number of files, this is better than
  14840. using File::findChildFiles() because it doesn't block while it finds them
  14841. all, and this is more memory-efficient.
  14842. It can also guess how far it's got using a wildly inaccurate algorithm.
  14843. */
  14844. class JUCE_API DirectoryIterator
  14845. {
  14846. public:
  14847. /** Creates a DirectoryIterator for a given directory.
  14848. After creating one of these, call its next() method to get the
  14849. first file - e.g. @code
  14850. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  14851. while (iter.next())
  14852. {
  14853. File theFileItFound (iter.getFile());
  14854. ... etc
  14855. }
  14856. @endcode
  14857. @param directory the directory to search in
  14858. @param isRecursive whether all the subdirectories should also be searched
  14859. @param wildCard the file pattern to match
  14860. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  14861. whether to look for files, directories, or both.
  14862. */
  14863. DirectoryIterator (const File& directory,
  14864. bool isRecursive,
  14865. const String& wildCard = "*",
  14866. int whatToLookFor = File::findFiles);
  14867. /** Destructor. */
  14868. ~DirectoryIterator();
  14869. /** Moves the iterator along to the next file.
  14870. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14871. false if there are no more matching files.
  14872. */
  14873. bool next();
  14874. /** Moves the iterator along to the next file, and returns various properties of that file.
  14875. If you need to find out details about the file, it's more efficient to call this method than
  14876. to call the normal next() method and then find out the details afterwards.
  14877. All the parameters are optional, so pass null pointers for any items that you're not
  14878. interested in.
  14879. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14880. false if there are no more matching files. If it returns false, then none of the
  14881. parameters will be filled-in.
  14882. */
  14883. bool next (bool* isDirectory,
  14884. bool* isHidden,
  14885. int64* fileSize,
  14886. Time* modTime,
  14887. Time* creationTime,
  14888. bool* isReadOnly);
  14889. /** Returns the file that the iterator is currently pointing at.
  14890. The result of this call is only valid after a call to next() has returned true.
  14891. */
  14892. const File getFile() const;
  14893. /** Returns a guess of how far through the search the iterator has got.
  14894. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  14895. very accurate.
  14896. */
  14897. float getEstimatedProgress() const;
  14898. private:
  14899. class NativeIterator
  14900. {
  14901. public:
  14902. NativeIterator (const File& directory, const String& wildCard);
  14903. ~NativeIterator();
  14904. bool next (String& filenameFound,
  14905. bool* isDirectory, bool* isHidden, int64* fileSize,
  14906. Time* modTime, Time* creationTime, bool* isReadOnly);
  14907. class Pimpl;
  14908. private:
  14909. friend class DirectoryIterator;
  14910. friend class ScopedPointer<Pimpl>;
  14911. ScopedPointer<Pimpl> pimpl;
  14912. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeIterator);
  14913. };
  14914. friend class ScopedPointer<NativeIterator::Pimpl>;
  14915. NativeIterator fileFinder;
  14916. String wildCard, path;
  14917. int index;
  14918. mutable int totalNumFiles;
  14919. const int whatToLookFor;
  14920. const bool isRecursive;
  14921. bool hasBeenAdvanced;
  14922. ScopedPointer <DirectoryIterator> subIterator;
  14923. File currentFile;
  14924. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryIterator);
  14925. };
  14926. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14927. /*** End of inlined file: juce_DirectoryIterator.h ***/
  14928. #endif
  14929. #ifndef __JUCE_FILE_JUCEHEADER__
  14930. #endif
  14931. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14932. /*** Start of inlined file: juce_FileInputStream.h ***/
  14933. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14934. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14935. /**
  14936. An input stream that reads from a local file.
  14937. @see InputStream, FileOutputStream, File::createInputStream
  14938. */
  14939. class JUCE_API FileInputStream : public InputStream
  14940. {
  14941. public:
  14942. /** Creates a FileInputStream.
  14943. @param fileToRead the file to read from - if the file can't be accessed for some
  14944. reason, then the stream will just contain no data
  14945. */
  14946. explicit FileInputStream (const File& fileToRead);
  14947. /** Destructor. */
  14948. ~FileInputStream();
  14949. /** Returns the file that this stream is reading from. */
  14950. const File& getFile() const noexcept { return file; }
  14951. /** Returns the status of the file stream.
  14952. The result will be ok if the file opened successfully. If an error occurs while
  14953. opening or reading from the file, this will contain an error message.
  14954. */
  14955. const Result getStatus() const { return status; }
  14956. int64 getTotalLength();
  14957. int read (void* destBuffer, int maxBytesToRead);
  14958. bool isExhausted();
  14959. int64 getPosition();
  14960. bool setPosition (int64 pos);
  14961. private:
  14962. File file;
  14963. void* fileHandle;
  14964. int64 currentPosition, totalSize;
  14965. Result status;
  14966. bool needToSeek;
  14967. void openHandle();
  14968. void closeHandle();
  14969. size_t readInternal (void* buffer, size_t numBytes);
  14970. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputStream);
  14971. };
  14972. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14973. /*** End of inlined file: juce_FileInputStream.h ***/
  14974. #endif
  14975. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14976. /*** Start of inlined file: juce_FileOutputStream.h ***/
  14977. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14978. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14979. /**
  14980. An output stream that writes into a local file.
  14981. @see OutputStream, FileInputStream, File::createOutputStream
  14982. */
  14983. class JUCE_API FileOutputStream : public OutputStream
  14984. {
  14985. public:
  14986. /** Creates a FileOutputStream.
  14987. If the file doesn't exist, it will first be created. If the file can't be
  14988. created or opened, the failedToOpen() method will return
  14989. true.
  14990. If the file already exists when opened, the stream's write-postion will
  14991. be set to the end of the file. To overwrite an existing file,
  14992. use File::deleteFile() before opening the stream, or use setPosition(0)
  14993. after it's opened (although this won't truncate the file).
  14994. It's better to use File::createOutputStream() to create one of these, rather
  14995. than using the class directly.
  14996. @see TemporaryFile
  14997. */
  14998. FileOutputStream (const File& fileToWriteTo,
  14999. int bufferSizeToUse = 16384);
  15000. /** Destructor. */
  15001. ~FileOutputStream();
  15002. /** Returns the file that this stream is writing to.
  15003. */
  15004. const File& getFile() const { return file; }
  15005. /** Returns the status of the file stream.
  15006. The result will be ok if the file opened successfully. If an error occurs while
  15007. opening or writing to the file, this will contain an error message.
  15008. */
  15009. const Result getStatus() const { return status; }
  15010. /** Returns true if the stream couldn't be opened for some reason.
  15011. @see getResult()
  15012. */
  15013. bool failedToOpen() const { return status.failed(); }
  15014. void flush();
  15015. int64 getPosition();
  15016. bool setPosition (int64 pos);
  15017. bool write (const void* data, int numBytes);
  15018. private:
  15019. File file;
  15020. void* fileHandle;
  15021. Result status;
  15022. int64 currentPosition;
  15023. int bufferSize, bytesInBuffer;
  15024. HeapBlock <char> buffer;
  15025. void openHandle();
  15026. void closeHandle();
  15027. void flushInternal();
  15028. int64 setPositionInternal (int64 newPosition);
  15029. int writeInternal (const void* data, int numBytes);
  15030. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileOutputStream);
  15031. };
  15032. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  15033. /*** End of inlined file: juce_FileOutputStream.h ***/
  15034. #endif
  15035. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  15036. /*** Start of inlined file: juce_FileSearchPath.h ***/
  15037. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  15038. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  15039. /**
  15040. Encapsulates a set of folders that make up a search path.
  15041. @see File
  15042. */
  15043. class JUCE_API FileSearchPath
  15044. {
  15045. public:
  15046. /** Creates an empty search path. */
  15047. FileSearchPath();
  15048. /** Creates a search path from a string of pathnames.
  15049. The path can be semicolon- or comma-separated, e.g.
  15050. "/foo/bar;/foo/moose;/fish/moose"
  15051. The separate folders are tokenised and added to the search path.
  15052. */
  15053. FileSearchPath (const String& path);
  15054. /** Creates a copy of another search path. */
  15055. FileSearchPath (const FileSearchPath& other);
  15056. /** Destructor. */
  15057. ~FileSearchPath();
  15058. /** Uses a string containing a list of pathnames to re-initialise this list.
  15059. This search path is cleared and the semicolon- or comma-separated folders
  15060. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  15061. */
  15062. FileSearchPath& operator= (const String& path);
  15063. /** Returns the number of folders in this search path.
  15064. @see operator[]
  15065. */
  15066. int getNumPaths() const;
  15067. /** Returns one of the folders in this search path.
  15068. The file returned isn't guaranteed to actually be a valid directory.
  15069. @see getNumPaths
  15070. */
  15071. const File operator[] (int index) const;
  15072. /** Returns the search path as a semicolon-separated list of directories. */
  15073. const String toString() const;
  15074. /** Adds a new directory to the search path.
  15075. The new directory is added to the end of the list if the insertIndex parameter is
  15076. less than zero, otherwise it is inserted at the given index.
  15077. */
  15078. void add (const File& directoryToAdd,
  15079. int insertIndex = -1);
  15080. /** Adds a new directory to the search path if it's not already in there. */
  15081. void addIfNotAlreadyThere (const File& directoryToAdd);
  15082. /** Removes a directory from the search path. */
  15083. void remove (int indexToRemove);
  15084. /** Merges another search path into this one.
  15085. This will remove any duplicate directories.
  15086. */
  15087. void addPath (const FileSearchPath& other);
  15088. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  15089. If the search is intended to be recursive, there's no point having nested folders in the search
  15090. path, because they'll just get searched twice and you'll get duplicate results.
  15091. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  15092. */
  15093. void removeRedundantPaths();
  15094. /** Removes any directories that don't actually exist. */
  15095. void removeNonExistentPaths();
  15096. /** Searches the path for a wildcard.
  15097. This will search all the directories in the search path in order, adding any
  15098. matching files to the results array.
  15099. @param results an array to append the results to
  15100. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  15101. return files, directories, or both.
  15102. @param searchRecursively whether to recursively search the subdirectories too
  15103. @param wildCardPattern a pattern to match against the filenames
  15104. @returns the number of files added to the array
  15105. @see File::findChildFiles
  15106. */
  15107. int findChildFiles (Array<File>& results,
  15108. int whatToLookFor,
  15109. bool searchRecursively,
  15110. const String& wildCardPattern = "*") const;
  15111. /** Finds out whether a file is inside one of the path's directories.
  15112. This will return true if the specified file is a child of one of the
  15113. directories specified by this path. Note that this doesn't actually do any
  15114. searching or check that the files exist - it just looks at the pathnames
  15115. to work out whether the file would be inside a directory.
  15116. @param fileToCheck the file to look for
  15117. @param checkRecursively if true, then this will return true if the file is inside a
  15118. subfolder of one of the path's directories (at any depth). If false
  15119. it will only return true if the file is actually a direct child
  15120. of one of the directories.
  15121. @see File::isAChildOf
  15122. */
  15123. bool isFileInPath (const File& fileToCheck,
  15124. bool checkRecursively) const;
  15125. private:
  15126. StringArray directories;
  15127. void init (const String& path);
  15128. JUCE_LEAK_DETECTOR (FileSearchPath);
  15129. };
  15130. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  15131. /*** End of inlined file: juce_FileSearchPath.h ***/
  15132. #endif
  15133. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  15134. /*** Start of inlined file: juce_NamedPipe.h ***/
  15135. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  15136. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  15137. /**
  15138. A cross-process pipe that can have data written to and read from it.
  15139. Two or more processes can use these for inter-process communication.
  15140. @see InterprocessConnection
  15141. */
  15142. class JUCE_API NamedPipe
  15143. {
  15144. public:
  15145. /** Creates a NamedPipe. */
  15146. NamedPipe();
  15147. /** Destructor. */
  15148. ~NamedPipe();
  15149. /** Tries to open a pipe that already exists.
  15150. Returns true if it succeeds.
  15151. */
  15152. bool openExisting (const String& pipeName);
  15153. /** Tries to create a new pipe.
  15154. Returns true if it succeeds.
  15155. */
  15156. bool createNewPipe (const String& pipeName);
  15157. /** Closes the pipe, if it's open. */
  15158. void close();
  15159. /** True if the pipe is currently open. */
  15160. bool isOpen() const;
  15161. /** Returns the last name that was used to try to open this pipe. */
  15162. const String getName() const;
  15163. /** Reads data from the pipe.
  15164. This will block until another thread has written enough data into the pipe to fill
  15165. the number of bytes specified, or until another thread calls the cancelPendingReads()
  15166. method.
  15167. If the operation fails, it returns -1, otherwise, it will return the number of
  15168. bytes read.
  15169. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  15170. this is a maximum timeout for reading from the pipe.
  15171. */
  15172. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  15173. /** Writes some data to the pipe.
  15174. If the operation fails, it returns -1, otherwise, it will return the number of
  15175. bytes written.
  15176. */
  15177. int write (const void* sourceBuffer, int numBytesToWrite,
  15178. int timeOutMilliseconds = 2000);
  15179. /** If any threads are currently blocked on a read operation, this tells them to abort.
  15180. */
  15181. void cancelPendingReads();
  15182. private:
  15183. void* internal;
  15184. String currentPipeName;
  15185. CriticalSection lock;
  15186. bool openInternal (const String& pipeName, const bool createPipe);
  15187. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NamedPipe);
  15188. };
  15189. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  15190. /*** End of inlined file: juce_NamedPipe.h ***/
  15191. #endif
  15192. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  15193. /*** Start of inlined file: juce_TemporaryFile.h ***/
  15194. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  15195. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  15196. /**
  15197. Manages a temporary file, which will be deleted when this object is deleted.
  15198. This object is intended to be used as a stack based object, using its scope
  15199. to make sure the temporary file isn't left lying around.
  15200. For example:
  15201. @code
  15202. {
  15203. File myTargetFile ("~/myfile.txt");
  15204. // this will choose a file called something like "~/myfile_temp239348.txt"
  15205. // which definitely doesn't exist at the time the constructor is called.
  15206. TemporaryFile temp (myTargetFile);
  15207. // create a stream to the temporary file, and write some data to it...
  15208. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  15209. if (out != nullptr)
  15210. {
  15211. out->write ( ...etc )
  15212. out->flush();
  15213. out = nullptr; // (deletes the stream)
  15214. // ..now we've finished writing, this will rename the temp file to
  15215. // make it replace the target file we specified above.
  15216. bool succeeded = temp.overwriteTargetFileWithTemporary();
  15217. }
  15218. // ..and even if something went wrong and our overwrite failed,
  15219. // as the TemporaryFile object goes out of scope here, it'll make sure
  15220. // that the temp file gets deleted.
  15221. }
  15222. @endcode
  15223. @see File, FileOutputStream
  15224. */
  15225. class JUCE_API TemporaryFile
  15226. {
  15227. public:
  15228. enum OptionFlags
  15229. {
  15230. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  15231. i.e. its name should start with a dot. */
  15232. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  15233. the file is unique, they should go in brackets rather
  15234. than just being appended (see File::getNonexistentSibling() )*/
  15235. };
  15236. /** Creates a randomly-named temporary file in the default temp directory.
  15237. @param suffix a file suffix to use for the file
  15238. @param optionFlags a combination of the values listed in the OptionFlags enum
  15239. The file will not be created until you write to it. And remember that when
  15240. this object is deleted, the file will also be deleted!
  15241. */
  15242. TemporaryFile (const String& suffix = String::empty,
  15243. int optionFlags = 0);
  15244. /** Creates a temporary file in the same directory as a specified file.
  15245. This is useful if you have a file that you want to overwrite, but don't
  15246. want to harm the original file if the write operation fails. You can
  15247. use this to create a temporary file next to the target file, then
  15248. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  15249. to replace the target file with the one you've just written.
  15250. This class won't create any files until you actually write to them. And remember
  15251. that when this object is deleted, the temporary file will also be deleted!
  15252. @param targetFile the file that you intend to overwrite - the temporary
  15253. file will be created in the same directory as this
  15254. @param optionFlags a combination of the values listed in the OptionFlags enum
  15255. */
  15256. TemporaryFile (const File& targetFile,
  15257. int optionFlags = 0);
  15258. /** Destructor.
  15259. When this object is deleted it will make sure that its temporary file is
  15260. also deleted! If the operation fails, it'll throw an assertion in debug
  15261. mode.
  15262. */
  15263. ~TemporaryFile();
  15264. /** Returns the temporary file. */
  15265. const File getFile() const { return temporaryFile; }
  15266. /** Returns the target file that was specified in the constructor. */
  15267. const File getTargetFile() const { return targetFile; }
  15268. /** Tries to move the temporary file to overwrite the target file that was
  15269. specified in the constructor.
  15270. If you used the constructor that specified a target file, this will attempt
  15271. to replace that file with the temporary one.
  15272. Before calling this, make sure:
  15273. - that you've actually written to the temporary file
  15274. - that you've closed any open streams that you were using to write to it
  15275. - and that you don't have any streams open to the target file, which would
  15276. prevent it being overwritten
  15277. If the file move succeeds, this returns false, and the temporary file will
  15278. have disappeared. If it fails, the temporary file will probably still exist,
  15279. but will be deleted when this object is destroyed.
  15280. */
  15281. bool overwriteTargetFileWithTemporary() const;
  15282. /** Attempts to delete the temporary file, if it exists.
  15283. @returns true if the file is successfully deleted (or if it didn't exist).
  15284. */
  15285. bool deleteTemporaryFile() const;
  15286. private:
  15287. File temporaryFile, targetFile;
  15288. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  15289. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryFile);
  15290. };
  15291. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  15292. /*** End of inlined file: juce_TemporaryFile.h ***/
  15293. #endif
  15294. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  15295. /*** Start of inlined file: juce_ZipFile.h ***/
  15296. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  15297. #define __JUCE_ZIPFILE_JUCEHEADER__
  15298. /*** Start of inlined file: juce_InputSource.h ***/
  15299. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  15300. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  15301. /**
  15302. A lightweight object that can create a stream to read some kind of resource.
  15303. This may be used to refer to a file, or some other kind of source, allowing a
  15304. caller to create an input stream that can read from it when required.
  15305. @see FileInputSource
  15306. */
  15307. class JUCE_API InputSource
  15308. {
  15309. public:
  15310. InputSource() noexcept {}
  15311. /** Destructor. */
  15312. virtual ~InputSource() {}
  15313. /** Returns a new InputStream to read this item.
  15314. @returns an inputstream that the caller will delete, or 0 if
  15315. the filename isn't found.
  15316. */
  15317. virtual InputStream* createInputStream() = 0;
  15318. /** Returns a new InputStream to read an item, relative.
  15319. @param relatedItemPath the relative pathname of the resource that is required
  15320. @returns an inputstream that the caller will delete, or 0 if
  15321. the item isn't found.
  15322. */
  15323. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  15324. /** Returns a hash code that uniquely represents this item.
  15325. */
  15326. virtual int64 hashCode() const = 0;
  15327. private:
  15328. JUCE_LEAK_DETECTOR (InputSource);
  15329. };
  15330. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  15331. /*** End of inlined file: juce_InputSource.h ***/
  15332. /**
  15333. Decodes a ZIP file from a stream.
  15334. This can enumerate the items in a ZIP file and can create suitable stream objects
  15335. to read each one.
  15336. */
  15337. class JUCE_API ZipFile
  15338. {
  15339. public:
  15340. /** Creates a ZipFile for a given stream.
  15341. @param inputStream the stream to read from
  15342. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  15343. will be deleted when this ZipFile object is deleted
  15344. */
  15345. ZipFile (InputStream* inputStream, bool deleteStreamWhenDestroyed);
  15346. /** Creates a ZipFile based for a file. */
  15347. ZipFile (const File& file);
  15348. /** Creates a ZipFile for an input source.
  15349. The inputSource object will be owned by the zip file, which will delete
  15350. it later when not needed.
  15351. */
  15352. ZipFile (InputSource* inputSource);
  15353. /** Destructor. */
  15354. ~ZipFile();
  15355. /**
  15356. Contains information about one of the entries in a ZipFile.
  15357. @see ZipFile::getEntry
  15358. */
  15359. struct ZipEntry
  15360. {
  15361. /** The name of the file, which may also include a partial pathname. */
  15362. String filename;
  15363. /** The file's original size. */
  15364. unsigned int uncompressedSize;
  15365. /** The last time the file was modified. */
  15366. Time fileTime;
  15367. };
  15368. /** Returns the number of items in the zip file. */
  15369. int getNumEntries() const noexcept;
  15370. /** Returns a structure that describes one of the entries in the zip file.
  15371. This may return zero if the index is out of range.
  15372. @see ZipFile::ZipEntry
  15373. */
  15374. const ZipEntry* getEntry (int index) const noexcept;
  15375. /** Returns the index of the first entry with a given filename.
  15376. This uses a case-sensitive comparison to look for a filename in the
  15377. list of entries. It might return -1 if no match is found.
  15378. @see ZipFile::ZipEntry
  15379. */
  15380. int getIndexOfFileName (const String& fileName) const noexcept;
  15381. /** Returns a structure that describes one of the entries in the zip file.
  15382. This uses a case-sensitive comparison to look for a filename in the
  15383. list of entries. It might return 0 if no match is found.
  15384. @see ZipFile::ZipEntry
  15385. */
  15386. const ZipEntry* getEntry (const String& fileName) const noexcept;
  15387. /** Sorts the list of entries, based on the filename.
  15388. */
  15389. void sortEntriesByFilename();
  15390. /** Creates a stream that can read from one of the zip file's entries.
  15391. The stream that is returned must be deleted by the caller (and
  15392. zero might be returned if a stream can't be opened for some reason).
  15393. The stream must not be used after the ZipFile object that created
  15394. has been deleted.
  15395. */
  15396. InputStream* createStreamForEntry (int index);
  15397. /** Creates a stream that can read from one of the zip file's entries.
  15398. The stream that is returned must be deleted by the caller (and
  15399. zero might be returned if a stream can't be opened for some reason).
  15400. The stream must not be used after the ZipFile object that created
  15401. has been deleted.
  15402. */
  15403. InputStream* createStreamForEntry (ZipEntry& entry);
  15404. /** Uncompresses all of the files in the zip file.
  15405. This will expand all the entries into a target directory. The relative
  15406. paths of the entries are used.
  15407. @param targetDirectory the root folder to uncompress to
  15408. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  15409. @returns true if all the files are successfully unzipped
  15410. */
  15411. bool uncompressTo (const File& targetDirectory,
  15412. bool shouldOverwriteFiles = true);
  15413. /** Uncompresses one of the entries from the zip file.
  15414. This will expand the entry and write it in a target directory. The entry's path is used to
  15415. determine which subfolder of the target should contain the new file.
  15416. @param index the index of the entry to uncompress
  15417. @param targetDirectory the root folder to uncompress into
  15418. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  15419. @returns true if the files is successfully unzipped
  15420. */
  15421. bool uncompressEntry (int index,
  15422. const File& targetDirectory,
  15423. bool shouldOverwriteFiles = true);
  15424. /** Used to create a new zip file.
  15425. Create a ZipFile::Builder object, and call its addFile() method to add some files,
  15426. then you can write it to a stream with write().
  15427. Currently this just stores the files with no compression.. That will be added
  15428. soon!
  15429. */
  15430. class Builder
  15431. {
  15432. public:
  15433. Builder();
  15434. ~Builder();
  15435. /** Adds a file while should be added to the archive.
  15436. The file isn't read immediately, all the files will be read later when the writeToStream()
  15437. method is called.
  15438. The compressionLevel can be between 0 (no compression), and 9 (maximum compression).
  15439. If the storedPathName parameter is specified, you can customise the partial pathname that
  15440. will be stored for this file.
  15441. */
  15442. void addFile (const File& fileToAdd, int compressionLevel,
  15443. const String& storedPathName = String::empty);
  15444. /** Generates the zip file, writing it to the specified stream. */
  15445. bool writeToStream (OutputStream& target) const;
  15446. private:
  15447. class Item;
  15448. friend class OwnedArray<Item>;
  15449. OwnedArray<Item> items;
  15450. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Builder);
  15451. };
  15452. private:
  15453. class ZipInputStream;
  15454. class ZipFilenameComparator;
  15455. class ZipEntryInfo;
  15456. friend class ZipInputStream;
  15457. friend class ZipFilenameComparator;
  15458. friend class ZipEntryInfo;
  15459. OwnedArray <ZipEntryInfo> entries;
  15460. CriticalSection lock;
  15461. InputStream* inputStream;
  15462. ScopedPointer <InputStream> streamToDelete;
  15463. ScopedPointer <InputSource> inputSource;
  15464. #if JUCE_DEBUG
  15465. int numOpenStreams;
  15466. #endif
  15467. void init();
  15468. int findEndOfZipEntryTable (InputStream& input, int& numEntries);
  15469. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  15470. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipFile);
  15471. };
  15472. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  15473. /*** End of inlined file: juce_ZipFile.h ***/
  15474. #endif
  15475. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  15476. /*** Start of inlined file: juce_MACAddress.h ***/
  15477. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  15478. #define __JUCE_MACADDRESS_JUCEHEADER__
  15479. /**
  15480. A wrapper for a streaming (TCP) socket.
  15481. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15482. sockets, you could also try the InterprocessConnection class.
  15483. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  15484. */
  15485. class JUCE_API MACAddress
  15486. {
  15487. public:
  15488. /** Populates a list of the MAC addresses of all the available network cards. */
  15489. static void findAllAddresses (Array<MACAddress>& results);
  15490. /** Creates a null address (00-00-00-00-00-00). */
  15491. MACAddress();
  15492. /** Creates a copy of another address. */
  15493. MACAddress (const MACAddress& other);
  15494. /** Creates a copy of another address. */
  15495. MACAddress& operator= (const MACAddress& other);
  15496. /** Creates an address from 6 bytes. */
  15497. explicit MACAddress (const uint8 bytes[6]);
  15498. /** Returns a pointer to the 6 bytes that make up this address. */
  15499. const uint8* getBytes() const noexcept { return asBytes; }
  15500. /** Returns a dash-separated string in the form "11-22-33-44-55-66" */
  15501. const String toString() const;
  15502. /** Returns the address in the lower 6 bytes of an int64.
  15503. This uses a little-endian arrangement, with the first byte of the address being
  15504. stored in the least-significant byte of the result value.
  15505. */
  15506. int64 toInt64() const noexcept;
  15507. /** Returns true if this address is null (00-00-00-00-00-00). */
  15508. bool isNull() const noexcept;
  15509. bool operator== (const MACAddress& other) const noexcept;
  15510. bool operator!= (const MACAddress& other) const noexcept;
  15511. private:
  15512. #ifndef DOXYGEN
  15513. union
  15514. {
  15515. uint64 asInt64;
  15516. uint8 asBytes[6];
  15517. };
  15518. #endif
  15519. };
  15520. #endif // __JUCE_MACADDRESS_JUCEHEADER__
  15521. /*** End of inlined file: juce_MACAddress.h ***/
  15522. #endif
  15523. #ifndef __JUCE_SOCKET_JUCEHEADER__
  15524. /*** Start of inlined file: juce_Socket.h ***/
  15525. #ifndef __JUCE_SOCKET_JUCEHEADER__
  15526. #define __JUCE_SOCKET_JUCEHEADER__
  15527. /**
  15528. A wrapper for a streaming (TCP) socket.
  15529. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15530. sockets, you could also try the InterprocessConnection class.
  15531. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  15532. */
  15533. class JUCE_API StreamingSocket
  15534. {
  15535. public:
  15536. /** Creates an uninitialised socket.
  15537. To connect it, use the connect() method, after which you can read() or write()
  15538. to it.
  15539. To wait for other sockets to connect to this one, the createListener() method
  15540. enters "listener" mode, and can be used to spawn new sockets for each connection
  15541. that comes along.
  15542. */
  15543. StreamingSocket();
  15544. /** Destructor. */
  15545. ~StreamingSocket();
  15546. /** Binds the socket to the specified local port.
  15547. @returns true on success; false may indicate that another socket is already bound
  15548. on the same port
  15549. */
  15550. bool bindToPort (int localPortNumber);
  15551. /** Tries to connect the socket to hostname:port.
  15552. If timeOutMillisecs is 0, then this method will block until the operating system
  15553. rejects the connection (which could take a long time).
  15554. @returns true if it succeeds.
  15555. @see isConnected
  15556. */
  15557. bool connect (const String& remoteHostname,
  15558. int remotePortNumber,
  15559. int timeOutMillisecs = 3000);
  15560. /** True if the socket is currently connected. */
  15561. bool isConnected() const noexcept { return connected; }
  15562. /** Closes the connection. */
  15563. void close();
  15564. /** Returns the name of the currently connected host. */
  15565. const String& getHostName() const noexcept { return hostName; }
  15566. /** Returns the port number that's currently open. */
  15567. int getPort() const noexcept { return portNumber; }
  15568. /** True if the socket is connected to this machine rather than over the network. */
  15569. bool isLocal() const noexcept;
  15570. /** Waits until the socket is ready for reading or writing.
  15571. If readyForReading is true, it will wait until the socket is ready for
  15572. reading; if false, it will wait until it's ready for writing.
  15573. If the timeout is < 0, it will wait forever, or else will give up after
  15574. the specified time.
  15575. If the socket is ready on return, this returns 1. If it times-out before
  15576. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  15577. */
  15578. int waitUntilReady (bool readyForReading,
  15579. int timeoutMsecs) const;
  15580. /** Reads bytes from the socket.
  15581. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  15582. maxBytesToRead bytes have been read, (or until an error occurs). If this
  15583. flag is false, the method will return as much data as is currently available
  15584. without blocking.
  15585. @returns the number of bytes read, or -1 if there was an error.
  15586. @see waitUntilReady
  15587. */
  15588. int read (void* destBuffer, int maxBytesToRead,
  15589. bool blockUntilSpecifiedAmountHasArrived);
  15590. /** Writes bytes to the socket from a buffer.
  15591. Note that this method will block unless you have checked the socket is ready
  15592. for writing before calling it (see the waitUntilReady() method).
  15593. @returns the number of bytes written, or -1 if there was an error.
  15594. */
  15595. int write (const void* sourceBuffer, int numBytesToWrite);
  15596. /** Puts this socket into "listener" mode.
  15597. When in this mode, your thread can call waitForNextConnection() repeatedly,
  15598. which will spawn new sockets for each new connection, so that these can
  15599. be handled in parallel by other threads.
  15600. @param portNumber the port number to listen on
  15601. @param localHostName the interface address to listen on - pass an empty
  15602. string to listen on all addresses
  15603. @returns true if it manages to open the socket successfully.
  15604. @see waitForNextConnection
  15605. */
  15606. bool createListener (int portNumber, const String& localHostName = String::empty);
  15607. /** When in "listener" mode, this waits for a connection and spawns it as a new
  15608. socket.
  15609. The object that gets returned will be owned by the caller.
  15610. This method can only be called after using createListener().
  15611. @see createListener
  15612. */
  15613. StreamingSocket* waitForNextConnection() const;
  15614. private:
  15615. String hostName;
  15616. int volatile portNumber, handle;
  15617. bool connected, isListener;
  15618. StreamingSocket (const String& hostname, int portNumber, int handle);
  15619. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StreamingSocket);
  15620. };
  15621. /**
  15622. A wrapper for a datagram (UDP) socket.
  15623. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15624. sockets, you could also try the InterprocessConnection class.
  15625. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  15626. */
  15627. class JUCE_API DatagramSocket
  15628. {
  15629. public:
  15630. /**
  15631. Creates an (uninitialised) datagram socket.
  15632. The localPortNumber is the port on which to bind this socket. If this value is 0,
  15633. the port number is assigned by the operating system.
  15634. To use the socket for sending, call the connect() method. This will not immediately
  15635. make a connection, but will save the destination you've provided. After this, you can
  15636. call read() or write().
  15637. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  15638. (may require extra privileges on linux)
  15639. To wait for other sockets to connect to this one, call waitForNextConnection().
  15640. */
  15641. DatagramSocket (int localPortNumber,
  15642. bool enableBroadcasting = false);
  15643. /** Destructor. */
  15644. ~DatagramSocket();
  15645. /** Binds the socket to the specified local port.
  15646. @returns true on success; false may indicate that another socket is already bound
  15647. on the same port
  15648. */
  15649. bool bindToPort (int localPortNumber);
  15650. /** Tries to connect the socket to hostname:port.
  15651. If timeOutMillisecs is 0, then this method will block until the operating system
  15652. rejects the connection (which could take a long time).
  15653. @returns true if it succeeds.
  15654. @see isConnected
  15655. */
  15656. bool connect (const String& remoteHostname,
  15657. int remotePortNumber,
  15658. int timeOutMillisecs = 3000);
  15659. /** True if the socket is currently connected. */
  15660. bool isConnected() const noexcept { return connected; }
  15661. /** Closes the connection. */
  15662. void close();
  15663. /** Returns the name of the currently connected host. */
  15664. const String& getHostName() const noexcept { return hostName; }
  15665. /** Returns the port number that's currently open. */
  15666. int getPort() const noexcept { return portNumber; }
  15667. /** True if the socket is connected to this machine rather than over the network. */
  15668. bool isLocal() const noexcept;
  15669. /** Waits until the socket is ready for reading or writing.
  15670. If readyForReading is true, it will wait until the socket is ready for
  15671. reading; if false, it will wait until it's ready for writing.
  15672. If the timeout is < 0, it will wait forever, or else will give up after
  15673. the specified time.
  15674. If the socket is ready on return, this returns 1. If it times-out before
  15675. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  15676. */
  15677. int waitUntilReady (bool readyForReading,
  15678. int timeoutMsecs) const;
  15679. /** Reads bytes from the socket.
  15680. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  15681. maxBytesToRead bytes have been read, (or until an error occurs). If this
  15682. flag is false, the method will return as much data as is currently available
  15683. without blocking.
  15684. @returns the number of bytes read, or -1 if there was an error.
  15685. @see waitUntilReady
  15686. */
  15687. int read (void* destBuffer, int maxBytesToRead,
  15688. bool blockUntilSpecifiedAmountHasArrived);
  15689. /** Writes bytes to the socket from a buffer.
  15690. Note that this method will block unless you have checked the socket is ready
  15691. for writing before calling it (see the waitUntilReady() method).
  15692. @returns the number of bytes written, or -1 if there was an error.
  15693. */
  15694. int write (const void* sourceBuffer, int numBytesToWrite);
  15695. /** This waits for incoming data to be sent, and returns a socket that can be used
  15696. to read it.
  15697. The object that gets returned is owned by the caller, and can't be used for
  15698. sending, but can be used to read the data.
  15699. */
  15700. DatagramSocket* waitForNextConnection() const;
  15701. private:
  15702. String hostName;
  15703. int volatile portNumber, handle;
  15704. bool connected, allowBroadcast;
  15705. void* serverAddress;
  15706. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  15707. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DatagramSocket);
  15708. };
  15709. #endif // __JUCE_SOCKET_JUCEHEADER__
  15710. /*** End of inlined file: juce_Socket.h ***/
  15711. #endif
  15712. #ifndef __JUCE_URL_JUCEHEADER__
  15713. /*** Start of inlined file: juce_URL.h ***/
  15714. #ifndef __JUCE_URL_JUCEHEADER__
  15715. #define __JUCE_URL_JUCEHEADER__
  15716. /**
  15717. Represents a URL and has a bunch of useful functions to manipulate it.
  15718. This class can be used to launch URLs in browsers, and also to create
  15719. InputStreams that can read from remote http or ftp sources.
  15720. */
  15721. class JUCE_API URL
  15722. {
  15723. public:
  15724. /** Creates an empty URL. */
  15725. URL();
  15726. /** Creates a URL from a string. */
  15727. URL (const String& url);
  15728. /** Creates a copy of another URL. */
  15729. URL (const URL& other);
  15730. /** Destructor. */
  15731. ~URL();
  15732. /** Copies this URL from another one. */
  15733. URL& operator= (const URL& other);
  15734. /** Returns a string version of the URL.
  15735. If includeGetParameters is true and any parameters have been set with the
  15736. withParameter() method, then the string will have these appended on the
  15737. end and url-encoded.
  15738. */
  15739. const String toString (bool includeGetParameters) const;
  15740. /** True if it seems to be valid. */
  15741. bool isWellFormed() const;
  15742. /** Returns just the domain part of the URL.
  15743. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  15744. */
  15745. const String getDomain() const;
  15746. /** Returns the path part of the URL.
  15747. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  15748. */
  15749. const String getSubPath() const;
  15750. /** Returns the scheme of the URL.
  15751. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  15752. include the colon).
  15753. */
  15754. const String getScheme() const;
  15755. /** Returns a new version of this URL that uses a different sub-path.
  15756. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  15757. "bar", it'll return "http://www.xyz.com/bar?x=1".
  15758. */
  15759. const URL withNewSubPath (const String& newPath) const;
  15760. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  15761. Any control characters in the value will be encoded.
  15762. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  15763. would produce a new url whose toString(true) method would return
  15764. "www.fish.com?amount=some+fish".
  15765. */
  15766. const URL withParameter (const String& parameterName,
  15767. const String& parameterValue) const;
  15768. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  15769. When performing a POST where one of your parameters is a binary file, this
  15770. lets you specify the file.
  15771. Note that the filename is stored, but the file itself won't actually be read
  15772. until this URL is later used to create a network input stream.
  15773. */
  15774. const URL withFileToUpload (const String& parameterName,
  15775. const File& fileToUpload,
  15776. const String& mimeType) const;
  15777. /** Returns a set of all the parameters encoded into the url.
  15778. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  15779. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  15780. The values returned will have been cleaned up to remove any escape characters.
  15781. @see getNamedParameter, withParameter
  15782. */
  15783. const StringPairArray& getParameters() const;
  15784. /** Returns the set of files that should be uploaded as part of a POST operation.
  15785. This is the set of files that were added to the URL with the withFileToUpload()
  15786. method.
  15787. */
  15788. const StringPairArray& getFilesToUpload() const;
  15789. /** Returns the set of mime types associated with each of the upload files.
  15790. */
  15791. const StringPairArray& getMimeTypesOfUploadFiles() const;
  15792. /** Returns a copy of this URL, with a block of data to send as the POST data.
  15793. If you're setting the POST data, be careful not to have any parameters set
  15794. as well, otherwise it'll all get thrown in together, and might not have the
  15795. desired effect.
  15796. If the URL already contains some POST data, this will replace it, rather
  15797. than being appended to it.
  15798. This data will only be used if you specify a post operation when you call
  15799. createInputStream().
  15800. */
  15801. const URL withPOSTData (const String& postData) const;
  15802. /** Returns the data that was set using withPOSTData().
  15803. */
  15804. const String getPostData() const { return postData; }
  15805. /** Tries to launch the system's default browser to open the URL.
  15806. Returns true if this seems to have worked.
  15807. */
  15808. bool launchInDefaultBrowser() const;
  15809. /** Takes a guess as to whether a string might be a valid website address.
  15810. This isn't foolproof!
  15811. */
  15812. static bool isProbablyAWebsiteURL (const String& possibleURL);
  15813. /** Takes a guess as to whether a string might be a valid email address.
  15814. This isn't foolproof!
  15815. */
  15816. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  15817. /** This callback function can be used by the createInputStream() method.
  15818. It allows your app to receive progress updates during a lengthy POST operation. If you
  15819. want to continue the operation, this should return true, or false to abort.
  15820. */
  15821. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  15822. /** Attempts to open a stream that can read from this URL.
  15823. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  15824. the paramters, otherwise it'll encode them into the
  15825. URL and do a 'GET'.
  15826. @param progressCallback if this is non-zero, it lets you supply a callback function
  15827. to keep track of the operation's progress. This can be useful
  15828. for lengthy POST operations, so that you can provide user feedback.
  15829. @param progressCallbackContext if a callback is specified, this value will be passed to
  15830. the function
  15831. @param extraHeaders if not empty, this string is appended onto the headers that
  15832. are used for the request. It must therefore be a valid set of HTML
  15833. header directives, separated by newlines.
  15834. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  15835. a negative number, it will be infinite. Otherwise it specifies a
  15836. time in milliseconds.
  15837. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  15838. in the response will be stored in this array
  15839. @returns an input stream that the caller must delete, or a null pointer if there was an
  15840. error trying to open it.
  15841. */
  15842. InputStream* createInputStream (bool usePostCommand,
  15843. OpenStreamProgressCallback* progressCallback = nullptr,
  15844. void* progressCallbackContext = nullptr,
  15845. const String& extraHeaders = String::empty,
  15846. int connectionTimeOutMs = 0,
  15847. StringPairArray* responseHeaders = nullptr) const;
  15848. /** Tries to download the entire contents of this URL into a binary data block.
  15849. If it succeeds, this will return true and append the data it read onto the end
  15850. of the memory block.
  15851. @param destData the memory block to append the new data to
  15852. @param usePostCommand whether to use a POST command to get the data (uses
  15853. a GET command if this is false)
  15854. @see readEntireTextStream, readEntireXmlStream
  15855. */
  15856. bool readEntireBinaryStream (MemoryBlock& destData,
  15857. bool usePostCommand = false) const;
  15858. /** Tries to download the entire contents of this URL as a string.
  15859. If it fails, this will return an empty string, otherwise it will return the
  15860. contents of the downloaded file. If you need to distinguish between a read
  15861. operation that fails and one that returns an empty string, you'll need to use
  15862. a different method, such as readEntireBinaryStream().
  15863. @param usePostCommand whether to use a POST command to get the data (uses
  15864. a GET command if this is false)
  15865. @see readEntireBinaryStream, readEntireXmlStream
  15866. */
  15867. const String readEntireTextStream (bool usePostCommand = false) const;
  15868. /** Tries to download the entire contents of this URL and parse it as XML.
  15869. If it fails, or if the text that it reads can't be parsed as XML, this will
  15870. return 0.
  15871. When it returns a valid XmlElement object, the caller is responsibile for deleting
  15872. this object when no longer needed.
  15873. @param usePostCommand whether to use a POST command to get the data (uses
  15874. a GET command if this is false)
  15875. @see readEntireBinaryStream, readEntireTextStream
  15876. */
  15877. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  15878. /** Adds escape sequences to a string to encode any characters that aren't
  15879. legal in a URL.
  15880. E.g. any spaces will be replaced with "%20".
  15881. This is the opposite of removeEscapeChars().
  15882. If isParameter is true, it means that the string is going to be used
  15883. as a parameter, so it also encodes '$' and ',' (which would otherwise
  15884. be legal in a URL.
  15885. @see removeEscapeChars
  15886. */
  15887. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  15888. bool isParameter);
  15889. /** Replaces any escape character sequences in a string with their original
  15890. character codes.
  15891. E.g. any instances of "%20" will be replaced by a space.
  15892. This is the opposite of addEscapeChars().
  15893. @see addEscapeChars
  15894. */
  15895. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  15896. private:
  15897. String url, postData;
  15898. StringPairArray parameters, filesToUpload, mimeTypes;
  15899. static InputStream* createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  15900. OpenStreamProgressCallback* progressCallback,
  15901. void* progressCallbackContext, const String& headers,
  15902. const int timeOutMs, StringPairArray* responseHeaders);
  15903. JUCE_LEAK_DETECTOR (URL);
  15904. };
  15905. #endif // __JUCE_URL_JUCEHEADER__
  15906. /*** End of inlined file: juce_URL.h ***/
  15907. #endif
  15908. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15909. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  15910. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15911. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15912. /*** Start of inlined file: juce_OptionalScopedPointer.h ***/
  15913. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15914. #define __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15915. /**
  15916. Holds a pointer to an object which can optionally be deleted when this pointer
  15917. goes out of scope.
  15918. This acts in many ways like a ScopedPointer, but allows you to specify whether or
  15919. not the object is deleted.
  15920. @see ScopedPointer
  15921. */
  15922. template <class ObjectType>
  15923. class OptionalScopedPointer
  15924. {
  15925. public:
  15926. /** Creates an empty OptionalScopedPointer. */
  15927. OptionalScopedPointer() : shouldDelete (false) {}
  15928. /** Creates an OptionalScopedPointer to point to a given object, and specifying whether
  15929. the OptionalScopedPointer will delete it.
  15930. If takeOwnership is true, then the OptionalScopedPointer will act like a ScopedPointer,
  15931. deleting the object when it is itself deleted. If this parameter is false, then the
  15932. OptionalScopedPointer just holds a normal pointer to the object, and won't delete it.
  15933. */
  15934. OptionalScopedPointer (ObjectType* objectToHold, bool takeOwnership)
  15935. : object (objectToHold), shouldDelete (takeOwnership)
  15936. {
  15937. }
  15938. /** Takes ownership of the object that another OptionalScopedPointer holds.
  15939. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  15940. as ownership of the managed object is transferred to this object.
  15941. The flag to indicate whether or not to delete the managed object is also
  15942. copied from the source object.
  15943. */
  15944. OptionalScopedPointer (OptionalScopedPointer& objectToTransferFrom)
  15945. : object (objectToTransferFrom.release()),
  15946. shouldDelete (objectToTransferFrom.shouldDelete)
  15947. {
  15948. }
  15949. /** Takes ownership of the object that another OptionalScopedPointer holds.
  15950. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  15951. as ownership of the managed object is transferred to this object.
  15952. The ownership flag that says whether or not to delete the managed object is also
  15953. copied from the source object.
  15954. */
  15955. OptionalScopedPointer& operator= (OptionalScopedPointer& objectToTransferFrom)
  15956. {
  15957. if (object != objectToTransferFrom.object)
  15958. {
  15959. clear();
  15960. object = objectToTransferFrom.object;
  15961. }
  15962. shouldDelete = objectToTransferFrom.shouldDelete;
  15963. return *this;
  15964. }
  15965. /** The destructor may or may not delete the object that is being held, depending on the
  15966. takeOwnership flag that was specified when the object was first passed into an
  15967. OptionalScopedPointer constructor.
  15968. */
  15969. ~OptionalScopedPointer()
  15970. {
  15971. clear();
  15972. }
  15973. /** Returns the object that this pointer is managing. */
  15974. inline operator ObjectType*() const noexcept { return object; }
  15975. /** Returns the object that this pointer is managing. */
  15976. inline ObjectType& operator*() const noexcept { return *object; }
  15977. /** Lets you access methods and properties of the object that this pointer is holding. */
  15978. inline ObjectType* operator->() const noexcept { return object; }
  15979. /** Removes the current object from this OptionalScopedPointer without deleting it.
  15980. This will return the current object, and set this OptionalScopedPointer to a null pointer.
  15981. */
  15982. ObjectType* release() noexcept { return object.release(); }
  15983. /** Resets this pointer to null, possibly deleting the object that it holds, if it has
  15984. ownership of it.
  15985. */
  15986. void clear()
  15987. {
  15988. if (! shouldDelete)
  15989. object.release();
  15990. }
  15991. /** Swaps this object with another OptionalScopedPointer.
  15992. The two objects simply exchange their states.
  15993. */
  15994. void swapWith (OptionalScopedPointer<ObjectType>& other) noexcept
  15995. {
  15996. object.swapWith (other.object);
  15997. std::swap (shouldDelete, other.shouldDelete);
  15998. }
  15999. private:
  16000. ScopedPointer<ObjectType> object;
  16001. bool shouldDelete;
  16002. };
  16003. #endif // __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  16004. /*** End of inlined file: juce_OptionalScopedPointer.h ***/
  16005. /** Wraps another input stream, and reads from it using an intermediate buffer
  16006. If you're using an input stream such as a file input stream, and making lots of
  16007. small read accesses to it, it's probably sensible to wrap it in one of these,
  16008. so that the source stream gets accessed in larger chunk sizes, meaning less
  16009. work for the underlying stream.
  16010. */
  16011. class JUCE_API BufferedInputStream : public InputStream
  16012. {
  16013. public:
  16014. /** Creates a BufferedInputStream from an input source.
  16015. @param sourceStream the source stream to read from
  16016. @param bufferSize the size of reservoir to use to buffer the source
  16017. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  16018. deleted by this object when it is itself deleted.
  16019. */
  16020. BufferedInputStream (InputStream* sourceStream,
  16021. int bufferSize,
  16022. bool deleteSourceWhenDestroyed);
  16023. /** Creates a BufferedInputStream from an input source.
  16024. @param sourceStream the source stream to read from - the source stream must not
  16025. be deleted until this object has been destroyed.
  16026. @param bufferSize the size of reservoir to use to buffer the source
  16027. */
  16028. BufferedInputStream (InputStream& sourceStream, int bufferSize);
  16029. /** Destructor.
  16030. This may also delete the source stream, if that option was chosen when the
  16031. buffered stream was created.
  16032. */
  16033. ~BufferedInputStream();
  16034. int64 getTotalLength();
  16035. int64 getPosition();
  16036. bool setPosition (int64 newPosition);
  16037. int read (void* destBuffer, int maxBytesToRead);
  16038. const String readString();
  16039. bool isExhausted();
  16040. private:
  16041. OptionalScopedPointer<InputStream> source;
  16042. int bufferSize;
  16043. int64 position, lastReadPos, bufferStart, bufferOverlap;
  16044. HeapBlock <char> buffer;
  16045. void ensureBuffered();
  16046. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferedInputStream);
  16047. };
  16048. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  16049. /*** End of inlined file: juce_BufferedInputStream.h ***/
  16050. #endif
  16051. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  16052. /*** Start of inlined file: juce_FileInputSource.h ***/
  16053. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  16054. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  16055. /**
  16056. A type of InputSource that represents a normal file.
  16057. @see InputSource
  16058. */
  16059. class JUCE_API FileInputSource : public InputSource
  16060. {
  16061. public:
  16062. FileInputSource (const File& file, bool useFileTimeInHashGeneration = false);
  16063. ~FileInputSource();
  16064. InputStream* createInputStream();
  16065. InputStream* createInputStreamFor (const String& relatedItemPath);
  16066. int64 hashCode() const;
  16067. private:
  16068. const File file;
  16069. bool useFileTimeInHashGeneration;
  16070. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputSource);
  16071. };
  16072. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  16073. /*** End of inlined file: juce_FileInputSource.h ***/
  16074. #endif
  16075. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16076. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  16077. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16078. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16079. /**
  16080. A stream which uses zlib to compress the data written into it.
  16081. @see GZIPDecompressorInputStream
  16082. */
  16083. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  16084. {
  16085. public:
  16086. /** Creates a compression stream.
  16087. @param destStream the stream into which the compressed data should
  16088. be written
  16089. @param compressionLevel how much to compress the data, between 1 and 9, where
  16090. 1 is the fastest/lowest compression, and 9 is the
  16091. slowest/highest compression. Any value outside this range
  16092. indicates that a default compression level should be used.
  16093. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  16094. this stream is destroyed
  16095. @param windowBits this is used internally to change the window size used
  16096. by zlib - leave it as 0 unless you specifically need to set
  16097. its value for some reason
  16098. */
  16099. GZIPCompressorOutputStream (OutputStream* destStream,
  16100. int compressionLevel = 0,
  16101. bool deleteDestStreamWhenDestroyed = false,
  16102. int windowBits = 0);
  16103. /** Destructor. */
  16104. ~GZIPCompressorOutputStream();
  16105. void flush();
  16106. int64 getPosition();
  16107. bool setPosition (int64 newPosition);
  16108. bool write (const void* destBuffer, int howMany);
  16109. /** These are preset values that can be used for the constructor's windowBits paramter.
  16110. For more info about this, see the zlib documentation for its windowBits parameter.
  16111. */
  16112. enum WindowBitsValues
  16113. {
  16114. windowBitsRaw = -15,
  16115. windowBitsGZIP = 15 + 16
  16116. };
  16117. private:
  16118. OptionalScopedPointer<OutputStream> destStream;
  16119. HeapBlock <uint8> buffer;
  16120. class GZIPCompressorHelper;
  16121. friend class ScopedPointer <GZIPCompressorHelper>;
  16122. ScopedPointer <GZIPCompressorHelper> helper;
  16123. bool doNextBlock();
  16124. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPCompressorOutputStream);
  16125. };
  16126. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16127. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  16128. #endif
  16129. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16130. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  16131. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16132. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16133. /**
  16134. This stream will decompress a source-stream using zlib.
  16135. Tip: if you're reading lots of small items from one of these streams, you
  16136. can increase the performance enormously by passing it through a
  16137. BufferedInputStream, so that it has to read larger blocks less often.
  16138. @see GZIPCompressorOutputStream
  16139. */
  16140. class JUCE_API GZIPDecompressorInputStream : public InputStream
  16141. {
  16142. public:
  16143. /** Creates a decompressor stream.
  16144. @param sourceStream the stream to read from
  16145. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  16146. when this object is destroyed
  16147. @param noWrap this is used internally by the ZipFile class
  16148. and should be ignored by user applications
  16149. @param uncompressedStreamLength if the creator knows the length that the
  16150. uncompressed stream will be, then it can supply this
  16151. value, which will be returned by getTotalLength()
  16152. */
  16153. GZIPDecompressorInputStream (InputStream* sourceStream,
  16154. bool deleteSourceWhenDestroyed,
  16155. bool noWrap = false,
  16156. int64 uncompressedStreamLength = -1);
  16157. /** Creates a decompressor stream.
  16158. @param sourceStream the stream to read from - the source stream must not be
  16159. deleted until this object has been destroyed
  16160. */
  16161. GZIPDecompressorInputStream (InputStream& sourceStream);
  16162. /** Destructor. */
  16163. ~GZIPDecompressorInputStream();
  16164. int64 getPosition();
  16165. bool setPosition (int64 pos);
  16166. int64 getTotalLength();
  16167. bool isExhausted();
  16168. int read (void* destBuffer, int maxBytesToRead);
  16169. private:
  16170. OptionalScopedPointer<InputStream> sourceStream;
  16171. const int64 uncompressedStreamLength;
  16172. const bool noWrap;
  16173. bool isEof;
  16174. int activeBufferSize;
  16175. int64 originalSourcePos, currentPos;
  16176. HeapBlock <uint8> buffer;
  16177. class GZIPDecompressHelper;
  16178. friend class ScopedPointer <GZIPDecompressHelper>;
  16179. ScopedPointer <GZIPDecompressHelper> helper;
  16180. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPDecompressorInputStream);
  16181. };
  16182. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16183. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  16184. #endif
  16185. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  16186. #endif
  16187. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  16188. #endif
  16189. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16190. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  16191. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16192. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16193. /**
  16194. Allows a block of data and to be accessed as a stream.
  16195. This can either be used to refer to a shared block of memory, or can make its
  16196. own internal copy of the data when the MemoryInputStream is created.
  16197. */
  16198. class JUCE_API MemoryInputStream : public InputStream
  16199. {
  16200. public:
  16201. /** Creates a MemoryInputStream.
  16202. @param sourceData the block of data to use as the stream's source
  16203. @param sourceDataSize the number of bytes in the source data block
  16204. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  16205. the source data, so this data shouldn't be changed
  16206. for the lifetime of the stream; if this parameter is
  16207. true, the stream will make its own copy of the
  16208. data and use that.
  16209. */
  16210. MemoryInputStream (const void* sourceData,
  16211. size_t sourceDataSize,
  16212. bool keepInternalCopyOfData);
  16213. /** Creates a MemoryInputStream.
  16214. @param data a block of data to use as the stream's source
  16215. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  16216. the source data, so this data shouldn't be changed
  16217. for the lifetime of the stream; if this parameter is
  16218. true, the stream will make its own copy of the
  16219. data and use that.
  16220. */
  16221. MemoryInputStream (const MemoryBlock& data,
  16222. bool keepInternalCopyOfData);
  16223. /** Destructor. */
  16224. ~MemoryInputStream();
  16225. int64 getPosition();
  16226. bool setPosition (int64 pos);
  16227. int64 getTotalLength();
  16228. bool isExhausted();
  16229. int read (void* destBuffer, int maxBytesToRead);
  16230. private:
  16231. const char* data;
  16232. size_t dataSize, position;
  16233. MemoryBlock internalCopy;
  16234. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryInputStream);
  16235. };
  16236. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16237. /*** End of inlined file: juce_MemoryInputStream.h ***/
  16238. #endif
  16239. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16240. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  16241. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16242. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16243. /**
  16244. Writes data to an internal memory buffer, which grows as required.
  16245. The data that was written into the stream can then be accessed later as
  16246. a contiguous block of memory.
  16247. */
  16248. class JUCE_API MemoryOutputStream : public OutputStream
  16249. {
  16250. public:
  16251. /** Creates an empty memory stream ready for writing into.
  16252. @param initialSize the intial amount of capacity to allocate for writing into
  16253. */
  16254. MemoryOutputStream (size_t initialSize = 256);
  16255. /** Creates a memory stream for writing into into a pre-existing MemoryBlock object.
  16256. Note that the destination block will always be larger than the amount of data
  16257. that has been written to the stream, because the MemoryOutputStream keeps some
  16258. spare capactity at its end. To trim the block's size down to fit the actual
  16259. data, call flush(), or delete the MemoryOutputStream.
  16260. @param memoryBlockToWriteTo the block into which new data will be written.
  16261. @param appendToExistingBlockContent if this is true, the contents of the block will be
  16262. kept, and new data will be appended to it. If false,
  16263. the block will be cleared before use
  16264. */
  16265. MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  16266. bool appendToExistingBlockContent);
  16267. /** Destructor.
  16268. This will free any data that was written to it.
  16269. */
  16270. ~MemoryOutputStream();
  16271. /** Returns a pointer to the data that has been written to the stream.
  16272. @see getDataSize
  16273. */
  16274. const void* getData() const noexcept;
  16275. /** Returns the number of bytes of data that have been written to the stream.
  16276. @see getData
  16277. */
  16278. size_t getDataSize() const noexcept { return size; }
  16279. /** Resets the stream, clearing any data that has been written to it so far. */
  16280. void reset() noexcept;
  16281. /** Increases the internal storage capacity to be able to contain at least the specified
  16282. amount of data without needing to be resized.
  16283. */
  16284. void preallocate (size_t bytesToPreallocate);
  16285. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  16286. const String toUTF8() const;
  16287. /** Attempts to detect the encoding of the data and convert it to a string.
  16288. @see String::createStringFromData
  16289. */
  16290. const String toString() const;
  16291. /** If the stream is writing to a user-supplied MemoryBlock, this will trim any excess
  16292. capacity off the block, so that its length matches the amount of actual data that
  16293. has been written so far.
  16294. */
  16295. void flush();
  16296. bool write (const void* buffer, int howMany);
  16297. int64 getPosition() { return position; }
  16298. bool setPosition (int64 newPosition);
  16299. int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  16300. private:
  16301. MemoryBlock& data;
  16302. MemoryBlock internalBlock;
  16303. size_t position, size;
  16304. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryOutputStream);
  16305. };
  16306. /** Copies all the data that has been written to a MemoryOutputStream into another stream. */
  16307. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead);
  16308. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16309. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  16310. #endif
  16311. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  16312. #endif
  16313. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16314. /*** Start of inlined file: juce_SubregionStream.h ***/
  16315. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16316. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16317. /** Wraps another input stream, and reads from a specific part of it.
  16318. This lets you take a subsection of a stream and present it as an entire
  16319. stream in its own right.
  16320. */
  16321. class JUCE_API SubregionStream : public InputStream
  16322. {
  16323. public:
  16324. /** Creates a SubregionStream from an input source.
  16325. @param sourceStream the source stream to read from
  16326. @param startPositionInSourceStream this is the position in the source stream that
  16327. corresponds to position 0 in this stream
  16328. @param lengthOfSourceStream this specifies the maximum number of bytes
  16329. from the source stream that will be passed through
  16330. by this stream. When the position of this stream
  16331. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  16332. If the length passed in here is greater than the length
  16333. of the source stream (as returned by getTotalLength()),
  16334. then the smaller value will be used.
  16335. Passing a negative value for this parameter means it
  16336. will keep reading until the source's end-of-stream.
  16337. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  16338. deleted by this object when it is itself deleted.
  16339. */
  16340. SubregionStream (InputStream* sourceStream,
  16341. int64 startPositionInSourceStream,
  16342. int64 lengthOfSourceStream,
  16343. bool deleteSourceWhenDestroyed);
  16344. /** Destructor.
  16345. This may also delete the source stream, if that option was chosen when the
  16346. buffered stream was created.
  16347. */
  16348. ~SubregionStream();
  16349. int64 getTotalLength();
  16350. int64 getPosition();
  16351. bool setPosition (int64 newPosition);
  16352. int read (void* destBuffer, int maxBytesToRead);
  16353. bool isExhausted();
  16354. private:
  16355. OptionalScopedPointer<InputStream> source;
  16356. const int64 startPositionInSourceStream, lengthOfSourceStream;
  16357. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubregionStream);
  16358. };
  16359. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16360. /*** End of inlined file: juce_SubregionStream.h ***/
  16361. #endif
  16362. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  16363. #endif
  16364. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  16365. /*** Start of inlined file: juce_Expression.h ***/
  16366. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  16367. #define __JUCE_EXPRESSION_JUCEHEADER__
  16368. /**
  16369. A class for dynamically evaluating simple numeric expressions.
  16370. This class can parse a simple C-style string expression involving floating point
  16371. numbers, named symbols and functions. The basic arithmetic operations of +, -, *, /
  16372. are supported, as well as parentheses, and any alphanumeric identifiers are
  16373. assumed to be named symbols which will be resolved when the expression is
  16374. evaluated.
  16375. Expressions which use identifiers and functions require a subclass of
  16376. Expression::Scope to be supplied when evaluating them, and this object
  16377. is expected to be able to resolve the symbol names and perform the functions that
  16378. are used.
  16379. */
  16380. class JUCE_API Expression
  16381. {
  16382. public:
  16383. /** Creates a simple expression with a value of 0. */
  16384. Expression();
  16385. /** Destructor. */
  16386. ~Expression();
  16387. /** Creates a simple expression with a specified constant value. */
  16388. explicit Expression (double constant);
  16389. /** Creates a copy of an expression. */
  16390. Expression (const Expression& other);
  16391. /** Copies another expression. */
  16392. Expression& operator= (const Expression& other);
  16393. /** Creates an expression by parsing a string.
  16394. If there's a syntax error in the string, this will throw a ParseError exception.
  16395. @throws ParseError
  16396. */
  16397. explicit Expression (const String& stringToParse);
  16398. /** Returns a string version of the expression. */
  16399. const String toString() const;
  16400. /** Returns an expression which is an addtion operation of two existing expressions. */
  16401. const Expression operator+ (const Expression& other) const;
  16402. /** Returns an expression which is a subtraction operation of two existing expressions. */
  16403. const Expression operator- (const Expression& other) const;
  16404. /** Returns an expression which is a multiplication operation of two existing expressions. */
  16405. const Expression operator* (const Expression& other) const;
  16406. /** Returns an expression which is a division operation of two existing expressions. */
  16407. const Expression operator/ (const Expression& other) const;
  16408. /** Returns an expression which performs a negation operation on an existing expression. */
  16409. const Expression operator-() const;
  16410. /** Returns an Expression which is an identifier reference. */
  16411. static const Expression symbol (const String& symbol);
  16412. /** Returns an Expression which is a function call. */
  16413. static const Expression function (const String& functionName, const Array<Expression>& parameters);
  16414. /** Returns an Expression which parses a string from a character pointer, and updates the pointer
  16415. to indicate where it finished.
  16416. The pointer is incremented so that on return, it indicates the character that follows
  16417. the end of the expression that was parsed.
  16418. If there's a syntax error in the string, this will throw a ParseError exception.
  16419. @throws ParseError
  16420. */
  16421. static const Expression parse (String::CharPointerType& stringToParse);
  16422. /** When evaluating an Expression object, this class is used to resolve symbols and
  16423. perform functions that the expression uses.
  16424. */
  16425. class JUCE_API Scope
  16426. {
  16427. public:
  16428. Scope();
  16429. virtual ~Scope();
  16430. /** Returns some kind of globally unique ID that identifies this scope. */
  16431. virtual const String getScopeUID() const;
  16432. /** Returns the value of a symbol.
  16433. If the symbol is unknown, this can throw an Expression::EvaluationError exception.
  16434. The member value is set to the part of the symbol that followed the dot, if there is
  16435. one, e.g. for "foo.bar", symbol = "foo" and member = "bar".
  16436. @throws Expression::EvaluationError
  16437. */
  16438. virtual const Expression getSymbolValue (const String& symbol) const;
  16439. /** Executes a named function.
  16440. If the function name is unknown, this can throw an Expression::EvaluationError exception.
  16441. @throws Expression::EvaluationError
  16442. */
  16443. virtual double evaluateFunction (const String& functionName,
  16444. const double* parameters, int numParameters) const;
  16445. /** Used as a callback by the Scope::visitRelativeScope() method.
  16446. You should never create an instance of this class yourself, it's used by the
  16447. expression evaluation code.
  16448. */
  16449. class Visitor
  16450. {
  16451. public:
  16452. virtual ~Visitor() {}
  16453. virtual void visit (const Scope&) = 0;
  16454. };
  16455. /** Creates a Scope object for a named scope, and then calls a visitor
  16456. to do some kind of processing with this new scope.
  16457. If the name is valid, this method must create a suitable (temporary) Scope
  16458. object to represent it, and must call the Visitor::visit() method with this
  16459. new scope.
  16460. */
  16461. virtual void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  16462. };
  16463. /** Evaluates this expression, without using a Scope.
  16464. Without a Scope, no symbols can be used, and only basic functions such as sin, cos, tan,
  16465. min, max are available.
  16466. To find out about any errors during evaluation, use the other version of this method which
  16467. takes a String parameter.
  16468. */
  16469. double evaluate() const;
  16470. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  16471. or functions that it uses.
  16472. To find out about any errors during evaluation, use the other version of this method which
  16473. takes a String parameter.
  16474. */
  16475. double evaluate (const Scope& scope) const;
  16476. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  16477. or functions that it uses.
  16478. */
  16479. double evaluate (const Scope& scope, String& evaluationError) const;
  16480. /** Attempts to return an expression which is a copy of this one, but with a constant adjusted
  16481. to make the expression resolve to a target value.
  16482. E.g. if the expression is "x + 10" and x is 5, then asking for a target value of 8 will return
  16483. the expression "x + 3". Obviously some expressions can't be reversed in this way, in which
  16484. case they might just be adjusted by adding a constant to the original expression.
  16485. @throws Expression::EvaluationError
  16486. */
  16487. const Expression adjustedToGiveNewResult (double targetValue, const Scope& scope) const;
  16488. /** Represents a symbol that is used in an Expression. */
  16489. struct Symbol
  16490. {
  16491. Symbol (const String& scopeUID, const String& symbolName);
  16492. bool operator== (const Symbol&) const noexcept;
  16493. bool operator!= (const Symbol&) const noexcept;
  16494. String scopeUID; /**< The unique ID of the Scope that contains this symbol. */
  16495. String symbolName; /**< The name of the symbol. */
  16496. };
  16497. /** Returns a copy of this expression in which all instances of a given symbol have been renamed. */
  16498. const Expression withRenamedSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope) const;
  16499. /** Returns true if this expression makes use of the specified symbol.
  16500. If a suitable scope is supplied, the search will dereference and recursively check
  16501. all symbols, so that it can be determined whether this expression relies on the given
  16502. symbol at any level in its evaluation. If the scope parameter is null, this just checks
  16503. whether the expression contains any direct references to the symbol.
  16504. @throws Expression::EvaluationError
  16505. */
  16506. bool referencesSymbol (const Symbol& symbol, const Scope& scope) const;
  16507. /** Returns true if this expression contains any symbols. */
  16508. bool usesAnySymbols() const;
  16509. /** Returns a list of all symbols that may be needed to resolve this expression in the given scope. */
  16510. void findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const;
  16511. /** An exception that can be thrown by Expression::parse(). */
  16512. class ParseError : public std::exception
  16513. {
  16514. public:
  16515. ParseError (const String& message);
  16516. String description;
  16517. };
  16518. /** Expression type.
  16519. @see Expression::getType()
  16520. */
  16521. enum Type
  16522. {
  16523. constantType,
  16524. functionType,
  16525. operatorType,
  16526. symbolType
  16527. };
  16528. /** Returns the type of this expression. */
  16529. Type getType() const noexcept;
  16530. /** If this expression is a symbol, function or operator, this returns its identifier. */
  16531. const String getSymbolOrFunction() const;
  16532. /** Returns the number of inputs to this expression.
  16533. @see getInput
  16534. */
  16535. int getNumInputs() const;
  16536. /** Retrieves one of the inputs to this expression.
  16537. @see getNumInputs
  16538. */
  16539. const Expression getInput (int index) const;
  16540. private:
  16541. class Term;
  16542. class Helpers;
  16543. friend class Term;
  16544. friend class Helpers;
  16545. friend class ScopedPointer<Term>;
  16546. friend class ReferenceCountedObjectPtr<Term>;
  16547. ReferenceCountedObjectPtr<Term> term;
  16548. explicit Expression (Term* term);
  16549. };
  16550. #endif // __JUCE_EXPRESSION_JUCEHEADER__
  16551. /*** End of inlined file: juce_Expression.h ***/
  16552. #endif
  16553. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  16554. #endif
  16555. #ifndef __JUCE_RANDOM_JUCEHEADER__
  16556. /*** Start of inlined file: juce_Random.h ***/
  16557. #ifndef __JUCE_RANDOM_JUCEHEADER__
  16558. #define __JUCE_RANDOM_JUCEHEADER__
  16559. /**
  16560. A random number generator.
  16561. You can create a Random object and use it to generate a sequence of random numbers.
  16562. As a handy shortcut to avoid having to create and seed one yourself, you can call
  16563. Random::getSystemRandom() to return a global RNG that is seeded randomly when the
  16564. app launches.
  16565. */
  16566. class JUCE_API Random
  16567. {
  16568. public:
  16569. /** Creates a Random object based on a seed value.
  16570. For a given seed value, the subsequent numbers generated by this object
  16571. will be predictable, so a good idea is to set this value based
  16572. on the time, e.g.
  16573. new Random (Time::currentTimeMillis())
  16574. */
  16575. explicit Random (int64 seedValue) noexcept;
  16576. /** Destructor. */
  16577. ~Random() noexcept;
  16578. /** Returns the next random 32 bit integer.
  16579. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  16580. */
  16581. int nextInt() noexcept;
  16582. /** Returns the next random number, limited to a given range.
  16583. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  16584. */
  16585. int nextInt (int maxValue) noexcept;
  16586. /** Returns the next 64-bit random number.
  16587. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  16588. */
  16589. int64 nextInt64() noexcept;
  16590. /** Returns the next random floating-point number.
  16591. @returns a random value in the range 0 to 1.0
  16592. */
  16593. float nextFloat() noexcept;
  16594. /** Returns the next random floating-point number.
  16595. @returns a random value in the range 0 to 1.0
  16596. */
  16597. double nextDouble() noexcept;
  16598. /** Returns the next random boolean value.
  16599. */
  16600. bool nextBool() noexcept;
  16601. /** Returns a BigInteger containing a random number.
  16602. @returns a random value in the range 0 to (maximumValue - 1).
  16603. */
  16604. const BigInteger nextLargeNumber (const BigInteger& maximumValue);
  16605. /** Sets a range of bits in a BigInteger to random values. */
  16606. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  16607. /** To avoid the overhead of having to create a new Random object whenever
  16608. you need a number, this is a shared application-wide object that
  16609. can be used.
  16610. It's not thread-safe though, so threads should use their own Random object.
  16611. */
  16612. static Random& getSystemRandom() noexcept;
  16613. /** Resets this Random object to a given seed value. */
  16614. void setSeed (int64 newSeed) noexcept;
  16615. /** Merges this object's seed with another value.
  16616. This sets the seed to be a value created by combining the current seed and this
  16617. new value.
  16618. */
  16619. void combineSeed (int64 seedValue) noexcept;
  16620. /** Reseeds this generator using a value generated from various semi-random system
  16621. properties like the current time, etc.
  16622. Because this function convolves the time with the last seed value, calling
  16623. it repeatedly will increase the randomness of the final result.
  16624. */
  16625. void setSeedRandomly();
  16626. private:
  16627. int64 seed;
  16628. JUCE_LEAK_DETECTOR (Random);
  16629. };
  16630. #endif // __JUCE_RANDOM_JUCEHEADER__
  16631. /*** End of inlined file: juce_Random.h ***/
  16632. #endif
  16633. #ifndef __JUCE_RANGE_JUCEHEADER__
  16634. #endif
  16635. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  16636. #endif
  16637. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  16638. #endif
  16639. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  16640. #endif
  16641. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  16642. #endif
  16643. #ifndef __JUCE_MEMORY_JUCEHEADER__
  16644. #endif
  16645. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  16646. #endif
  16647. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  16648. #endif
  16649. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  16650. #endif
  16651. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  16652. #endif
  16653. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  16654. /*** Start of inlined file: juce_WeakReference.h ***/
  16655. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  16656. #define __JUCE_WEAKREFERENCE_JUCEHEADER__
  16657. /**
  16658. This class acts as a pointer which will automatically become null if the object
  16659. to which it points is deleted.
  16660. To accomplish this, the source object needs to cooperate by performing a couple of simple tasks.
  16661. It must provide a getWeakReference() method and embed a WeakReference::Master object, which stores
  16662. a shared pointer object. It must also clear this master pointer when it's getting deleted.
  16663. E.g.
  16664. @code
  16665. class MyObject
  16666. {
  16667. public:
  16668. MyObject()
  16669. {
  16670. // If you're planning on using your WeakReferences in a multi-threaded situation, you may choose
  16671. // to call getWeakReference() here in the constructor, which will pre-initialise it, avoiding an
  16672. // (extremely unlikely) race condition that could occur if multiple threads overlap while making
  16673. // the first call to getWeakReference().
  16674. }
  16675. ~MyObject()
  16676. {
  16677. // This will zero all the references - you need to call this in your destructor.
  16678. masterReference.clear();
  16679. }
  16680. // Your object must provide a method that looks pretty much identical to this (except
  16681. // for the templated class name, of course).
  16682. const WeakReference<MyObject>::SharedRef& getWeakReference()
  16683. {
  16684. return masterReference (this);
  16685. }
  16686. private:
  16687. // You need to embed one of these inside your object. It can be private.
  16688. WeakReference<MyObject>::Master masterReference;
  16689. };
  16690. // Here's an example of using a pointer..
  16691. MyObject* n = new MyObject();
  16692. WeakReference<MyObject> myObjectRef = n;
  16693. MyObject* pointer1 = myObjectRef; // returns a valid pointer to 'n'
  16694. delete n;
  16695. MyObject* pointer2 = myObjectRef; // returns a null pointer
  16696. @endcode
  16697. @see WeakReference::Master
  16698. */
  16699. template <class ObjectType>
  16700. class WeakReference
  16701. {
  16702. public:
  16703. /** Creates a null SafePointer. */
  16704. WeakReference() noexcept {}
  16705. /** Creates a WeakReference that points at the given object. */
  16706. WeakReference (ObjectType* const object) : holder (object != nullptr ? object->getWeakReference() : nullptr) {}
  16707. /** Creates a copy of another WeakReference. */
  16708. WeakReference (const WeakReference& other) noexcept : holder (other.holder) {}
  16709. /** Copies another pointer to this one. */
  16710. WeakReference& operator= (const WeakReference& other) { holder = other.holder; return *this; }
  16711. /** Copies another pointer to this one. */
  16712. WeakReference& operator= (ObjectType* const newObject) { holder = (newObject != nullptr) ? newObject->getWeakReference() : nullptr; return *this; }
  16713. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16714. ObjectType* get() const noexcept { return holder != nullptr ? holder->get() : nullptr; }
  16715. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16716. operator ObjectType*() const noexcept { return get(); }
  16717. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16718. ObjectType* operator->() noexcept { return get(); }
  16719. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16720. const ObjectType* operator->() const noexcept { return get(); }
  16721. /** This returns true if this reference has been pointing at an object, but that object has
  16722. since been deleted.
  16723. If this reference was only ever pointing at a null pointer, this will return false. Using
  16724. operator=() to make this refer to a different object will reset this flag to match the status
  16725. of the reference from which you're copying.
  16726. */
  16727. bool wasObjectDeleted() const noexcept { return holder != nullptr && holder->get() == nullptr; }
  16728. bool operator== (ObjectType* const object) const noexcept { return get() == object; }
  16729. bool operator!= (ObjectType* const object) const noexcept { return get() != object; }
  16730. /** This class is used internally by the WeakReference class - don't use it directly
  16731. in your code!
  16732. @see WeakReference
  16733. */
  16734. class SharedPointer : public ReferenceCountedObject
  16735. {
  16736. public:
  16737. explicit SharedPointer (ObjectType* const owner_) noexcept : owner (owner_) {}
  16738. inline ObjectType* get() const noexcept { return owner; }
  16739. void clearPointer() noexcept { owner = nullptr; }
  16740. private:
  16741. ObjectType* volatile owner;
  16742. JUCE_DECLARE_NON_COPYABLE (SharedPointer);
  16743. };
  16744. typedef ReferenceCountedObjectPtr<SharedPointer> SharedRef;
  16745. /**
  16746. This class is embedded inside an object to which you want to attach WeakReference pointers.
  16747. See the WeakReference class notes for an example of how to use this class.
  16748. @see WeakReference
  16749. */
  16750. class Master
  16751. {
  16752. public:
  16753. Master() noexcept {}
  16754. ~Master()
  16755. {
  16756. // You must remember to call clear() in your source object's destructor! See the notes
  16757. // for the WeakReference class for an example of how to do this.
  16758. jassert (sharedPointer == nullptr || sharedPointer->get() == nullptr);
  16759. }
  16760. /** The first call to this method will create an internal object that is shared by all weak
  16761. references to the object.
  16762. You need to call this from your main object's getWeakReference() method - see the WeakReference
  16763. class notes for an example.
  16764. */
  16765. const SharedRef& operator() (ObjectType* const object)
  16766. {
  16767. if (sharedPointer == nullptr)
  16768. {
  16769. sharedPointer = new SharedPointer (object);
  16770. }
  16771. else
  16772. {
  16773. // You're trying to create a weak reference to an object that has already been deleted!!
  16774. jassert (sharedPointer->get() != nullptr);
  16775. }
  16776. return sharedPointer;
  16777. }
  16778. /** The object that owns this master pointer should call this before it gets destroyed,
  16779. to zero all the references to this object that may be out there. See the WeakReference
  16780. class notes for an example of how to do this.
  16781. */
  16782. void clear()
  16783. {
  16784. if (sharedPointer != nullptr)
  16785. sharedPointer->clearPointer();
  16786. }
  16787. private:
  16788. SharedRef sharedPointer;
  16789. JUCE_DECLARE_NON_COPYABLE (Master);
  16790. };
  16791. private:
  16792. SharedRef holder;
  16793. };
  16794. #endif // __JUCE_WEAKREFERENCE_JUCEHEADER__
  16795. /*** End of inlined file: juce_WeakReference.h ***/
  16796. #endif
  16797. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  16798. #endif
  16799. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  16800. #endif
  16801. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  16802. #endif
  16803. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  16804. #endif
  16805. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  16806. #endif
  16807. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  16808. #endif
  16809. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16810. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  16811. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16812. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16813. /** Used in the same way as the T(text) macro, this will attempt to translate a
  16814. string into a localised version using the LocalisedStrings class.
  16815. @see LocalisedStrings
  16816. */
  16817. #define TRANS(stringLiteral) \
  16818. JUCE_NAMESPACE::LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  16819. /**
  16820. Used to convert strings to localised foreign-language versions.
  16821. This is basically a look-up table of strings and their translated equivalents.
  16822. It can be loaded from a text file, so that you can supply a set of localised
  16823. versions of strings that you use in your app.
  16824. To use it in your code, simply call the translate() method on each string that
  16825. might have foreign versions, and if none is found, the method will just return
  16826. the original string.
  16827. The translation file should start with some lines specifying a description of
  16828. the language it contains, and also a list of ISO country codes where it might
  16829. be appropriate to use the file. After that, each line of the file should contain
  16830. a pair of quoted strings with an '=' sign.
  16831. E.g. for a french translation, the file might be:
  16832. @code
  16833. language: French
  16834. countries: fr be mc ch lu
  16835. "hello" = "bonjour"
  16836. "goodbye" = "au revoir"
  16837. @endcode
  16838. If the strings need to contain a quote character, they can use '\"' instead, and
  16839. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  16840. (you can use this to add comments).
  16841. Note that this is a singleton class, so don't create or destroy the object directly.
  16842. There's also a TRANS(text) macro defined to make it easy to use the this.
  16843. E.g. @code
  16844. printSomething (TRANS("hello"));
  16845. @endcode
  16846. This macro is used in the Juce classes themselves, so your application has a chance to
  16847. intercept and translate any internal Juce text strings that might be shown. (You can easily
  16848. get a list of all the messages by searching for the TRANS() macro in the Juce source
  16849. code).
  16850. */
  16851. class JUCE_API LocalisedStrings
  16852. {
  16853. public:
  16854. /** Creates a set of translations from the text of a translation file.
  16855. When you create one of these, you can call setCurrentMappings() to make it
  16856. the set of mappings that the system's using.
  16857. */
  16858. LocalisedStrings (const String& fileContents);
  16859. /** Creates a set of translations from a file.
  16860. When you create one of these, you can call setCurrentMappings() to make it
  16861. the set of mappings that the system's using.
  16862. */
  16863. LocalisedStrings (const File& fileToLoad);
  16864. /** Destructor. */
  16865. ~LocalisedStrings();
  16866. /** Selects the current set of mappings to be used by the system.
  16867. The object you pass in will be automatically deleted when no longer needed, so
  16868. don't keep a pointer to it. You can also pass in zero to remove the current
  16869. mappings.
  16870. See also the TRANS() macro, which uses the current set to do its translation.
  16871. @see translateWithCurrentMappings
  16872. */
  16873. static void setCurrentMappings (LocalisedStrings* newTranslations);
  16874. /** Returns the currently selected set of mappings.
  16875. This is the object that was last passed to setCurrentMappings(). It may
  16876. be 0 if none has been created.
  16877. */
  16878. static LocalisedStrings* getCurrentMappings();
  16879. /** Tries to translate a string using the currently selected set of mappings.
  16880. If no mapping has been set, or if the mapping doesn't contain a translation
  16881. for the string, this will just return the original string.
  16882. See also the TRANS() macro, which uses this method to do its translation.
  16883. @see setCurrentMappings, getCurrentMappings
  16884. */
  16885. static const String translateWithCurrentMappings (const String& text);
  16886. /** Tries to translate a string using the currently selected set of mappings.
  16887. If no mapping has been set, or if the mapping doesn't contain a translation
  16888. for the string, this will just return the original string.
  16889. See also the TRANS() macro, which uses this method to do its translation.
  16890. @see setCurrentMappings, getCurrentMappings
  16891. */
  16892. static const String translateWithCurrentMappings (const char* text);
  16893. /** Attempts to look up a string and return its localised version.
  16894. If the string isn't found in the list, the original string will be returned.
  16895. */
  16896. const String translate (const String& text) const;
  16897. /** Returns the name of the language specified in the translation file.
  16898. This is specified in the file using a line starting with "language:", e.g.
  16899. @code
  16900. language: german
  16901. @endcode
  16902. */
  16903. const String getLanguageName() const { return languageName; }
  16904. /** Returns the list of suitable country codes listed in the translation file.
  16905. These is specified in the file using a line starting with "countries:", e.g.
  16906. @code
  16907. countries: fr be mc ch lu
  16908. @endcode
  16909. The country codes are supposed to be 2-character ISO complient codes.
  16910. */
  16911. const StringArray getCountryCodes() const { return countryCodes; }
  16912. /** Indicates whether to use a case-insensitive search when looking up a string.
  16913. This defaults to true.
  16914. */
  16915. void setIgnoresCase (bool shouldIgnoreCase);
  16916. private:
  16917. String languageName;
  16918. StringArray countryCodes;
  16919. StringPairArray translations;
  16920. void loadFromText (const String& fileContents);
  16921. JUCE_LEAK_DETECTOR (LocalisedStrings);
  16922. };
  16923. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16924. /*** End of inlined file: juce_LocalisedStrings.h ***/
  16925. #endif
  16926. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  16927. #endif
  16928. #ifndef __JUCE_STRING_JUCEHEADER__
  16929. #endif
  16930. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  16931. #endif
  16932. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  16933. #endif
  16934. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  16935. #endif
  16936. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  16937. /*** Start of inlined file: juce_XmlDocument.h ***/
  16938. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  16939. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  16940. /**
  16941. Parses a text-based XML document and creates an XmlElement object from it.
  16942. The parser will parse DTDs to load external entities but won't
  16943. check the document for validity against the DTD.
  16944. e.g.
  16945. @code
  16946. XmlDocument myDocument (File ("myfile.xml"));
  16947. XmlElement* mainElement = myDocument.getDocumentElement();
  16948. if (mainElement == nullptr)
  16949. {
  16950. String error = myDocument.getLastParseError();
  16951. }
  16952. else
  16953. {
  16954. ..use the element
  16955. }
  16956. @endcode
  16957. Or you can use the static helper methods for quick parsing..
  16958. @code
  16959. XmlElement* xml = XmlDocument::parse (myXmlFile);
  16960. if (xml != nullptr && xml->hasTagName ("foobar"))
  16961. {
  16962. ...etc
  16963. @endcode
  16964. @see XmlElement
  16965. */
  16966. class JUCE_API XmlDocument
  16967. {
  16968. public:
  16969. /** Creates an XmlDocument from the xml text.
  16970. The text doesn't actually get parsed until the getDocumentElement() method is called.
  16971. */
  16972. XmlDocument (const String& documentText);
  16973. /** Creates an XmlDocument from a file.
  16974. The text doesn't actually get parsed until the getDocumentElement() method is called.
  16975. */
  16976. XmlDocument (const File& file);
  16977. /** Destructor. */
  16978. ~XmlDocument();
  16979. /** Creates an XmlElement object to represent the main document node.
  16980. This method will do the actual parsing of the text, and if there's a
  16981. parse error, it may returns 0 (and you can find out the error using
  16982. the getLastParseError() method).
  16983. See also the parse() methods, which provide a shorthand way to quickly
  16984. parse a file or string.
  16985. @param onlyReadOuterDocumentElement if true, the parser will only read the
  16986. first section of the file, and will only
  16987. return the outer document element - this
  16988. allows quick checking of large files to
  16989. see if they contain the correct type of
  16990. tag, without having to parse the entire file
  16991. @returns a new XmlElement which the caller will need to delete, or null if
  16992. there was an error.
  16993. @see getLastParseError
  16994. */
  16995. XmlElement* getDocumentElement (bool onlyReadOuterDocumentElement = false);
  16996. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  16997. @returns the error, or an empty string if there was no error.
  16998. */
  16999. const String& getLastParseError() const noexcept;
  17000. /** Sets an input source object to use for parsing documents that reference external entities.
  17001. If the document has been created from a file, this probably won't be needed, but
  17002. if you're parsing some text and there might be a DTD that references external
  17003. files, you may need to create a custom input source that can retrieve the
  17004. other files it needs.
  17005. The object that is passed-in will be deleted automatically when no longer needed.
  17006. @see InputSource
  17007. */
  17008. void setInputSource (InputSource* newSource) noexcept;
  17009. /** Sets a flag to change the treatment of empty text elements.
  17010. If this is true (the default state), then any text elements that contain only
  17011. whitespace characters will be ingored during parsing. If you need to catch
  17012. whitespace-only text, then you should set this to false before calling the
  17013. getDocumentElement() method.
  17014. */
  17015. void setEmptyTextElementsIgnored (bool shouldBeIgnored) noexcept;
  17016. /** A handy static method that parses a file.
  17017. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  17018. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  17019. */
  17020. static XmlElement* parse (const File& file);
  17021. /** A handy static method that parses some XML data.
  17022. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  17023. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  17024. */
  17025. static XmlElement* parse (const String& xmlData);
  17026. private:
  17027. String originalText;
  17028. String::CharPointerType input;
  17029. bool outOfData, errorOccurred;
  17030. String lastError, dtdText;
  17031. StringArray tokenisedDTD;
  17032. bool needToLoadDTD, ignoreEmptyTextElements;
  17033. ScopedPointer <InputSource> inputSource;
  17034. void setLastError (const String& desc, bool carryOn);
  17035. void skipHeader();
  17036. void skipNextWhiteSpace();
  17037. juce_wchar readNextChar() noexcept;
  17038. XmlElement* readNextElement (bool alsoParseSubElements);
  17039. void readChildElements (XmlElement* parent);
  17040. int findNextTokenLength() noexcept;
  17041. void readQuotedString (String& result);
  17042. void readEntity (String& result);
  17043. const String getFileContents (const String& filename) const;
  17044. const String expandEntity (const String& entity);
  17045. const String expandExternalEntity (const String& entity);
  17046. const String getParameterEntity (const String& entity);
  17047. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XmlDocument);
  17048. };
  17049. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  17050. /*** End of inlined file: juce_XmlDocument.h ***/
  17051. #endif
  17052. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  17053. #endif
  17054. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  17055. #endif
  17056. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17057. /*** Start of inlined file: juce_InterProcessLock.h ***/
  17058. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17059. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17060. /**
  17061. Acts as a critical section which processes can use to block each other.
  17062. @see CriticalSection
  17063. */
  17064. class JUCE_API InterProcessLock
  17065. {
  17066. public:
  17067. /** Creates a lock object.
  17068. @param name a name that processes will use to identify this lock object
  17069. */
  17070. explicit InterProcessLock (const String& name);
  17071. /** Destructor.
  17072. This will also release the lock if it's currently held by this process.
  17073. */
  17074. ~InterProcessLock();
  17075. /** Attempts to lock the critical section.
  17076. @param timeOutMillisecs how many milliseconds to wait if the lock
  17077. is already held by another process - a value of
  17078. 0 will return immediately, negative values will wait
  17079. forever
  17080. @returns true if the lock could be gained within the timeout period, or
  17081. false if the timeout expired.
  17082. */
  17083. bool enter (int timeOutMillisecs = -1);
  17084. /** Releases the lock if it's currently held by this process.
  17085. */
  17086. void exit();
  17087. /**
  17088. Automatically locks and unlocks an InterProcessLock object.
  17089. This works like a ScopedLock, but using an InterprocessLock rather than
  17090. a CriticalSection.
  17091. @see ScopedLock
  17092. */
  17093. class ScopedLockType
  17094. {
  17095. public:
  17096. /** Creates a scoped lock.
  17097. As soon as it is created, this will lock the InterProcessLock, and
  17098. when the ScopedLockType object is deleted, the InterProcessLock will
  17099. be unlocked.
  17100. Note that since an InterprocessLock can fail due to errors, you should check
  17101. isLocked() to make sure that the lock was successful before using it.
  17102. Make sure this object is created and deleted by the same thread,
  17103. otherwise there are no guarantees what will happen! Best just to use it
  17104. as a local stack object, rather than creating one with the new() operator.
  17105. */
  17106. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  17107. /** Destructor.
  17108. The InterProcessLock will be unlocked when the destructor is called.
  17109. Make sure this object is created and deleted by the same thread,
  17110. otherwise there are no guarantees what will happen!
  17111. */
  17112. inline ~ScopedLockType() { lock_.exit(); }
  17113. /** Returns true if the InterProcessLock was successfully locked. */
  17114. bool isLocked() const noexcept { return lockWasSuccessful; }
  17115. private:
  17116. InterProcessLock& lock_;
  17117. bool lockWasSuccessful;
  17118. JUCE_DECLARE_NON_COPYABLE (ScopedLockType);
  17119. };
  17120. private:
  17121. class Pimpl;
  17122. friend class ScopedPointer <Pimpl>;
  17123. ScopedPointer <Pimpl> pimpl;
  17124. CriticalSection lock;
  17125. String name;
  17126. JUCE_DECLARE_NON_COPYABLE (InterProcessLock);
  17127. };
  17128. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17129. /*** End of inlined file: juce_InterProcessLock.h ***/
  17130. #endif
  17131. #ifndef __JUCE_PROCESS_JUCEHEADER__
  17132. /*** Start of inlined file: juce_Process.h ***/
  17133. #ifndef __JUCE_PROCESS_JUCEHEADER__
  17134. #define __JUCE_PROCESS_JUCEHEADER__
  17135. /** Represents the current executable's process.
  17136. This contains methods for controlling the current application at the
  17137. process-level.
  17138. @see Thread, JUCEApplication
  17139. */
  17140. class JUCE_API Process
  17141. {
  17142. public:
  17143. enum ProcessPriority
  17144. {
  17145. LowPriority = 0,
  17146. NormalPriority = 1,
  17147. HighPriority = 2,
  17148. RealtimePriority = 3
  17149. };
  17150. /** Changes the current process's priority.
  17151. @param priority the process priority, where
  17152. 0=low, 1=normal, 2=high, 3=realtime
  17153. */
  17154. static void setPriority (const ProcessPriority priority);
  17155. /** Kills the current process immediately.
  17156. This is an emergency process terminator that kills the application
  17157. immediately - it's intended only for use only when something goes
  17158. horribly wrong.
  17159. @see JUCEApplication::quit
  17160. */
  17161. static void terminate();
  17162. /** Returns true if this application process is the one that the user is
  17163. currently using.
  17164. */
  17165. static bool isForegroundProcess();
  17166. /** Raises the current process's privilege level.
  17167. Does nothing if this isn't supported by the current OS, or if process
  17168. privilege level is fixed.
  17169. */
  17170. static void raisePrivilege();
  17171. /** Lowers the current process's privilege level.
  17172. Does nothing if this isn't supported by the current OS, or if process
  17173. privilege level is fixed.
  17174. */
  17175. static void lowerPrivilege();
  17176. /** Returns true if this process is being hosted by a debugger.
  17177. */
  17178. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  17179. private:
  17180. Process();
  17181. JUCE_DECLARE_NON_COPYABLE (Process);
  17182. };
  17183. #endif // __JUCE_PROCESS_JUCEHEADER__
  17184. /*** End of inlined file: juce_Process.h ***/
  17185. #endif
  17186. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  17187. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  17188. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  17189. #define __JUCE_READWRITELOCK_JUCEHEADER__
  17190. /*** Start of inlined file: juce_SpinLock.h ***/
  17191. #ifndef __JUCE_SPINLOCK_JUCEHEADER__
  17192. #define __JUCE_SPINLOCK_JUCEHEADER__
  17193. /**
  17194. A simple spin-lock class that can be used as a simple, low-overhead mutex for
  17195. uncontended situations.
  17196. Note that unlike a CriticalSection, this type of lock is not re-entrant, and may
  17197. be less efficient when used it a highly contended situation, but it's very small and
  17198. requires almost no initialisation.
  17199. It's most appropriate for simple situations where you're only going to hold the
  17200. lock for a very brief time.
  17201. @see CriticalSection
  17202. */
  17203. class JUCE_API SpinLock
  17204. {
  17205. public:
  17206. inline SpinLock() noexcept {}
  17207. inline ~SpinLock() noexcept {}
  17208. /** Acquires the lock.
  17209. This will block until the lock has been successfully acquired by this thread.
  17210. Note that a SpinLock is NOT re-entrant, and is not smart enough to know whether the
  17211. caller thread already has the lock - so if a thread tries to acquire a lock that it
  17212. already holds, this method will never return!
  17213. It's strongly recommended that you never call this method directly - instead use the
  17214. ScopedLockType class to manage the locking using an RAII pattern instead.
  17215. */
  17216. void enter() const noexcept;
  17217. /** Attempts to acquire the lock, returning true if this was successful. */
  17218. inline bool tryEnter() const noexcept
  17219. {
  17220. return lock.compareAndSetBool (1, 0);
  17221. }
  17222. /** Releases the lock. */
  17223. inline void exit() const noexcept
  17224. {
  17225. jassert (lock.value == 1); // Agh! Releasing a lock that isn't currently held!
  17226. lock = 0;
  17227. }
  17228. /** Provides the type of scoped lock to use for locking a SpinLock. */
  17229. typedef GenericScopedLock <SpinLock> ScopedLockType;
  17230. /** Provides the type of scoped unlocker to use with a SpinLock. */
  17231. typedef GenericScopedUnlock <SpinLock> ScopedUnlockType;
  17232. private:
  17233. mutable Atomic<int> lock;
  17234. JUCE_DECLARE_NON_COPYABLE (SpinLock);
  17235. };
  17236. #endif // __JUCE_SPINLOCK_JUCEHEADER__
  17237. /*** End of inlined file: juce_SpinLock.h ***/
  17238. /*** Start of inlined file: juce_WaitableEvent.h ***/
  17239. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  17240. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  17241. /**
  17242. Allows threads to wait for events triggered by other threads.
  17243. A thread can call wait() on a WaitableObject, and this will suspend the
  17244. calling thread until another thread wakes it up by calling the signal()
  17245. method.
  17246. */
  17247. class JUCE_API WaitableEvent
  17248. {
  17249. public:
  17250. /** Creates a WaitableEvent object.
  17251. @param manualReset If this is false, the event will be reset automatically when the wait()
  17252. method is called. If manualReset is true, then once the event is signalled,
  17253. the only way to reset it will be by calling the reset() method.
  17254. */
  17255. WaitableEvent (bool manualReset = false) noexcept;
  17256. /** Destructor.
  17257. If other threads are waiting on this object when it gets deleted, this
  17258. can cause nasty errors, so be careful!
  17259. */
  17260. ~WaitableEvent() noexcept;
  17261. /** Suspends the calling thread until the event has been signalled.
  17262. This will wait until the object's signal() method is called by another thread,
  17263. or until the timeout expires.
  17264. After the event has been signalled, this method will return true and if manualReset
  17265. was set to false in the WaitableEvent's constructor, then the event will be reset.
  17266. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  17267. value will cause it to wait forever.
  17268. @returns true if the object has been signalled, false if the timeout expires first.
  17269. @see signal, reset
  17270. */
  17271. bool wait (int timeOutMilliseconds = -1) const noexcept;
  17272. /** Wakes up any threads that are currently waiting on this object.
  17273. If signal() is called when nothing is waiting, the next thread to call wait()
  17274. will return immediately and reset the signal.
  17275. If the WaitableEvent is manual reset, all threads that are currently waiting on this
  17276. object will be woken.
  17277. If the WaitableEvent is automatic reset, and there are one or more threads waiting
  17278. on the object, then one of them will be woken up. If no threads are currently waiting,
  17279. then the next thread to call wait() will be woken up.
  17280. @see wait, reset
  17281. */
  17282. void signal() const noexcept;
  17283. /** Resets the event to an unsignalled state.
  17284. If it's not already signalled, this does nothing.
  17285. */
  17286. void reset() const noexcept;
  17287. private:
  17288. void* internal;
  17289. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WaitableEvent);
  17290. };
  17291. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  17292. /*** End of inlined file: juce_WaitableEvent.h ***/
  17293. /*** Start of inlined file: juce_Thread.h ***/
  17294. #ifndef __JUCE_THREAD_JUCEHEADER__
  17295. #define __JUCE_THREAD_JUCEHEADER__
  17296. /**
  17297. Encapsulates a thread.
  17298. Subclasses derive from Thread and implement the run() method, in which they
  17299. do their business. The thread can then be started with the startThread() method
  17300. and controlled with various other methods.
  17301. This class also contains some thread-related static methods, such
  17302. as sleep(), yield(), getCurrentThreadId() etc.
  17303. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  17304. MessageManagerLock
  17305. */
  17306. class JUCE_API Thread
  17307. {
  17308. public:
  17309. /**
  17310. Creates a thread.
  17311. When first created, the thread is not running. Use the startThread()
  17312. method to start it.
  17313. */
  17314. explicit Thread (const String& threadName);
  17315. /** Destructor.
  17316. Deleting a Thread object that is running will only give the thread a
  17317. brief opportunity to stop itself cleanly, so it's recommended that you
  17318. should always call stopThread() with a decent timeout before deleting,
  17319. to avoid the thread being forcibly killed (which is a Bad Thing).
  17320. */
  17321. virtual ~Thread();
  17322. /** Must be implemented to perform the thread's actual code.
  17323. Remember that the thread must regularly check the threadShouldExit()
  17324. method whilst running, and if this returns true it should return from
  17325. the run() method as soon as possible to avoid being forcibly killed.
  17326. @see threadShouldExit, startThread
  17327. */
  17328. virtual void run() = 0;
  17329. // Thread control functions..
  17330. /** Starts the thread running.
  17331. This will start the thread's run() method.
  17332. (if it's already started, startThread() won't do anything).
  17333. @see stopThread
  17334. */
  17335. void startThread();
  17336. /** Starts the thread with a given priority.
  17337. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  17338. If the thread is already running, its priority will be changed.
  17339. @see startThread, setPriority
  17340. */
  17341. void startThread (int priority);
  17342. /** Attempts to stop the thread running.
  17343. This method will cause the threadShouldExit() method to return true
  17344. and call notify() in case the thread is currently waiting.
  17345. Hopefully the thread will then respond to this by exiting cleanly, and
  17346. the stopThread method will wait for a given time-period for this to
  17347. happen.
  17348. If the thread is stuck and fails to respond after the time-out, it gets
  17349. forcibly killed, which is a very bad thing to happen, as it could still
  17350. be holding locks, etc. which are needed by other parts of your program.
  17351. @param timeOutMilliseconds The number of milliseconds to wait for the
  17352. thread to finish before killing it by force. A negative
  17353. value in here will wait forever.
  17354. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  17355. */
  17356. void stopThread (int timeOutMilliseconds);
  17357. /** Returns true if the thread is currently active */
  17358. bool isThreadRunning() const;
  17359. /** Sets a flag to tell the thread it should stop.
  17360. Calling this means that the threadShouldExit() method will then return true.
  17361. The thread should be regularly checking this to see whether it should exit.
  17362. If your thread makes use of wait(), you might want to call notify() after calling
  17363. this method, to interrupt any waits that might be in progress, and allow it
  17364. to reach a point where it can exit.
  17365. @see threadShouldExit
  17366. @see waitForThreadToExit
  17367. */
  17368. void signalThreadShouldExit();
  17369. /** Checks whether the thread has been told to stop running.
  17370. Threads need to check this regularly, and if it returns true, they should
  17371. return from their run() method at the first possible opportunity.
  17372. @see signalThreadShouldExit
  17373. */
  17374. inline bool threadShouldExit() const { return threadShouldExit_; }
  17375. /** Waits for the thread to stop.
  17376. This will waits until isThreadRunning() is false or until a timeout expires.
  17377. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  17378. is less than zero, it will wait forever.
  17379. @returns true if the thread exits, or false if the timeout expires first.
  17380. */
  17381. bool waitForThreadToExit (int timeOutMilliseconds) const;
  17382. /** Changes the thread's priority.
  17383. May return false if for some reason the priority can't be changed.
  17384. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  17385. of 5 is normal.
  17386. */
  17387. bool setPriority (int priority);
  17388. /** Changes the priority of the caller thread.
  17389. Similar to setPriority(), but this static method acts on the caller thread.
  17390. May return false if for some reason the priority can't be changed.
  17391. @see setPriority
  17392. */
  17393. static bool setCurrentThreadPriority (int priority);
  17394. /** Sets the affinity mask for the thread.
  17395. This will only have an effect next time the thread is started - i.e. if the
  17396. thread is already running when called, it'll have no effect.
  17397. @see setCurrentThreadAffinityMask
  17398. */
  17399. void setAffinityMask (uint32 affinityMask);
  17400. /** Changes the affinity mask for the caller thread.
  17401. This will change the affinity mask for the thread that calls this static method.
  17402. @see setAffinityMask
  17403. */
  17404. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  17405. // this can be called from any thread that needs to pause..
  17406. static void JUCE_CALLTYPE sleep (int milliseconds);
  17407. /** Yields the calling thread's current time-slot. */
  17408. static void JUCE_CALLTYPE yield();
  17409. /** Makes the thread wait for a notification.
  17410. This puts the thread to sleep until either the timeout period expires, or
  17411. another thread calls the notify() method to wake it up.
  17412. A negative time-out value means that the method will wait indefinitely.
  17413. @returns true if the event has been signalled, false if the timeout expires.
  17414. */
  17415. bool wait (int timeOutMilliseconds) const;
  17416. /** Wakes up the thread.
  17417. If the thread has called the wait() method, this will wake it up.
  17418. @see wait
  17419. */
  17420. void notify() const;
  17421. /** A value type used for thread IDs.
  17422. @see getCurrentThreadId(), getThreadId()
  17423. */
  17424. typedef void* ThreadID;
  17425. /** Returns an id that identifies the caller thread.
  17426. To find the ID of a particular thread object, use getThreadId().
  17427. @returns a unique identifier that identifies the calling thread.
  17428. @see getThreadId
  17429. */
  17430. static ThreadID getCurrentThreadId();
  17431. /** Finds the thread object that is currently running.
  17432. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  17433. object associated with them, so this will return 0.
  17434. */
  17435. static Thread* getCurrentThread();
  17436. /** Returns the ID of this thread.
  17437. That means the ID of this thread object - not of the thread that's calling the method.
  17438. This can change when the thread is started and stopped, and will be invalid if the
  17439. thread's not actually running.
  17440. @see getCurrentThreadId
  17441. */
  17442. ThreadID getThreadId() const noexcept { return threadId_; }
  17443. /** Returns the name of the thread.
  17444. This is the name that gets set in the constructor.
  17445. */
  17446. const String getThreadName() const { return threadName_; }
  17447. /** Returns the number of currently-running threads.
  17448. @returns the number of Thread objects known to be currently running.
  17449. @see stopAllThreads
  17450. */
  17451. static int getNumRunningThreads();
  17452. /** Tries to stop all currently-running threads.
  17453. This will attempt to stop all the threads known to be running at the moment.
  17454. */
  17455. static void stopAllThreads (int timeoutInMillisecs);
  17456. private:
  17457. const String threadName_;
  17458. void* volatile threadHandle_;
  17459. ThreadID threadId_;
  17460. CriticalSection startStopLock;
  17461. WaitableEvent startSuspensionEvent_, defaultEvent_;
  17462. int threadPriority_;
  17463. uint32 affinityMask_;
  17464. bool volatile threadShouldExit_;
  17465. #ifndef DOXYGEN
  17466. friend class MessageManager;
  17467. friend void JUCE_API juce_threadEntryPoint (void*);
  17468. #endif
  17469. void launchThread();
  17470. void closeThreadHandle();
  17471. void killThread();
  17472. void threadEntryPoint();
  17473. static void setCurrentThreadName (const String& name);
  17474. static bool setThreadPriority (void* handle, int priority);
  17475. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread);
  17476. };
  17477. #endif // __JUCE_THREAD_JUCEHEADER__
  17478. /*** End of inlined file: juce_Thread.h ***/
  17479. /**
  17480. A critical section that allows multiple simultaneous readers.
  17481. Features of this type of lock are:
  17482. - Multiple readers can hold the lock at the same time, but only one writer
  17483. can hold it at once.
  17484. - Writers trying to gain the lock will be blocked until all readers and writers
  17485. have released it
  17486. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  17487. blocked until the writer has obtained and released it
  17488. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  17489. there are no other readers
  17490. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  17491. - Recursive locking is supported.
  17492. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  17493. */
  17494. class JUCE_API ReadWriteLock
  17495. {
  17496. public:
  17497. /**
  17498. Creates a ReadWriteLock object.
  17499. */
  17500. ReadWriteLock() noexcept;
  17501. /** Destructor.
  17502. If the object is deleted whilst locked, any subsequent behaviour
  17503. is unpredictable.
  17504. */
  17505. ~ReadWriteLock() noexcept;
  17506. /** Locks this object for reading.
  17507. Multiple threads can simulaneously lock the object for reading, but if another
  17508. thread has it locked for writing, then this will block until it releases the
  17509. lock.
  17510. @see exitRead, ScopedReadLock
  17511. */
  17512. void enterRead() const noexcept;
  17513. /** Releases the read-lock.
  17514. If the caller thread hasn't got the lock, this can have unpredictable results.
  17515. If the enterRead() method has been called multiple times by the thread, each
  17516. call must be matched by a call to exitRead() before other threads will be allowed
  17517. to take over the lock.
  17518. @see enterRead, ScopedReadLock
  17519. */
  17520. void exitRead() const noexcept;
  17521. /** Locks this object for writing.
  17522. This will block until any other threads that have it locked for reading or
  17523. writing have released their lock.
  17524. @see exitWrite, ScopedWriteLock
  17525. */
  17526. void enterWrite() const noexcept;
  17527. /** Tries to lock this object for writing.
  17528. This is like enterWrite(), but doesn't block - it returns true if it manages
  17529. to obtain the lock.
  17530. @see enterWrite
  17531. */
  17532. bool tryEnterWrite() const noexcept;
  17533. /** Releases the write-lock.
  17534. If the caller thread hasn't got the lock, this can have unpredictable results.
  17535. If the enterWrite() method has been called multiple times by the thread, each
  17536. call must be matched by a call to exit() before other threads will be allowed
  17537. to take over the lock.
  17538. @see enterWrite, ScopedWriteLock
  17539. */
  17540. void exitWrite() const noexcept;
  17541. private:
  17542. SpinLock accessLock;
  17543. WaitableEvent waitEvent;
  17544. mutable int numWaitingWriters, numWriters;
  17545. mutable Thread::ThreadID writerThreadId;
  17546. mutable Array <Thread::ThreadID> readerThreads;
  17547. JUCE_DECLARE_NON_COPYABLE (ReadWriteLock);
  17548. };
  17549. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  17550. /*** End of inlined file: juce_ReadWriteLock.h ***/
  17551. #endif
  17552. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  17553. #endif
  17554. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17555. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  17556. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17557. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17558. /**
  17559. Automatically locks and unlocks a ReadWriteLock object.
  17560. Use one of these as a local variable to control access to a ReadWriteLock.
  17561. e.g. @code
  17562. ReadWriteLock myLock;
  17563. for (;;)
  17564. {
  17565. const ScopedReadLock myScopedLock (myLock);
  17566. // myLock is now locked
  17567. ...do some stuff...
  17568. // myLock gets unlocked here.
  17569. }
  17570. @endcode
  17571. @see ReadWriteLock, ScopedWriteLock
  17572. */
  17573. class JUCE_API ScopedReadLock
  17574. {
  17575. public:
  17576. /** Creates a ScopedReadLock.
  17577. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  17578. when the ScopedReadLock object is deleted, the ReadWriteLock will
  17579. be unlocked.
  17580. Make sure this object is created and deleted by the same thread,
  17581. otherwise there are no guarantees what will happen! Best just to use it
  17582. as a local stack object, rather than creating one with the new() operator.
  17583. */
  17584. inline explicit ScopedReadLock (const ReadWriteLock& lock) noexcept : lock_ (lock) { lock.enterRead(); }
  17585. /** Destructor.
  17586. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  17587. Make sure this object is created and deleted by the same thread,
  17588. otherwise there are no guarantees what will happen!
  17589. */
  17590. inline ~ScopedReadLock() noexcept { lock_.exitRead(); }
  17591. private:
  17592. const ReadWriteLock& lock_;
  17593. JUCE_DECLARE_NON_COPYABLE (ScopedReadLock);
  17594. };
  17595. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17596. /*** End of inlined file: juce_ScopedReadLock.h ***/
  17597. #endif
  17598. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17599. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  17600. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17601. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17602. /**
  17603. Automatically locks and unlocks a ReadWriteLock object.
  17604. Use one of these as a local variable to control access to a ReadWriteLock.
  17605. e.g. @code
  17606. ReadWriteLock myLock;
  17607. for (;;)
  17608. {
  17609. const ScopedWriteLock myScopedLock (myLock);
  17610. // myLock is now locked
  17611. ...do some stuff...
  17612. // myLock gets unlocked here.
  17613. }
  17614. @endcode
  17615. @see ReadWriteLock, ScopedReadLock
  17616. */
  17617. class JUCE_API ScopedWriteLock
  17618. {
  17619. public:
  17620. /** Creates a ScopedWriteLock.
  17621. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  17622. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  17623. be unlocked.
  17624. Make sure this object is created and deleted by the same thread,
  17625. otherwise there are no guarantees what will happen! Best just to use it
  17626. as a local stack object, rather than creating one with the new() operator.
  17627. */
  17628. inline explicit ScopedWriteLock (const ReadWriteLock& lock) noexcept : lock_ (lock) { lock.enterWrite(); }
  17629. /** Destructor.
  17630. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  17631. Make sure this object is created and deleted by the same thread,
  17632. otherwise there are no guarantees what will happen!
  17633. */
  17634. inline ~ScopedWriteLock() noexcept { lock_.exitWrite(); }
  17635. private:
  17636. const ReadWriteLock& lock_;
  17637. JUCE_DECLARE_NON_COPYABLE (ScopedWriteLock);
  17638. };
  17639. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17640. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  17641. #endif
  17642. #ifndef __JUCE_SPINLOCK_JUCEHEADER__
  17643. #endif
  17644. #ifndef __JUCE_THREAD_JUCEHEADER__
  17645. #endif
  17646. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  17647. /*** Start of inlined file: juce_ThreadPool.h ***/
  17648. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  17649. #define __JUCE_THREADPOOL_JUCEHEADER__
  17650. class ThreadPool;
  17651. class ThreadPoolThread;
  17652. /**
  17653. A task that is executed by a ThreadPool object.
  17654. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  17655. its threads.
  17656. The runJob() method needs to be implemented to do the task, and if the code that
  17657. does the work takes a significant time to run, it must keep checking the shouldExit()
  17658. method to see if something is trying to interrupt the job. If shouldExit() returns
  17659. true, the runJob() method must return immediately.
  17660. @see ThreadPool, Thread
  17661. */
  17662. class JUCE_API ThreadPoolJob
  17663. {
  17664. public:
  17665. /** Creates a thread pool job object.
  17666. After creating your job, add it to a thread pool with ThreadPool::addJob().
  17667. */
  17668. explicit ThreadPoolJob (const String& name);
  17669. /** Destructor. */
  17670. virtual ~ThreadPoolJob();
  17671. /** Returns the name of this job.
  17672. @see setJobName
  17673. */
  17674. const String getJobName() const;
  17675. /** Changes the job's name.
  17676. @see getJobName
  17677. */
  17678. void setJobName (const String& newName);
  17679. /** These are the values that can be returned by the runJob() method.
  17680. */
  17681. enum JobStatus
  17682. {
  17683. jobHasFinished = 0, /**< indicates that the job has finished and can be
  17684. removed from the pool. */
  17685. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  17686. should be automatically deleted by the pool. */
  17687. jobNeedsRunningAgain /**< indicates that the job would like to be called
  17688. again when a thread is free. */
  17689. };
  17690. /** Peforms the actual work that this job needs to do.
  17691. Your subclass must implement this method, in which is does its work.
  17692. If the code in this method takes a significant time to run, it must repeatedly check
  17693. the shouldExit() method to see if something is trying to interrupt the job.
  17694. If shouldExit() ever returns true, the runJob() method must return immediately.
  17695. If this method returns jobHasFinished, then the job will be removed from the pool
  17696. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  17697. pool and will get a chance to run again as soon as a thread is free.
  17698. @see shouldExit()
  17699. */
  17700. virtual JobStatus runJob() = 0;
  17701. /** Returns true if this job is currently running its runJob() method. */
  17702. bool isRunning() const { return isActive; }
  17703. /** Returns true if something is trying to interrupt this job and make it stop.
  17704. Your runJob() method must call this whenever it gets a chance, and if it ever
  17705. returns true, the runJob() method must return immediately.
  17706. @see signalJobShouldExit()
  17707. */
  17708. bool shouldExit() const { return shouldStop; }
  17709. /** Calling this will cause the shouldExit() method to return true, and the job
  17710. should (if it's been implemented correctly) stop as soon as possible.
  17711. @see shouldExit()
  17712. */
  17713. void signalJobShouldExit();
  17714. private:
  17715. friend class ThreadPool;
  17716. friend class ThreadPoolThread;
  17717. String jobName;
  17718. ThreadPool* pool;
  17719. bool shouldStop, isActive, shouldBeDeleted;
  17720. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob);
  17721. };
  17722. /**
  17723. A set of threads that will run a list of jobs.
  17724. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  17725. will be called by the next pooled thread that becomes free.
  17726. @see ThreadPoolJob, Thread
  17727. */
  17728. class JUCE_API ThreadPool
  17729. {
  17730. public:
  17731. /** Creates a thread pool.
  17732. Once you've created a pool, you can give it some things to do with the addJob()
  17733. method.
  17734. @param numberOfThreads the maximum number of actual threads to run.
  17735. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  17736. until there are some jobs to run. If false, then
  17737. all the threads will be fired-up immediately so that
  17738. they're ready for action
  17739. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  17740. inactive for this length of time, they will automatically
  17741. be stopped until more jobs come along and they're needed
  17742. */
  17743. ThreadPool (int numberOfThreads,
  17744. bool startThreadsOnlyWhenNeeded = true,
  17745. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  17746. /** Destructor.
  17747. This will attempt to remove all the jobs before deleting, but if you want to
  17748. specify a timeout, you should call removeAllJobs() explicitly before deleting
  17749. the pool.
  17750. */
  17751. ~ThreadPool();
  17752. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  17753. for some kind of operation.
  17754. @see ThreadPool::removeAllJobs
  17755. */
  17756. class JUCE_API JobSelector
  17757. {
  17758. public:
  17759. virtual ~JobSelector() {}
  17760. /** Should return true if the specified thread matches your criteria for whatever
  17761. operation that this object is being used for.
  17762. Any implementation of this method must be extremely fast and thread-safe!
  17763. */
  17764. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  17765. };
  17766. /** Adds a job to the queue.
  17767. Once a job has been added, then the next time a thread is free, it will run
  17768. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  17769. runJob() method, the pool will either remove the job from the pool or add it to
  17770. the back of the queue to be run again.
  17771. */
  17772. void addJob (ThreadPoolJob* job);
  17773. /** Tries to remove a job from the pool.
  17774. If the job isn't yet running, this will simply remove it. If it is running, it
  17775. will wait for it to finish.
  17776. If the timeout period expires before the job finishes running, then the job will be
  17777. left in the pool and this will return false. It returns true if the job is sucessfully
  17778. stopped and removed.
  17779. @param job the job to remove
  17780. @param interruptIfRunning if true, then if the job is currently busy, its
  17781. ThreadPoolJob::signalJobShouldExit() method will be called to try
  17782. to interrupt it. If false, then if the job will be allowed to run
  17783. until it stops normally (or the timeout expires)
  17784. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  17785. before giving up and returning false
  17786. */
  17787. bool removeJob (ThreadPoolJob* job,
  17788. bool interruptIfRunning,
  17789. int timeOutMilliseconds);
  17790. /** Tries to remove all jobs from the pool.
  17791. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  17792. methods called to try to interrupt them
  17793. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  17794. before giving up and returning false
  17795. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  17796. they will simply be removed from the pool. Jobs that are already running when
  17797. this method is called can choose whether they should be deleted by
  17798. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  17799. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  17800. jobs should be removed. If it is zero, all jobs are removed
  17801. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  17802. expires while waiting for one or more jobs to stop
  17803. */
  17804. bool removeAllJobs (bool interruptRunningJobs,
  17805. int timeOutMilliseconds,
  17806. bool deleteInactiveJobs = false,
  17807. JobSelector* selectedJobsToRemove = 0);
  17808. /** Returns the number of jobs currently running or queued.
  17809. */
  17810. int getNumJobs() const;
  17811. /** Returns one of the jobs in the queue.
  17812. Note that this can be a very volatile list as jobs might be continuously getting shifted
  17813. around in the list, and this method may return 0 if the index is currently out-of-range.
  17814. */
  17815. ThreadPoolJob* getJob (int index) const;
  17816. /** Returns true if the given job is currently queued or running.
  17817. @see isJobRunning()
  17818. */
  17819. bool contains (const ThreadPoolJob* job) const;
  17820. /** Returns true if the given job is currently being run by a thread.
  17821. */
  17822. bool isJobRunning (const ThreadPoolJob* job) const;
  17823. /** Waits until a job has finished running and has been removed from the pool.
  17824. This will wait until the job is no longer in the pool - i.e. until its
  17825. runJob() method returns ThreadPoolJob::jobHasFinished.
  17826. If the timeout period expires before the job finishes, this will return false;
  17827. it returns true if the job has finished successfully.
  17828. */
  17829. bool waitForJobToFinish (const ThreadPoolJob* job,
  17830. int timeOutMilliseconds) const;
  17831. /** Returns a list of the names of all the jobs currently running or queued.
  17832. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  17833. */
  17834. const StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  17835. /** Changes the priority of all the threads.
  17836. This will call Thread::setPriority() for each thread in the pool.
  17837. May return false if for some reason the priority can't be changed.
  17838. */
  17839. bool setThreadPriorities (int newPriority);
  17840. private:
  17841. const int threadStopTimeout;
  17842. int priority;
  17843. class ThreadPoolThread;
  17844. friend class OwnedArray <ThreadPoolThread>;
  17845. OwnedArray <ThreadPoolThread> threads;
  17846. Array <ThreadPoolJob*> jobs;
  17847. CriticalSection lock;
  17848. uint32 lastJobEndTime;
  17849. WaitableEvent jobFinishedSignal;
  17850. friend class ThreadPoolThread;
  17851. bool runNextJob();
  17852. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool);
  17853. };
  17854. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  17855. /*** End of inlined file: juce_ThreadPool.h ***/
  17856. #endif
  17857. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17858. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  17859. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17860. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17861. class TimeSliceThread;
  17862. /**
  17863. Used by the TimeSliceThread class.
  17864. To register your class with a TimeSliceThread, derive from this class and
  17865. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  17866. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  17867. deleting your client!
  17868. @see TimeSliceThread
  17869. */
  17870. class JUCE_API TimeSliceClient
  17871. {
  17872. public:
  17873. /** Destructor. */
  17874. virtual ~TimeSliceClient() {}
  17875. /** Called back by a TimeSliceThread.
  17876. When you register this class with it, a TimeSliceThread will repeatedly call
  17877. this method.
  17878. The implementation of this method should use its time-slice to do something that's
  17879. quick - never block for longer than absolutely necessary.
  17880. @returns Your method should return the number of milliseconds which it would like to wait before being called
  17881. again. Returning 0 will make the thread call again as soon as possible (after possibly servicing
  17882. other busy clients). If you return a value below zero, your client will be removed from the list of clients,
  17883. and won't be called again. The value you specify isn't a guaranteee, and is only used as a hint by the
  17884. thread - the actual time before the next callback may be more or less than specified.
  17885. You can force the TimeSliceThread to wake up and poll again immediately by calling its notify() method.
  17886. */
  17887. virtual int useTimeSlice() = 0;
  17888. private:
  17889. friend class TimeSliceThread;
  17890. Time nextCallTime;
  17891. };
  17892. /**
  17893. A thread that keeps a list of clients, and calls each one in turn, giving them
  17894. all a chance to run some sort of short task.
  17895. @see TimeSliceClient, Thread
  17896. */
  17897. class JUCE_API TimeSliceThread : public Thread
  17898. {
  17899. public:
  17900. /**
  17901. Creates a TimeSliceThread.
  17902. When first created, the thread is not running. Use the startThread()
  17903. method to start it.
  17904. */
  17905. explicit TimeSliceThread (const String& threadName);
  17906. /** Destructor.
  17907. Deleting a Thread object that is running will only give the thread a
  17908. brief opportunity to stop itself cleanly, so it's recommended that you
  17909. should always call stopThread() with a decent timeout before deleting,
  17910. to avoid the thread being forcibly killed (which is a Bad Thing).
  17911. */
  17912. ~TimeSliceThread();
  17913. /** Adds a client to the list.
  17914. The client's callbacks will start after the number of milliseconds specified
  17915. by millisecondsBeforeStarting (and this may happen before this method has returned).
  17916. */
  17917. void addTimeSliceClient (TimeSliceClient* client, int millisecondsBeforeStarting = 0);
  17918. /** Removes a client from the list.
  17919. This method will make sure that all callbacks to the client have completely
  17920. finished before the method returns.
  17921. */
  17922. void removeTimeSliceClient (TimeSliceClient* client);
  17923. /** Returns the number of registered clients. */
  17924. int getNumClients() const;
  17925. /** Returns one of the registered clients. */
  17926. TimeSliceClient* getClient (int index) const;
  17927. #ifndef DOXYGEN
  17928. void run();
  17929. #endif
  17930. private:
  17931. CriticalSection callbackLock, listLock;
  17932. Array <TimeSliceClient*> clients;
  17933. TimeSliceClient* clientBeingCalled;
  17934. TimeSliceClient* getNextClient (int index) const;
  17935. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimeSliceThread);
  17936. };
  17937. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17938. /*** End of inlined file: juce_TimeSliceThread.h ***/
  17939. #endif
  17940. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  17941. #endif
  17942. #endif
  17943. /*** End of inlined file: juce_core_includes.h ***/
  17944. // if you're compiling a command-line app, you might want to just include the core headers,
  17945. // so you can set this macro before including juce.h
  17946. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  17947. /*** Start of inlined file: juce_app_includes.h ***/
  17948. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  17949. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  17950. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  17951. /*** Start of inlined file: juce_Application.h ***/
  17952. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  17953. #define __JUCE_APPLICATION_JUCEHEADER__
  17954. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  17955. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17956. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17957. /*** Start of inlined file: juce_Component.h ***/
  17958. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  17959. #define __JUCE_COMPONENT_JUCEHEADER__
  17960. /*** Start of inlined file: juce_MouseCursor.h ***/
  17961. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  17962. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  17963. class Image;
  17964. class ComponentPeer;
  17965. class Component;
  17966. /**
  17967. Represents a mouse cursor image.
  17968. This object can either be used to represent one of the standard mouse
  17969. cursor shapes, or a custom one generated from an image.
  17970. */
  17971. class JUCE_API MouseCursor
  17972. {
  17973. public:
  17974. /** The set of available standard mouse cursors. */
  17975. enum StandardCursorType
  17976. {
  17977. NoCursor = 0, /**< An invisible cursor. */
  17978. NormalCursor, /**< The stardard arrow cursor. */
  17979. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  17980. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  17981. CrosshairCursor, /**< A pair of crosshairs. */
  17982. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  17983. that you're dragging a copy of something. */
  17984. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  17985. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  17986. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  17987. UpDownResizeCursor, /**< an arrow pointing up and down. */
  17988. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  17989. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  17990. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  17991. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  17992. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  17993. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  17994. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  17995. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  17996. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  17997. };
  17998. /** Creates the standard arrow cursor. */
  17999. MouseCursor();
  18000. /** Creates one of the standard mouse cursor */
  18001. MouseCursor (StandardCursorType type);
  18002. /** Creates a custom cursor from an image.
  18003. @param image the image to use for the cursor - if this is bigger than the
  18004. system can manage, it might get scaled down first, and might
  18005. also have to be turned to black-and-white if it can't do colour
  18006. cursors.
  18007. @param hotSpotX the x position of the cursor's hotspot within the image
  18008. @param hotSpotY the y position of the cursor's hotspot within the image
  18009. */
  18010. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  18011. /** Creates a copy of another cursor object. */
  18012. MouseCursor (const MouseCursor& other);
  18013. /** Copies this cursor from another object. */
  18014. MouseCursor& operator= (const MouseCursor& other);
  18015. /** Destructor. */
  18016. ~MouseCursor();
  18017. /** Checks whether two mouse cursors are the same.
  18018. For custom cursors, two cursors created from the same image won't be
  18019. recognised as the same, only MouseCursor objects that have been
  18020. copied from the same object.
  18021. */
  18022. bool operator== (const MouseCursor& other) const noexcept;
  18023. /** Checks whether two mouse cursors are the same.
  18024. For custom cursors, two cursors created from the same image won't be
  18025. recognised as the same, only MouseCursor objects that have been
  18026. copied from the same object.
  18027. */
  18028. bool operator!= (const MouseCursor& other) const noexcept;
  18029. /** Makes the system show its default 'busy' cursor.
  18030. This will turn the system cursor to an hourglass or spinning beachball
  18031. until the next time the mouse is moved, or hideWaitCursor() is called.
  18032. This is handy if the message loop is about to block for a couple of
  18033. seconds while busy and you want to give the user feedback about this.
  18034. @see MessageManager::setTimeBeforeShowingWaitCursor
  18035. */
  18036. static void showWaitCursor();
  18037. /** If showWaitCursor has been called, this will return the mouse to its
  18038. normal state.
  18039. This will look at what component is under the mouse, and update the
  18040. cursor to be the correct one for that component.
  18041. @see showWaitCursor
  18042. */
  18043. static void hideWaitCursor();
  18044. private:
  18045. class SharedCursorHandle;
  18046. friend class SharedCursorHandle;
  18047. SharedCursorHandle* cursorHandle;
  18048. friend class MouseInputSourceInternal;
  18049. void showInWindow (ComponentPeer* window) const;
  18050. void showInAllWindows() const;
  18051. void* getHandle() const noexcept;
  18052. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  18053. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  18054. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  18055. JUCE_LEAK_DETECTOR (MouseCursor);
  18056. };
  18057. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  18058. /*** End of inlined file: juce_MouseCursor.h ***/
  18059. /*** Start of inlined file: juce_MouseListener.h ***/
  18060. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  18061. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  18062. class MouseEvent;
  18063. /**
  18064. A MouseListener can be registered with a component to receive callbacks
  18065. about mouse events that happen to that component.
  18066. @see Component::addMouseListener, Component::removeMouseListener
  18067. */
  18068. class JUCE_API MouseListener
  18069. {
  18070. public:
  18071. /** Destructor. */
  18072. virtual ~MouseListener() {}
  18073. /** Called when the mouse moves inside a component.
  18074. If the mouse button isn't pressed and the mouse moves over a component,
  18075. this will be called to let the component react to this.
  18076. A component will always get a mouseEnter callback before a mouseMove.
  18077. @param e details about the position and status of the mouse event, including
  18078. the source component in which it occurred
  18079. @see mouseEnter, mouseExit, mouseDrag, contains
  18080. */
  18081. virtual void mouseMove (const MouseEvent& e);
  18082. /** Called when the mouse first enters a component.
  18083. If the mouse button isn't pressed and the mouse moves into a component,
  18084. this will be called to let the component react to this.
  18085. When the mouse button is pressed and held down while being moved in
  18086. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  18087. mouseDrag messages are sent to the component that the mouse was originally
  18088. clicked on, until the button is released.
  18089. @param e details about the position and status of the mouse event, including
  18090. the source component in which it occurred
  18091. @see mouseExit, mouseDrag, mouseMove, contains
  18092. */
  18093. virtual void mouseEnter (const MouseEvent& e);
  18094. /** Called when the mouse moves out of a component.
  18095. This will be called when the mouse moves off the edge of this
  18096. component.
  18097. If the mouse button was pressed, and it was then dragged off the
  18098. edge of the component and released, then this callback will happen
  18099. when the button is released, after the mouseUp callback.
  18100. @param e details about the position and status of the mouse event, including
  18101. the source component in which it occurred
  18102. @see mouseEnter, mouseDrag, mouseMove, contains
  18103. */
  18104. virtual void mouseExit (const MouseEvent& e);
  18105. /** Called when a mouse button is pressed.
  18106. The MouseEvent object passed in contains lots of methods for finding out
  18107. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  18108. were held down at the time.
  18109. Once a button is held down, the mouseDrag method will be called when the
  18110. mouse moves, until the button is released.
  18111. @param e details about the position and status of the mouse event, including
  18112. the source component in which it occurred
  18113. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  18114. */
  18115. virtual void mouseDown (const MouseEvent& e);
  18116. /** Called when the mouse is moved while a button is held down.
  18117. When a mouse button is pressed inside a component, that component
  18118. receives mouseDrag callbacks each time the mouse moves, even if the
  18119. mouse strays outside the component's bounds.
  18120. @param e details about the position and status of the mouse event, including
  18121. the source component in which it occurred
  18122. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  18123. */
  18124. virtual void mouseDrag (const MouseEvent& e);
  18125. /** Called when a mouse button is released.
  18126. A mouseUp callback is sent to the component in which a button was pressed
  18127. even if the mouse is actually over a different component when the
  18128. button is released.
  18129. The MouseEvent object passed in contains lots of methods for finding out
  18130. which buttons were down just before they were released.
  18131. @param e details about the position and status of the mouse event, including
  18132. the source component in which it occurred
  18133. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  18134. */
  18135. virtual void mouseUp (const MouseEvent& e);
  18136. /** Called when a mouse button has been double-clicked on a component.
  18137. The MouseEvent object passed in contains lots of methods for finding out
  18138. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  18139. were held down at the time.
  18140. @param e details about the position and status of the mouse event, including
  18141. the source component in which it occurred
  18142. @see mouseDown, mouseUp
  18143. */
  18144. virtual void mouseDoubleClick (const MouseEvent& e);
  18145. /** Called when the mouse-wheel is moved.
  18146. This callback is sent to the component that the mouse is over when the
  18147. wheel is moved.
  18148. If not overridden, the component will forward this message to its parent, so
  18149. that parent components can collect mouse-wheel messages that happen to
  18150. child components which aren't interested in them.
  18151. @param e details about the position and status of the mouse event, including
  18152. the source component in which it occurred
  18153. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  18154. value means the wheel has been pushed to the right, negative means it
  18155. was pushed to the left
  18156. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  18157. value means the wheel has been pushed upwards, negative means it
  18158. was pushed downwards
  18159. */
  18160. virtual void mouseWheelMove (const MouseEvent& e,
  18161. float wheelIncrementX,
  18162. float wheelIncrementY);
  18163. };
  18164. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  18165. /*** End of inlined file: juce_MouseListener.h ***/
  18166. /*** Start of inlined file: juce_MouseEvent.h ***/
  18167. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  18168. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  18169. class Component;
  18170. class MouseInputSource;
  18171. /*** Start of inlined file: juce_ModifierKeys.h ***/
  18172. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  18173. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  18174. /**
  18175. Represents the state of the mouse buttons and modifier keys.
  18176. This is used both by mouse events and by KeyPress objects to describe
  18177. the state of keys such as shift, control, alt, etc.
  18178. @see KeyPress, MouseEvent::mods
  18179. */
  18180. class JUCE_API ModifierKeys
  18181. {
  18182. public:
  18183. /** Creates a ModifierKeys object from a raw set of flags.
  18184. @param flags to represent the keys that are down
  18185. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  18186. rightButtonModifier, commandModifier, popupMenuClickModifier
  18187. */
  18188. ModifierKeys (int flags = 0) noexcept;
  18189. /** Creates a copy of another object. */
  18190. ModifierKeys (const ModifierKeys& other) noexcept;
  18191. /** Copies this object from another one. */
  18192. ModifierKeys& operator= (const ModifierKeys& other) noexcept;
  18193. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  18194. This is a platform-agnostic way of checking for the operating system's
  18195. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  18196. Windows/Linux, it's actually checking for the CTRL key.
  18197. */
  18198. inline bool isCommandDown() const noexcept { return (flags & commandModifier) != 0; }
  18199. /** Checks whether the user is trying to launch a pop-up menu.
  18200. This checks for platform-specific modifiers that might indicate that the user
  18201. is following the operating system's normal method of showing a pop-up menu.
  18202. So on Windows/Linux, this method is really testing for a right-click.
  18203. On the Mac, it tests for either the CTRL key being down, or a right-click.
  18204. */
  18205. inline bool isPopupMenu() const noexcept { return (flags & popupMenuClickModifier) != 0; }
  18206. /** Checks whether the flag is set for the left mouse-button. */
  18207. inline bool isLeftButtonDown() const noexcept { return (flags & leftButtonModifier) != 0; }
  18208. /** Checks whether the flag is set for the right mouse-button.
  18209. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  18210. this is platform-independent (and makes your code more explanatory too).
  18211. */
  18212. inline bool isRightButtonDown() const noexcept { return (flags & rightButtonModifier) != 0; }
  18213. inline bool isMiddleButtonDown() const noexcept { return (flags & middleButtonModifier) != 0; }
  18214. /** Tests for any of the mouse-button flags. */
  18215. inline bool isAnyMouseButtonDown() const noexcept { return (flags & allMouseButtonModifiers) != 0; }
  18216. /** Tests for any of the modifier key flags. */
  18217. inline bool isAnyModifierKeyDown() const noexcept { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  18218. /** Checks whether the shift key's flag is set. */
  18219. inline bool isShiftDown() const noexcept { return (flags & shiftModifier) != 0; }
  18220. /** Checks whether the CTRL key's flag is set.
  18221. Remember that it's better to use the platform-agnostic routines to test for command-key and
  18222. popup-menu modifiers.
  18223. @see isCommandDown, isPopupMenu
  18224. */
  18225. inline bool isCtrlDown() const noexcept { return (flags & ctrlModifier) != 0; }
  18226. /** Checks whether the shift key's flag is set. */
  18227. inline bool isAltDown() const noexcept { return (flags & altModifier) != 0; }
  18228. /** Flags that represent the different keys. */
  18229. enum Flags
  18230. {
  18231. /** Shift key flag. */
  18232. shiftModifier = 1,
  18233. /** CTRL key flag. */
  18234. ctrlModifier = 2,
  18235. /** ALT key flag. */
  18236. altModifier = 4,
  18237. /** Left mouse button flag. */
  18238. leftButtonModifier = 16,
  18239. /** Right mouse button flag. */
  18240. rightButtonModifier = 32,
  18241. /** Middle mouse button flag. */
  18242. middleButtonModifier = 64,
  18243. #if JUCE_MAC
  18244. /** Command key flag - on windows this is the same as the CTRL key flag. */
  18245. commandModifier = 8,
  18246. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  18247. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  18248. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  18249. #else
  18250. /** Command key flag - on windows this is the same as the CTRL key flag. */
  18251. commandModifier = ctrlModifier,
  18252. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  18253. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  18254. popupMenuClickModifier = rightButtonModifier,
  18255. #endif
  18256. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  18257. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  18258. /** Represents a combination of all the mouse buttons at once. */
  18259. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  18260. };
  18261. /** Returns a copy of only the mouse-button flags */
  18262. const ModifierKeys withOnlyMouseButtons() const noexcept { return ModifierKeys (flags & allMouseButtonModifiers); }
  18263. /** Returns a copy of only the non-mouse flags */
  18264. const ModifierKeys withoutMouseButtons() const noexcept { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  18265. bool operator== (const ModifierKeys& other) const noexcept { return flags == other.flags; }
  18266. bool operator!= (const ModifierKeys& other) const noexcept { return flags != other.flags; }
  18267. /** Returns the raw flags for direct testing. */
  18268. inline int getRawFlags() const noexcept { return flags; }
  18269. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const noexcept { return ModifierKeys (flags & ~rawFlagsToClear); }
  18270. inline const ModifierKeys withFlags (int rawFlagsToSet) const noexcept { return ModifierKeys (flags | rawFlagsToSet); }
  18271. /** Tests a combination of flags and returns true if any of them are set. */
  18272. inline bool testFlags (const int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  18273. /** Returns the total number of mouse buttons that are down. */
  18274. int getNumMouseButtonsDown() const noexcept;
  18275. /** Creates a ModifierKeys object to represent the last-known state of the
  18276. keyboard and mouse buttons.
  18277. @see getCurrentModifiersRealtime
  18278. */
  18279. static const ModifierKeys getCurrentModifiers() noexcept;
  18280. /** Creates a ModifierKeys object to represent the current state of the
  18281. keyboard and mouse buttons.
  18282. This isn't often needed and isn't recommended, but will actively check all the
  18283. mouse and key states rather than just returning their last-known state like
  18284. getCurrentModifiers() does.
  18285. This is only needed in special circumstances for up-to-date modifier information
  18286. at times when the app's event loop isn't running normally.
  18287. Another reason to avoid this method is that it's not stateless, and calling it may
  18288. update the value returned by getCurrentModifiers(), which could cause subtle changes
  18289. in the behaviour of some components.
  18290. */
  18291. static const ModifierKeys getCurrentModifiersRealtime() noexcept;
  18292. private:
  18293. int flags;
  18294. static ModifierKeys currentModifiers;
  18295. friend class ComponentPeer;
  18296. friend class MouseInputSource;
  18297. friend class MouseInputSourceInternal;
  18298. static void updateCurrentModifiers() noexcept;
  18299. };
  18300. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  18301. /*** End of inlined file: juce_ModifierKeys.h ***/
  18302. /*** Start of inlined file: juce_Point.h ***/
  18303. #ifndef __JUCE_POINT_JUCEHEADER__
  18304. #define __JUCE_POINT_JUCEHEADER__
  18305. /*** Start of inlined file: juce_AffineTransform.h ***/
  18306. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18307. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18308. /**
  18309. Represents a 2D affine-transformation matrix.
  18310. An affine transformation is a transformation such as a rotation, scale, shear,
  18311. resize or translation.
  18312. These are used for various 2D transformation tasks, e.g. with Path objects.
  18313. @see Path, Point, Line
  18314. */
  18315. class JUCE_API AffineTransform
  18316. {
  18317. public:
  18318. /** Creates an identity transform. */
  18319. AffineTransform() noexcept;
  18320. /** Creates a copy of another transform. */
  18321. AffineTransform (const AffineTransform& other) noexcept;
  18322. /** Creates a transform from a set of raw matrix values.
  18323. The resulting matrix is:
  18324. (mat00 mat01 mat02)
  18325. (mat10 mat11 mat12)
  18326. ( 0 0 1 )
  18327. */
  18328. AffineTransform (float mat00, float mat01, float mat02,
  18329. float mat10, float mat11, float mat12) noexcept;
  18330. /** Copies from another AffineTransform object */
  18331. AffineTransform& operator= (const AffineTransform& other) noexcept;
  18332. /** Compares two transforms. */
  18333. bool operator== (const AffineTransform& other) const noexcept;
  18334. /** Compares two transforms. */
  18335. bool operator!= (const AffineTransform& other) const noexcept;
  18336. /** A ready-to-use identity transform, which you can use to append other
  18337. transformations to.
  18338. e.g. @code
  18339. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  18340. .scaled (2.0f);
  18341. @endcode
  18342. */
  18343. static const AffineTransform identity;
  18344. /** Transforms a 2D co-ordinate using this matrix. */
  18345. template <typename ValueType>
  18346. void transformPoint (ValueType& x, ValueType& y) const noexcept
  18347. {
  18348. const ValueType oldX = x;
  18349. x = static_cast <ValueType> (mat00 * oldX + mat01 * y + mat02);
  18350. y = static_cast <ValueType> (mat10 * oldX + mat11 * y + mat12);
  18351. }
  18352. /** Transforms two 2D co-ordinates using this matrix.
  18353. This is just a shortcut for calling transformPoint() on each of these pairs of
  18354. coordinates in turn. (And putting all the calculations into one function hopefully
  18355. also gives the compiler a bit more scope for pipelining it).
  18356. */
  18357. template <typename ValueType>
  18358. void transformPoints (ValueType& x1, ValueType& y1,
  18359. ValueType& x2, ValueType& y2) const noexcept
  18360. {
  18361. const ValueType oldX1 = x1, oldX2 = x2;
  18362. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  18363. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  18364. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  18365. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  18366. }
  18367. /** Transforms three 2D co-ordinates using this matrix.
  18368. This is just a shortcut for calling transformPoint() on each of these pairs of
  18369. coordinates in turn. (And putting all the calculations into one function hopefully
  18370. also gives the compiler a bit more scope for pipelining it).
  18371. */
  18372. template <typename ValueType>
  18373. void transformPoints (ValueType& x1, ValueType& y1,
  18374. ValueType& x2, ValueType& y2,
  18375. ValueType& x3, ValueType& y3) const noexcept
  18376. {
  18377. const ValueType oldX1 = x1, oldX2 = x2, oldX3 = x3;
  18378. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  18379. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  18380. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  18381. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  18382. x3 = static_cast <ValueType> (mat00 * oldX3 + mat01 * y3 + mat02);
  18383. y3 = static_cast <ValueType> (mat10 * oldX3 + mat11 * y3 + mat12);
  18384. }
  18385. /** Returns a new transform which is the same as this one followed by a translation. */
  18386. const AffineTransform translated (float deltaX,
  18387. float deltaY) const noexcept;
  18388. /** Returns a new transform which is a translation. */
  18389. static const AffineTransform translation (float deltaX,
  18390. float deltaY) noexcept;
  18391. /** Returns a transform which is the same as this one followed by a rotation.
  18392. The rotation is specified by a number of radians to rotate clockwise, centred around
  18393. the origin (0, 0).
  18394. */
  18395. const AffineTransform rotated (float angleInRadians) const noexcept;
  18396. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  18397. The rotation is specified by a number of radians to rotate clockwise, centred around
  18398. the co-ordinates passed in.
  18399. */
  18400. const AffineTransform rotated (float angleInRadians,
  18401. float pivotX,
  18402. float pivotY) const noexcept;
  18403. /** Returns a new transform which is a rotation about (0, 0). */
  18404. static const AffineTransform rotation (float angleInRadians) noexcept;
  18405. /** Returns a new transform which is a rotation about a given point. */
  18406. static const AffineTransform rotation (float angleInRadians,
  18407. float pivotX,
  18408. float pivotY) noexcept;
  18409. /** Returns a transform which is the same as this one followed by a re-scaling.
  18410. The scaling is centred around the origin (0, 0).
  18411. */
  18412. const AffineTransform scaled (float factorX,
  18413. float factorY) const noexcept;
  18414. /** Returns a transform which is the same as this one followed by a re-scaling.
  18415. The scaling is centred around the origin provided.
  18416. */
  18417. const AffineTransform scaled (float factorX, float factorY,
  18418. float pivotX, float pivotY) const noexcept;
  18419. /** Returns a new transform which is a re-scale about the origin. */
  18420. static const AffineTransform scale (float factorX,
  18421. float factorY) noexcept;
  18422. /** Returns a new transform which is a re-scale centred around the point provided. */
  18423. static const AffineTransform scale (float factorX, float factorY,
  18424. float pivotX, float pivotY) noexcept;
  18425. /** Returns a transform which is the same as this one followed by a shear.
  18426. The shear is centred around the origin (0, 0).
  18427. */
  18428. const AffineTransform sheared (float shearX, float shearY) const noexcept;
  18429. /** Returns a shear transform, centred around the origin (0, 0). */
  18430. static const AffineTransform shear (float shearX, float shearY) noexcept;
  18431. /** Returns a matrix which is the inverse operation of this one.
  18432. Some matrices don't have an inverse - in this case, the method will just return
  18433. an identity transform.
  18434. */
  18435. const AffineTransform inverted() const noexcept;
  18436. /** Returns the transform that will map three known points onto three coordinates
  18437. that are supplied.
  18438. This returns the transform that will transform (0, 0) into (x00, y00),
  18439. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  18440. */
  18441. static const AffineTransform fromTargetPoints (float x00, float y00,
  18442. float x10, float y10,
  18443. float x01, float y01) noexcept;
  18444. /** Returns the transform that will map three specified points onto three target points.
  18445. */
  18446. static const AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  18447. float sourceX2, float sourceY2, float targetX2, float targetY2,
  18448. float sourceX3, float sourceY3, float targetX3, float targetY3) noexcept;
  18449. /** Returns the result of concatenating another transformation after this one. */
  18450. const AffineTransform followedBy (const AffineTransform& other) const noexcept;
  18451. /** Returns true if this transform has no effect on points. */
  18452. bool isIdentity() const noexcept;
  18453. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  18454. bool isSingularity() const noexcept;
  18455. /** Returns true if the transform only translates, and doesn't scale or rotate the
  18456. points. */
  18457. bool isOnlyTranslation() const noexcept;
  18458. /** If this transform is only a translation, this returns the X offset.
  18459. @see isOnlyTranslation
  18460. */
  18461. float getTranslationX() const noexcept { return mat02; }
  18462. /** If this transform is only a translation, this returns the X offset.
  18463. @see isOnlyTranslation
  18464. */
  18465. float getTranslationY() const noexcept { return mat12; }
  18466. /** Returns the approximate scale factor by which lengths will be transformed.
  18467. Obviously a length may be scaled by entirely different amounts depending on its
  18468. direction, so this is only appropriate as a rough guide.
  18469. */
  18470. float getScaleFactor() const noexcept;
  18471. /* The transform matrix is:
  18472. (mat00 mat01 mat02)
  18473. (mat10 mat11 mat12)
  18474. ( 0 0 1 )
  18475. */
  18476. float mat00, mat01, mat02;
  18477. float mat10, mat11, mat12;
  18478. private:
  18479. JUCE_LEAK_DETECTOR (AffineTransform);
  18480. };
  18481. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18482. /*** End of inlined file: juce_AffineTransform.h ***/
  18483. /**
  18484. A pair of (x, y) co-ordinates.
  18485. The ValueType template should be a primitive type such as int, float, double,
  18486. rather than a class.
  18487. @see Line, Path, AffineTransform
  18488. */
  18489. template <typename ValueType>
  18490. class Point
  18491. {
  18492. public:
  18493. /** Creates a point with co-ordinates (0, 0). */
  18494. Point() noexcept : x(), y() {}
  18495. /** Creates a copy of another point. */
  18496. Point (const Point& other) noexcept : x (other.x), y (other.y) {}
  18497. /** Creates a point from an (x, y) position. */
  18498. Point (const ValueType initialX, const ValueType initialY) noexcept : x (initialX), y (initialY) {}
  18499. /** Destructor. */
  18500. ~Point() noexcept {}
  18501. /** Copies this point from another one. */
  18502. Point& operator= (const Point& other) noexcept { x = other.x; y = other.y; return *this; }
  18503. inline bool operator== (const Point& other) const noexcept { return x == other.x && y == other.y; }
  18504. inline bool operator!= (const Point& other) const noexcept { return x != other.x || y != other.y; }
  18505. /** Returns true if the point is (0, 0). */
  18506. bool isOrigin() const noexcept { return x == ValueType() && y == ValueType(); }
  18507. /** Returns the point's x co-ordinate. */
  18508. inline ValueType getX() const noexcept { return x; }
  18509. /** Returns the point's y co-ordinate. */
  18510. inline ValueType getY() const noexcept { return y; }
  18511. /** Sets the point's x co-ordinate. */
  18512. inline void setX (const ValueType newX) noexcept { x = newX; }
  18513. /** Sets the point's y co-ordinate. */
  18514. inline void setY (const ValueType newY) noexcept { y = newY; }
  18515. /** Returns a point which has the same Y position as this one, but a new X. */
  18516. const Point withX (const ValueType newX) const noexcept { return Point (newX, y); }
  18517. /** Returns a point which has the same X position as this one, but a new Y. */
  18518. const Point withY (const ValueType newY) const noexcept { return Point (x, newY); }
  18519. /** Changes the point's x and y co-ordinates. */
  18520. void setXY (const ValueType newX, const ValueType newY) noexcept { x = newX; y = newY; }
  18521. /** Adds a pair of co-ordinates to this value. */
  18522. void addXY (const ValueType xToAdd, const ValueType yToAdd) noexcept { x += xToAdd; y += yToAdd; }
  18523. /** Returns a point with a given offset from this one. */
  18524. const Point translated (const ValueType xDelta, const ValueType yDelta) const noexcept { return Point (x + xDelta, y + yDelta); }
  18525. /** Adds two points together. */
  18526. const Point operator+ (const Point& other) const noexcept { return Point (x + other.x, y + other.y); }
  18527. /** Adds another point's co-ordinates to this one. */
  18528. Point& operator+= (const Point& other) noexcept { x += other.x; y += other.y; return *this; }
  18529. /** Subtracts one points from another. */
  18530. const Point operator- (const Point& other) const noexcept { return Point (x - other.x, y - other.y); }
  18531. /** Subtracts another point's co-ordinates to this one. */
  18532. Point& operator-= (const Point& other) noexcept { x -= other.x; y -= other.y; return *this; }
  18533. /** Returns a point whose coordinates are multiplied by a given value. */
  18534. const Point operator* (const ValueType multiplier) const noexcept { return Point (x * multiplier, y * multiplier); }
  18535. /** Multiplies the point's co-ordinates by a value. */
  18536. Point& operator*= (const ValueType multiplier) noexcept { x *= multiplier; y *= multiplier; return *this; }
  18537. /** Returns a point whose coordinates are divided by a given value. */
  18538. const Point operator/ (const ValueType divisor) const noexcept { return Point (x / divisor, y / divisor); }
  18539. /** Divides the point's co-ordinates by a value. */
  18540. Point& operator/= (const ValueType divisor) noexcept { x /= divisor; y /= divisor; return *this; }
  18541. /** Returns the inverse of this point. */
  18542. const Point operator-() const noexcept { return Point (-x, -y); }
  18543. /** Returns the straight-line distance between this point and another one. */
  18544. ValueType getDistanceFromOrigin() const noexcept { return juce_hypot (x, y); }
  18545. /** Returns the straight-line distance between this point and another one. */
  18546. ValueType getDistanceFrom (const Point& other) const noexcept { return juce_hypot (x - other.x, y - other.y); }
  18547. /** Returns the angle from this point to another one.
  18548. The return value is the number of radians clockwise from the 3 o'clock direction,
  18549. where this point is the centre and the other point is on the circumference.
  18550. */
  18551. ValueType getAngleToPoint (const Point& other) const noexcept { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  18552. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  18553. @param radius the radius of the circle.
  18554. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  18555. */
  18556. const Point getPointOnCircumference (const float radius, const float angle) const noexcept { return Point<float> (x + radius * std::sin (angle),
  18557. y - radius * std::cos (angle)); }
  18558. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  18559. @param radiusX the horizontal radius of the circle.
  18560. @param radiusY the vertical radius of the circle.
  18561. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  18562. */
  18563. const Point getPointOnCircumference (const float radiusX, const float radiusY, const float angle) const noexcept { return Point<float> (x + radiusX * std::sin (angle),
  18564. y - radiusY * std::cos (angle)); }
  18565. /** Uses a transform to change the point's co-ordinates.
  18566. This will only compile if ValueType = float!
  18567. @see AffineTransform::transformPoint
  18568. */
  18569. void applyTransform (const AffineTransform& transform) noexcept { transform.transformPoint (x, y); }
  18570. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  18571. const Point transformedBy (const AffineTransform& transform) const noexcept { return Point (transform.mat00 * x + transform.mat01 * y + transform.mat02,
  18572. transform.mat10 * x + transform.mat11 * y + transform.mat12); }
  18573. /** Casts this point to a Point<int> object. */
  18574. const Point<int> toInt() const noexcept { return Point<int> (static_cast <int> (x), static_cast<int> (y)); }
  18575. /** Casts this point to a Point<float> object. */
  18576. const Point<float> toFloat() const noexcept { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  18577. /** Casts this point to a Point<double> object. */
  18578. const Point<double> toDouble() const noexcept { return Point<double> (static_cast <double> (x), static_cast<double> (y)); }
  18579. /** Returns the point as a string in the form "x, y". */
  18580. const String toString() const { return String (x) + ", " + String (y); }
  18581. private:
  18582. ValueType x, y;
  18583. };
  18584. #endif // __JUCE_POINT_JUCEHEADER__
  18585. /*** End of inlined file: juce_Point.h ***/
  18586. /**
  18587. Contains position and status information about a mouse event.
  18588. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  18589. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  18590. */
  18591. class JUCE_API MouseEvent
  18592. {
  18593. public:
  18594. /** Creates a MouseEvent.
  18595. Normally an application will never need to use this.
  18596. @param source the source that's invoking the event
  18597. @param position the position of the mouse, relative to the component that is passed-in
  18598. @param modifiers the key modifiers at the time of the event
  18599. @param eventComponent the component that the mouse event applies to
  18600. @param originator the component that originally received the event
  18601. @param eventTime the time the event happened
  18602. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  18603. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  18604. the same as the current mouse-x position.
  18605. @param mouseDownTime the time at which the corresponding mouse-down event happened
  18606. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  18607. the same as the current mouse-event time.
  18608. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  18609. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  18610. */
  18611. MouseEvent (MouseInputSource& source,
  18612. const Point<int>& position,
  18613. const ModifierKeys& modifiers,
  18614. Component* eventComponent,
  18615. Component* originator,
  18616. const Time& eventTime,
  18617. const Point<int> mouseDownPos,
  18618. const Time& mouseDownTime,
  18619. int numberOfClicks,
  18620. bool mouseWasDragged) noexcept;
  18621. /** Destructor. */
  18622. ~MouseEvent() noexcept;
  18623. /** The x-position of the mouse when the event occurred.
  18624. This value is relative to the top-left of the component to which the
  18625. event applies (as indicated by the MouseEvent::eventComponent field).
  18626. */
  18627. const int x;
  18628. /** The y-position of the mouse when the event occurred.
  18629. This value is relative to the top-left of the component to which the
  18630. event applies (as indicated by the MouseEvent::eventComponent field).
  18631. */
  18632. const int y;
  18633. /** The key modifiers associated with the event.
  18634. This will let you find out which mouse buttons were down, as well as which
  18635. modifier keys were held down.
  18636. When used for mouse-up events, this will indicate the state of the mouse buttons
  18637. just before they were released, so that you can tell which button they let go of.
  18638. */
  18639. const ModifierKeys mods;
  18640. /** The component that this event applies to.
  18641. This is usually the component that the mouse was over at the time, but for mouse-drag
  18642. events the mouse could actually be over a different component and the events are
  18643. still sent to the component that the button was originally pressed on.
  18644. The x and y member variables are relative to this component's position.
  18645. If you use getEventRelativeTo() to retarget this object to be relative to a different
  18646. component, this pointer will be updated, but originalComponent remains unchanged.
  18647. @see originalComponent
  18648. */
  18649. Component* const eventComponent;
  18650. /** The component that the event first occurred on.
  18651. If you use getEventRelativeTo() to retarget this object to be relative to a different
  18652. component, this value remains unchanged to indicate the first component that received it.
  18653. @see eventComponent
  18654. */
  18655. Component* const originalComponent;
  18656. /** The time that this mouse-event occurred.
  18657. */
  18658. const Time eventTime;
  18659. /** The source device that generated this event.
  18660. */
  18661. MouseInputSource& source;
  18662. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  18663. The co-ordinate is relative to the component specified in MouseEvent::component.
  18664. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18665. */
  18666. int getMouseDownX() const noexcept;
  18667. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  18668. The co-ordinate is relative to the component specified in MouseEvent::component.
  18669. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18670. */
  18671. int getMouseDownY() const noexcept;
  18672. /** Returns the co-ordinates of the last place that a mouse was pressed.
  18673. The co-ordinates are relative to the component specified in MouseEvent::component.
  18674. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18675. */
  18676. const Point<int> getMouseDownPosition() const noexcept;
  18677. /** Returns the straight-line distance between where the mouse is now and where it
  18678. was the last time the button was pressed.
  18679. This is quite handy for things like deciding whether the user has moved far enough
  18680. for it to be considered a drag operation.
  18681. @see getDistanceFromDragStartX
  18682. */
  18683. int getDistanceFromDragStart() const noexcept;
  18684. /** Returns the difference between the mouse's current x postion and where it was
  18685. when the button was last pressed.
  18686. @see getDistanceFromDragStart
  18687. */
  18688. int getDistanceFromDragStartX() const noexcept;
  18689. /** Returns the difference between the mouse's current y postion and where it was
  18690. when the button was last pressed.
  18691. @see getDistanceFromDragStart
  18692. */
  18693. int getDistanceFromDragStartY() const noexcept;
  18694. /** Returns the difference between the mouse's current postion and where it was
  18695. when the button was last pressed.
  18696. @see getDistanceFromDragStart
  18697. */
  18698. const Point<int> getOffsetFromDragStart() const noexcept;
  18699. /** Returns true if the mouse has just been clicked.
  18700. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  18701. the user has dragged the mouse more than a few pixels from the place where the
  18702. mouse-down occurred.
  18703. Once they have dragged it far enough for this method to return false, it will continue
  18704. to return false until the mouse-up, even if they move the mouse back to the same
  18705. position where they originally pressed it. This means that it's very handy for
  18706. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  18707. callback to ignore any small movements they might make while clicking.
  18708. @returns true if the mouse wasn't dragged by more than a few pixels between
  18709. the last time the button was pressed and released.
  18710. */
  18711. bool mouseWasClicked() const noexcept;
  18712. /** For a click event, the number of times the mouse was clicked in succession.
  18713. So for example a double-click event will return 2, a triple-click 3, etc.
  18714. */
  18715. int getNumberOfClicks() const noexcept { return numberOfClicks; }
  18716. /** Returns the time that the mouse button has been held down for.
  18717. If called from a mouseDrag or mouseUp callback, this will return the
  18718. number of milliseconds since the corresponding mouseDown event occurred.
  18719. If called in other contexts, e.g. a mouseMove, then the returned value
  18720. may be 0 or an undefined value.
  18721. */
  18722. int getLengthOfMousePress() const noexcept;
  18723. /** The position of the mouse when the event occurred.
  18724. This position is relative to the top-left of the component to which the
  18725. event applies (as indicated by the MouseEvent::eventComponent field).
  18726. */
  18727. const Point<int> getPosition() const noexcept;
  18728. /** Returns the mouse x position of this event, in global screen co-ordinates.
  18729. The co-ordinates are relative to the top-left of the main monitor.
  18730. @see getScreenPosition
  18731. */
  18732. int getScreenX() const;
  18733. /** Returns the mouse y position of this event, in global screen co-ordinates.
  18734. The co-ordinates are relative to the top-left of the main monitor.
  18735. @see getScreenPosition
  18736. */
  18737. int getScreenY() const;
  18738. /** Returns the mouse position of this event, in global screen co-ordinates.
  18739. The co-ordinates are relative to the top-left of the main monitor.
  18740. @see getMouseDownScreenPosition
  18741. */
  18742. const Point<int> getScreenPosition() const;
  18743. /** Returns the x co-ordinate at which the mouse button was last pressed.
  18744. The co-ordinates are relative to the top-left of the main monitor.
  18745. @see getMouseDownScreenPosition
  18746. */
  18747. int getMouseDownScreenX() const;
  18748. /** Returns the y co-ordinate at which the mouse button was last pressed.
  18749. The co-ordinates are relative to the top-left of the main monitor.
  18750. @see getMouseDownScreenPosition
  18751. */
  18752. int getMouseDownScreenY() const;
  18753. /** Returns the co-ordinates at which the mouse button was last pressed.
  18754. The co-ordinates are relative to the top-left of the main monitor.
  18755. @see getScreenPosition
  18756. */
  18757. const Point<int> getMouseDownScreenPosition() const;
  18758. /** Creates a version of this event that is relative to a different component.
  18759. The x and y positions of the event that is returned will have been
  18760. adjusted to be relative to the new component.
  18761. */
  18762. const MouseEvent getEventRelativeTo (Component* otherComponent) const noexcept;
  18763. /** Creates a copy of this event with a different position.
  18764. All other members of the event object are the same, but the x and y are
  18765. replaced with these new values.
  18766. */
  18767. const MouseEvent withNewPosition (const Point<int>& newPosition) const noexcept;
  18768. /** Changes the application-wide setting for the double-click time limit.
  18769. This is the maximum length of time between mouse-clicks for it to be
  18770. considered a double-click. It's used by the Component class.
  18771. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  18772. */
  18773. static void setDoubleClickTimeout (int timeOutMilliseconds) noexcept;
  18774. /** Returns the application-wide setting for the double-click time limit.
  18775. This is the maximum length of time between mouse-clicks for it to be
  18776. considered a double-click. It's used by the Component class.
  18777. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  18778. */
  18779. static int getDoubleClickTimeout() noexcept;
  18780. private:
  18781. const Point<int> mouseDownPos;
  18782. const Time mouseDownTime;
  18783. const int numberOfClicks;
  18784. const bool wasMovedSinceMouseDown;
  18785. static int doubleClickTimeOutMs;
  18786. MouseEvent& operator= (const MouseEvent&);
  18787. };
  18788. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  18789. /*** End of inlined file: juce_MouseEvent.h ***/
  18790. /*** Start of inlined file: juce_ComponentListener.h ***/
  18791. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18792. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18793. class Component;
  18794. /**
  18795. Gets informed about changes to a component's hierarchy or position.
  18796. To monitor a component for changes, register a subclass of ComponentListener
  18797. with the component using Component::addComponentListener().
  18798. Be sure to deregister listeners before you delete them!
  18799. @see Component::addComponentListener, Component::removeComponentListener
  18800. */
  18801. class JUCE_API ComponentListener
  18802. {
  18803. public:
  18804. /** Destructor. */
  18805. virtual ~ComponentListener() {}
  18806. /** Called when the component's position or size changes.
  18807. @param component the component that was moved or resized
  18808. @param wasMoved true if the component's top-left corner has just moved
  18809. @param wasResized true if the component's width or height has just changed
  18810. @see Component::setBounds, Component::resized, Component::moved
  18811. */
  18812. virtual void componentMovedOrResized (Component& component,
  18813. bool wasMoved,
  18814. bool wasResized);
  18815. /** Called when the component is brought to the top of the z-order.
  18816. @param component the component that was moved
  18817. @see Component::toFront, Component::broughtToFront
  18818. */
  18819. virtual void componentBroughtToFront (Component& component);
  18820. /** Called when the component is made visible or invisible.
  18821. @param component the component that changed
  18822. @see Component::setVisible
  18823. */
  18824. virtual void componentVisibilityChanged (Component& component);
  18825. /** Called when the component has children added or removed.
  18826. @param component the component whose children were changed
  18827. @see Component::childrenChanged, Component::addChildComponent,
  18828. Component::removeChildComponent
  18829. */
  18830. virtual void componentChildrenChanged (Component& component);
  18831. /** Called to indicate that the component's parents have changed.
  18832. When a component is added or removed from its parent, all of its children
  18833. will produce this notification (recursively - so all children of its
  18834. children will also be called as well).
  18835. @param component the component that this listener is registered with
  18836. @see Component::parentHierarchyChanged
  18837. */
  18838. virtual void componentParentHierarchyChanged (Component& component);
  18839. /** Called when the component's name is changed.
  18840. @see Component::setName, Component::getName
  18841. */
  18842. virtual void componentNameChanged (Component& component);
  18843. /** Called when the component is in the process of being deleted.
  18844. This callback is made from inside the destructor, so be very, very cautious
  18845. about what you do in here.
  18846. In particular, bear in mind that it's the Component base class's destructor that calls
  18847. this - so if the object that's being deleted is a subclass of Component, then the
  18848. subclass layers of the object will already have been destructed when it gets to this
  18849. point!
  18850. */
  18851. virtual void componentBeingDeleted (Component& component);
  18852. };
  18853. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18854. /*** End of inlined file: juce_ComponentListener.h ***/
  18855. /*** Start of inlined file: juce_KeyListener.h ***/
  18856. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  18857. #define __JUCE_KEYLISTENER_JUCEHEADER__
  18858. /*** Start of inlined file: juce_KeyPress.h ***/
  18859. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  18860. #define __JUCE_KEYPRESS_JUCEHEADER__
  18861. /**
  18862. Represents a key press, including any modifier keys that are needed.
  18863. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  18864. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  18865. */
  18866. class JUCE_API KeyPress
  18867. {
  18868. public:
  18869. /** Creates an (invalid) KeyPress.
  18870. @see isValid
  18871. */
  18872. KeyPress() noexcept;
  18873. /** Creates a KeyPress for a key and some modifiers.
  18874. e.g.
  18875. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  18876. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  18877. @param keyCode a code that represents the key - this value must be
  18878. one of special constants listed in this class, or an
  18879. 8-bit character code such as a letter (case is ignored),
  18880. digit or a simple key like "," or ".". Note that this
  18881. isn't the same as the textCharacter parameter, so for example
  18882. a keyCode of 'a' and a shift-key modifier should have a
  18883. textCharacter value of 'A'.
  18884. @param modifiers the modifiers to associate with the keystroke
  18885. @param textCharacter the character that would be printed if someone typed
  18886. this keypress into a text editor. This value may be
  18887. null if the keypress is a non-printing character
  18888. @see getKeyCode, isKeyCode, getModifiers
  18889. */
  18890. KeyPress (int keyCode,
  18891. const ModifierKeys& modifiers,
  18892. juce_wchar textCharacter) noexcept;
  18893. /** Creates a keypress with a keyCode but no modifiers or text character.
  18894. */
  18895. KeyPress (int keyCode) noexcept;
  18896. /** Creates a copy of another KeyPress. */
  18897. KeyPress (const KeyPress& other) noexcept;
  18898. /** Copies this KeyPress from another one. */
  18899. KeyPress& operator= (const KeyPress& other) noexcept;
  18900. /** Compares two KeyPress objects. */
  18901. bool operator== (const KeyPress& other) const noexcept;
  18902. /** Compares two KeyPress objects. */
  18903. bool operator!= (const KeyPress& other) const noexcept;
  18904. /** Returns true if this is a valid KeyPress.
  18905. A null keypress can be created by the default constructor, in case it's
  18906. needed.
  18907. */
  18908. bool isValid() const noexcept { return keyCode != 0; }
  18909. /** Returns the key code itself.
  18910. This will either be one of the special constants defined in this class,
  18911. or an 8-bit character code.
  18912. */
  18913. int getKeyCode() const noexcept { return keyCode; }
  18914. /** Returns the key modifiers.
  18915. @see ModifierKeys
  18916. */
  18917. const ModifierKeys getModifiers() const noexcept { return mods; }
  18918. /** Returns the character that is associated with this keypress.
  18919. This is the character that you'd expect to see printed if you press this
  18920. keypress in a text editor or similar component.
  18921. */
  18922. juce_wchar getTextCharacter() const noexcept { return textCharacter; }
  18923. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  18924. the modifiers.
  18925. The values for key codes can either be one of the special constants defined in
  18926. this class, or an 8-bit character code.
  18927. @see getKeyCode
  18928. */
  18929. bool isKeyCode (int keyCodeToCompare) const noexcept { return keyCode == keyCodeToCompare; }
  18930. /** Converts a textual key description to a KeyPress.
  18931. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  18932. This isn't designed to cope with any kind of input, but should be given the
  18933. strings that are created by the getTextDescription() method.
  18934. If the string can't be parsed, the object returned will be invalid.
  18935. @see getTextDescription
  18936. */
  18937. static const KeyPress createFromDescription (const String& textVersion);
  18938. /** Creates a textual description of the key combination.
  18939. e.g. "CTRL + C" or "DELETE".
  18940. To store a keypress in a file, use this method, along with createFromDescription()
  18941. to retrieve it later.
  18942. */
  18943. const String getTextDescription() const;
  18944. /** Creates a textual description of the key combination, using unicode icon symbols if possible.
  18945. On OSX, this uses the Apple symbols for command, option, shift, etc, instead of the textual
  18946. modifier key descriptions that are returned by getTextDescription()
  18947. */
  18948. const String getTextDescriptionWithIcons() const;
  18949. /** Checks whether the user is currently holding down the keys that make up this
  18950. KeyPress.
  18951. Note that this will return false if any extra modifier keys are
  18952. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  18953. then it will be false.
  18954. */
  18955. bool isCurrentlyDown() const;
  18956. /** Checks whether a particular key is held down, irrespective of modifiers.
  18957. The values for key codes can either be one of the special constants defined in
  18958. this class, or an 8-bit character code.
  18959. */
  18960. static bool isKeyCurrentlyDown (int keyCode);
  18961. // Key codes
  18962. //
  18963. // Note that the actual values of these are platform-specific and may change
  18964. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  18965. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  18966. //
  18967. static const int spaceKey; /**< key-code for the space bar */
  18968. static const int escapeKey; /**< key-code for the escape key */
  18969. static const int returnKey; /**< key-code for the return key*/
  18970. static const int tabKey; /**< key-code for the tab key*/
  18971. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  18972. static const int backspaceKey; /**< key-code for the backspace key */
  18973. static const int insertKey; /**< key-code for the insert key */
  18974. static const int upKey; /**< key-code for the cursor-up key */
  18975. static const int downKey; /**< key-code for the cursor-down key */
  18976. static const int leftKey; /**< key-code for the cursor-left key */
  18977. static const int rightKey; /**< key-code for the cursor-right key */
  18978. static const int pageUpKey; /**< key-code for the page-up key */
  18979. static const int pageDownKey; /**< key-code for the page-down key */
  18980. static const int homeKey; /**< key-code for the home key */
  18981. static const int endKey; /**< key-code for the end key */
  18982. static const int F1Key; /**< key-code for the F1 key */
  18983. static const int F2Key; /**< key-code for the F2 key */
  18984. static const int F3Key; /**< key-code for the F3 key */
  18985. static const int F4Key; /**< key-code for the F4 key */
  18986. static const int F5Key; /**< key-code for the F5 key */
  18987. static const int F6Key; /**< key-code for the F6 key */
  18988. static const int F7Key; /**< key-code for the F7 key */
  18989. static const int F8Key; /**< key-code for the F8 key */
  18990. static const int F9Key; /**< key-code for the F9 key */
  18991. static const int F10Key; /**< key-code for the F10 key */
  18992. static const int F11Key; /**< key-code for the F11 key */
  18993. static const int F12Key; /**< key-code for the F12 key */
  18994. static const int F13Key; /**< key-code for the F13 key */
  18995. static const int F14Key; /**< key-code for the F14 key */
  18996. static const int F15Key; /**< key-code for the F15 key */
  18997. static const int F16Key; /**< key-code for the F16 key */
  18998. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  18999. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  19000. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  19001. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  19002. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  19003. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  19004. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  19005. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  19006. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  19007. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  19008. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  19009. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  19010. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  19011. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  19012. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  19013. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  19014. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  19015. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  19016. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  19017. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  19018. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  19019. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  19020. private:
  19021. int keyCode;
  19022. ModifierKeys mods;
  19023. juce_wchar textCharacter;
  19024. JUCE_LEAK_DETECTOR (KeyPress);
  19025. };
  19026. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  19027. /*** End of inlined file: juce_KeyPress.h ***/
  19028. class Component;
  19029. /**
  19030. Receives callbacks when keys are pressed.
  19031. You can add a key listener to a component to be informed when that component
  19032. gets key events. See the Component::addListener method for more details.
  19033. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  19034. */
  19035. class JUCE_API KeyListener
  19036. {
  19037. public:
  19038. /** Destructor. */
  19039. virtual ~KeyListener() {}
  19040. /** Called to indicate that a key has been pressed.
  19041. If your implementation returns true, then the key event is considered to have
  19042. been consumed, and will not be passed on to any other components. If it returns
  19043. false, then the key will be passed to other components that might want to use it.
  19044. @param key the keystroke, including modifier keys
  19045. @param originatingComponent the component that received the key event
  19046. @see keyStateChanged, Component::keyPressed
  19047. */
  19048. virtual bool keyPressed (const KeyPress& key,
  19049. Component* originatingComponent) = 0;
  19050. /** Called when any key is pressed or released.
  19051. When this is called, classes that might be interested in
  19052. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  19053. check whether their key has changed.
  19054. If your implementation returns true, then the key event is considered to have
  19055. been consumed, and will not be passed on to any other components. If it returns
  19056. false, then the key will be passed to other components that might want to use it.
  19057. @param originatingComponent the component that received the key event
  19058. @param isKeyDown true if a key is being pressed, false if one is being released
  19059. @see KeyPress, Component::keyStateChanged
  19060. */
  19061. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  19062. };
  19063. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  19064. /*** End of inlined file: juce_KeyListener.h ***/
  19065. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  19066. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  19067. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  19068. class Component;
  19069. /**
  19070. Controls the order in which focus moves between components.
  19071. The default algorithm used by this class to work out the order of traversal
  19072. is as follows:
  19073. - if two components both have an explicit focus order specified, then the
  19074. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  19075. method).
  19076. - any component with an explicit focus order greater than 0 comes before ones
  19077. that don't have an order specified.
  19078. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  19079. order.
  19080. If you need traversal in a more customised way, you can create a subclass
  19081. of KeyboardFocusTraverser that uses your own algorithm, and use
  19082. Component::createFocusTraverser() to create it.
  19083. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  19084. */
  19085. class JUCE_API KeyboardFocusTraverser
  19086. {
  19087. public:
  19088. KeyboardFocusTraverser();
  19089. /** Destructor. */
  19090. virtual ~KeyboardFocusTraverser();
  19091. /** Returns the component that should be given focus after the specified one
  19092. when moving "forwards".
  19093. The default implementation will return the next component which is to the
  19094. right of or below this one.
  19095. This may return 0 if there's no suitable candidate.
  19096. */
  19097. virtual Component* getNextComponent (Component* current);
  19098. /** Returns the component that should be given focus after the specified one
  19099. when moving "backwards".
  19100. The default implementation will return the next component which is to the
  19101. left of or above this one.
  19102. This may return 0 if there's no suitable candidate.
  19103. */
  19104. virtual Component* getPreviousComponent (Component* current);
  19105. /** Returns the component that should receive focus be default within the given
  19106. parent component.
  19107. The default implementation will just return the foremost child component that
  19108. wants focus.
  19109. This may return 0 if there's no suitable candidate.
  19110. */
  19111. virtual Component* getDefaultComponent (Component* parentComponent);
  19112. };
  19113. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  19114. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  19115. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  19116. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  19117. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  19118. /*** Start of inlined file: juce_Graphics.h ***/
  19119. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  19120. #define __JUCE_GRAPHICS_JUCEHEADER__
  19121. /*** Start of inlined file: juce_Font.h ***/
  19122. #ifndef __JUCE_FONT_JUCEHEADER__
  19123. #define __JUCE_FONT_JUCEHEADER__
  19124. /*** Start of inlined file: juce_Typeface.h ***/
  19125. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  19126. #define __JUCE_TYPEFACE_JUCEHEADER__
  19127. /*** Start of inlined file: juce_Path.h ***/
  19128. #ifndef __JUCE_PATH_JUCEHEADER__
  19129. #define __JUCE_PATH_JUCEHEADER__
  19130. /*** Start of inlined file: juce_Line.h ***/
  19131. #ifndef __JUCE_LINE_JUCEHEADER__
  19132. #define __JUCE_LINE_JUCEHEADER__
  19133. /**
  19134. Represents a line.
  19135. This class contains a bunch of useful methods for various geometric
  19136. tasks.
  19137. The ValueType template parameter should be a primitive type - float or double
  19138. are what it's designed for. Integer types will work in a basic way, but some methods
  19139. that perform mathematical operations may not compile, or they may not produce
  19140. sensible results.
  19141. @see Point, Rectangle, Path, Graphics::drawLine
  19142. */
  19143. template <typename ValueType>
  19144. class Line
  19145. {
  19146. public:
  19147. /** Creates a line, using (0, 0) as its start and end points. */
  19148. Line() noexcept {}
  19149. /** Creates a copy of another line. */
  19150. Line (const Line& other) noexcept
  19151. : start (other.start),
  19152. end (other.end)
  19153. {
  19154. }
  19155. /** Creates a line based on the co-ordinates of its start and end points. */
  19156. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) noexcept
  19157. : start (startX, startY),
  19158. end (endX, endY)
  19159. {
  19160. }
  19161. /** Creates a line from its start and end points. */
  19162. Line (const Point<ValueType>& startPoint,
  19163. const Point<ValueType>& endPoint) noexcept
  19164. : start (startPoint),
  19165. end (endPoint)
  19166. {
  19167. }
  19168. /** Copies a line from another one. */
  19169. Line& operator= (const Line& other) noexcept
  19170. {
  19171. start = other.start;
  19172. end = other.end;
  19173. return *this;
  19174. }
  19175. /** Destructor. */
  19176. ~Line() noexcept {}
  19177. /** Returns the x co-ordinate of the line's start point. */
  19178. inline ValueType getStartX() const noexcept { return start.getX(); }
  19179. /** Returns the y co-ordinate of the line's start point. */
  19180. inline ValueType getStartY() const noexcept { return start.getY(); }
  19181. /** Returns the x co-ordinate of the line's end point. */
  19182. inline ValueType getEndX() const noexcept { return end.getX(); }
  19183. /** Returns the y co-ordinate of the line's end point. */
  19184. inline ValueType getEndY() const noexcept { return end.getY(); }
  19185. /** Returns the line's start point. */
  19186. inline const Point<ValueType>& getStart() const noexcept { return start; }
  19187. /** Returns the line's end point. */
  19188. inline const Point<ValueType>& getEnd() const noexcept { return end; }
  19189. /** Changes this line's start point */
  19190. void setStart (ValueType newStartX, ValueType newStartY) noexcept { start.setXY (newStartX, newStartY); }
  19191. /** Changes this line's end point */
  19192. void setEnd (ValueType newEndX, ValueType newEndY) noexcept { end.setXY (newEndX, newEndY); }
  19193. /** Changes this line's start point */
  19194. void setStart (const Point<ValueType>& newStart) noexcept { start = newStart; }
  19195. /** Changes this line's end point */
  19196. void setEnd (const Point<ValueType>& newEnd) noexcept { end = newEnd; }
  19197. /** Returns a line that is the same as this one, but with the start and end reversed, */
  19198. const Line reversed() const noexcept { return Line (end, start); }
  19199. /** Applies an affine transform to the line's start and end points. */
  19200. void applyTransform (const AffineTransform& transform) noexcept
  19201. {
  19202. start.applyTransform (transform);
  19203. end.applyTransform (transform);
  19204. }
  19205. /** Returns the length of the line. */
  19206. ValueType getLength() const noexcept { return start.getDistanceFrom (end); }
  19207. /** Returns true if the line's start and end x co-ordinates are the same. */
  19208. bool isVertical() const noexcept { return start.getX() == end.getX(); }
  19209. /** Returns true if the line's start and end y co-ordinates are the same. */
  19210. bool isHorizontal() const noexcept { return start.getY() == end.getY(); }
  19211. /** Returns the line's angle.
  19212. This value is the number of radians clockwise from the 3 o'clock direction,
  19213. where the line's start point is considered to be at the centre.
  19214. */
  19215. ValueType getAngle() const noexcept { return start.getAngleToPoint (end); }
  19216. /** Compares two lines. */
  19217. bool operator== (const Line& other) const noexcept { return start == other.start && end == other.end; }
  19218. /** Compares two lines. */
  19219. bool operator!= (const Line& other) const noexcept { return start != other.start || end != other.end; }
  19220. /** Finds the intersection between two lines.
  19221. @param line the other line
  19222. @param intersection the position of the point where the lines meet (or
  19223. where they would meet if they were infinitely long)
  19224. the intersection (if the lines intersect). If the lines
  19225. are parallel, this will just be set to the position
  19226. of one of the line's endpoints.
  19227. @returns true if the line segments intersect; false if they dont. Even if they
  19228. don't intersect, the intersection co-ordinates returned will still
  19229. be valid
  19230. */
  19231. bool intersects (const Line& line, Point<ValueType>& intersection) const noexcept
  19232. {
  19233. return findIntersection (start, end, line.start, line.end, intersection);
  19234. }
  19235. /** Finds the intersection between two lines.
  19236. @param line the line to intersect with
  19237. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  19238. */
  19239. const Point<ValueType> getIntersection (const Line& line) const noexcept
  19240. {
  19241. Point<ValueType> p;
  19242. findIntersection (start, end, line.start, line.end, p);
  19243. return p;
  19244. }
  19245. /** Returns the location of the point which is a given distance along this line.
  19246. @param distanceFromStart the distance to move along the line from its
  19247. start point. This value can be negative or longer
  19248. than the line itself
  19249. @see getPointAlongLineProportionally
  19250. */
  19251. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const noexcept
  19252. {
  19253. return start + (end - start) * (distanceFromStart / getLength());
  19254. }
  19255. /** Returns a point which is a certain distance along and to the side of this line.
  19256. This effectively moves a given distance along the line, then another distance
  19257. perpendicularly to this, and returns the resulting position.
  19258. @param distanceFromStart the distance to move along the line from its
  19259. start point. This value can be negative or longer
  19260. than the line itself
  19261. @param perpendicularDistance how far to move sideways from the line. If you're
  19262. looking along the line from its start towards its
  19263. end, then a positive value here will move to the
  19264. right, negative value move to the left.
  19265. */
  19266. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  19267. ValueType perpendicularDistance) const noexcept
  19268. {
  19269. const Point<ValueType> delta (end - start);
  19270. const double length = juce_hypot ((double) delta.getX(),
  19271. (double) delta.getY());
  19272. if (length <= 0)
  19273. return start;
  19274. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  19275. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  19276. }
  19277. /** Returns the location of the point which is a given distance along this line
  19278. proportional to the line's length.
  19279. @param proportionOfLength the distance to move along the line from its
  19280. start point, in multiples of the line's length.
  19281. So a value of 0.0 will return the line's start point
  19282. and a value of 1.0 will return its end point. (This value
  19283. can be negative or greater than 1.0).
  19284. @see getPointAlongLine
  19285. */
  19286. const Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const noexcept
  19287. {
  19288. return start + (end - start) * proportionOfLength;
  19289. }
  19290. /** Returns the smallest distance between this line segment and a given point.
  19291. So if the point is close to the line, this will return the perpendicular
  19292. distance from the line; if the point is a long way beyond one of the line's
  19293. end-point's, it'll return the straight-line distance to the nearest end-point.
  19294. pointOnLine receives the position of the point that is found.
  19295. @returns the point's distance from the line
  19296. @see getPositionAlongLineOfNearestPoint
  19297. */
  19298. ValueType getDistanceFromPoint (const Point<ValueType>& targetPoint,
  19299. Point<ValueType>& pointOnLine) const noexcept
  19300. {
  19301. const Point<ValueType> delta (end - start);
  19302. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  19303. if (length > 0)
  19304. {
  19305. const double prop = ((targetPoint.getX() - start.getX()) * delta.getX()
  19306. + (targetPoint.getY() - start.getY()) * delta.getY()) / length;
  19307. if (prop >= 0 && prop <= 1.0)
  19308. {
  19309. pointOnLine = start + delta * (ValueType) prop;
  19310. return targetPoint.getDistanceFrom (pointOnLine);
  19311. }
  19312. }
  19313. const float fromStart = targetPoint.getDistanceFrom (start);
  19314. const float fromEnd = targetPoint.getDistanceFrom (end);
  19315. if (fromStart < fromEnd)
  19316. {
  19317. pointOnLine = start;
  19318. return fromStart;
  19319. }
  19320. else
  19321. {
  19322. pointOnLine = end;
  19323. return fromEnd;
  19324. }
  19325. }
  19326. /** Finds the point on this line which is nearest to a given point, and
  19327. returns its position as a proportional position along the line.
  19328. @returns a value 0 to 1.0 which is the distance along this line from the
  19329. line's start to the point which is nearest to the point passed-in. To
  19330. turn this number into a position, use getPointAlongLineProportionally().
  19331. @see getDistanceFromPoint, getPointAlongLineProportionally
  19332. */
  19333. ValueType findNearestProportionalPositionTo (const Point<ValueType>& point) const noexcept
  19334. {
  19335. const Point<ValueType> delta (end - start);
  19336. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  19337. return length <= 0 ? 0
  19338. : jlimit ((ValueType) 0, (ValueType) 1,
  19339. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  19340. + (point.getY() - start.getY()) * delta.getY()) / length));
  19341. }
  19342. /** Finds the point on this line which is nearest to a given point.
  19343. @see getDistanceFromPoint, findNearestProportionalPositionTo
  19344. */
  19345. const Point<ValueType> findNearestPointTo (const Point<ValueType>& point) const noexcept
  19346. {
  19347. return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
  19348. }
  19349. /** Returns true if the given point lies above this line.
  19350. The return value is true if the point's y coordinate is less than the y
  19351. coordinate of this line at the given x (assuming the line extends infinitely
  19352. in both directions).
  19353. */
  19354. bool isPointAbove (const Point<ValueType>& point) const noexcept
  19355. {
  19356. return start.getX() != end.getX()
  19357. && point.getY() < ((end.getY() - start.getY())
  19358. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  19359. }
  19360. /** Returns a shortened copy of this line.
  19361. This will chop off part of the start of this line by a certain amount, (leaving the
  19362. end-point the same), and return the new line.
  19363. */
  19364. const Line withShortenedStart (ValueType distanceToShortenBy) const noexcept
  19365. {
  19366. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  19367. }
  19368. /** Returns a shortened copy of this line.
  19369. This will chop off part of the end of this line by a certain amount, (leaving the
  19370. start-point the same), and return the new line.
  19371. */
  19372. const Line withShortenedEnd (ValueType distanceToShortenBy) const noexcept
  19373. {
  19374. const ValueType length = getLength();
  19375. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  19376. }
  19377. private:
  19378. Point<ValueType> start, end;
  19379. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  19380. const Point<ValueType>& p3, const Point<ValueType>& p4,
  19381. Point<ValueType>& intersection) noexcept
  19382. {
  19383. if (p2 == p3)
  19384. {
  19385. intersection = p2;
  19386. return true;
  19387. }
  19388. const Point<ValueType> d1 (p2 - p1);
  19389. const Point<ValueType> d2 (p4 - p3);
  19390. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  19391. if (divisor == 0)
  19392. {
  19393. if (! (d1.isOrigin() || d2.isOrigin()))
  19394. {
  19395. if (d1.getY() == 0 && d2.getY() != 0)
  19396. {
  19397. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  19398. intersection = p1.withX (p3.getX() + along * d2.getX());
  19399. return along >= 0 && along <= (ValueType) 1;
  19400. }
  19401. else if (d2.getY() == 0 && d1.getY() != 0)
  19402. {
  19403. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  19404. intersection = p3.withX (p1.getX() + along * d1.getX());
  19405. return along >= 0 && along <= (ValueType) 1;
  19406. }
  19407. else if (d1.getX() == 0 && d2.getX() != 0)
  19408. {
  19409. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  19410. intersection = p1.withY (p3.getY() + along * d2.getY());
  19411. return along >= 0 && along <= (ValueType) 1;
  19412. }
  19413. else if (d2.getX() == 0 && d1.getX() != 0)
  19414. {
  19415. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  19416. intersection = p3.withY (p1.getY() + along * d1.getY());
  19417. return along >= 0 && along <= (ValueType) 1;
  19418. }
  19419. }
  19420. intersection = (p2 + p3) / (ValueType) 2;
  19421. return false;
  19422. }
  19423. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  19424. intersection = p1 + d1 * along1;
  19425. if (along1 < 0 || along1 > (ValueType) 1)
  19426. return false;
  19427. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  19428. return along2 >= 0 && along2 <= (ValueType) 1;
  19429. }
  19430. };
  19431. #endif // __JUCE_LINE_JUCEHEADER__
  19432. /*** End of inlined file: juce_Line.h ***/
  19433. /*** Start of inlined file: juce_Rectangle.h ***/
  19434. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  19435. #define __JUCE_RECTANGLE_JUCEHEADER__
  19436. class RectangleList;
  19437. /**
  19438. Manages a rectangle and allows geometric operations to be performed on it.
  19439. @see RectangleList, Path, Line, Point
  19440. */
  19441. template <typename ValueType>
  19442. class Rectangle
  19443. {
  19444. public:
  19445. /** Creates a rectangle of zero size.
  19446. The default co-ordinates will be (0, 0, 0, 0).
  19447. */
  19448. Rectangle() noexcept
  19449. : x(), y(), w(), h()
  19450. {
  19451. }
  19452. /** Creates a copy of another rectangle. */
  19453. Rectangle (const Rectangle& other) noexcept
  19454. : x (other.x), y (other.y),
  19455. w (other.w), h (other.h)
  19456. {
  19457. }
  19458. /** Creates a rectangle with a given position and size. */
  19459. Rectangle (const ValueType initialX, const ValueType initialY,
  19460. const ValueType width, const ValueType height) noexcept
  19461. : x (initialX), y (initialY),
  19462. w (width), h (height)
  19463. {
  19464. }
  19465. /** Creates a rectangle with a given size, and a position of (0, 0). */
  19466. Rectangle (const ValueType width, const ValueType height) noexcept
  19467. : x(), y(), w (width), h (height)
  19468. {
  19469. }
  19470. /** Creates a Rectangle from the positions of two opposite corners. */
  19471. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) noexcept
  19472. : x (jmin (corner1.getX(), corner2.getX())),
  19473. y (jmin (corner1.getY(), corner2.getY())),
  19474. w (corner1.getX() - corner2.getX()),
  19475. h (corner1.getY() - corner2.getY())
  19476. {
  19477. if (w < ValueType()) w = -w;
  19478. if (h < ValueType()) h = -h;
  19479. }
  19480. /** Creates a Rectangle from a set of left, right, top, bottom coordinates.
  19481. The right and bottom values must be larger than the left and top ones, or the resulting
  19482. rectangle will have a negative size.
  19483. */
  19484. static const Rectangle leftTopRightBottom (const ValueType left, const ValueType top,
  19485. const ValueType right, const ValueType bottom) noexcept
  19486. {
  19487. return Rectangle (left, top, right - left, bottom - top);
  19488. }
  19489. Rectangle& operator= (const Rectangle& other) noexcept
  19490. {
  19491. x = other.x; y = other.y;
  19492. w = other.w; h = other.h;
  19493. return *this;
  19494. }
  19495. /** Destructor. */
  19496. ~Rectangle() noexcept {}
  19497. /** Returns true if the rectangle's width and height are both zero or less */
  19498. bool isEmpty() const noexcept { return w <= ValueType() || h <= ValueType(); }
  19499. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  19500. inline ValueType getX() const noexcept { return x; }
  19501. /** Returns the y co-ordinate of the rectangle's top edge. */
  19502. inline ValueType getY() const noexcept { return y; }
  19503. /** Returns the width of the rectangle. */
  19504. inline ValueType getWidth() const noexcept { return w; }
  19505. /** Returns the height of the rectangle. */
  19506. inline ValueType getHeight() const noexcept { return h; }
  19507. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  19508. inline ValueType getRight() const noexcept { return x + w; }
  19509. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  19510. inline ValueType getBottom() const noexcept { return y + h; }
  19511. /** Returns the x co-ordinate of the rectangle's centre. */
  19512. ValueType getCentreX() const noexcept { return x + w / (ValueType) 2; }
  19513. /** Returns the y co-ordinate of the rectangle's centre. */
  19514. ValueType getCentreY() const noexcept { return y + h / (ValueType) 2; }
  19515. /** Returns the centre point of the rectangle. */
  19516. const Point<ValueType> getCentre() const noexcept { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  19517. /** Returns the aspect ratio of the rectangle's width / height.
  19518. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  19519. it returns height / width. */
  19520. ValueType getAspectRatio (const bool widthOverHeight = true) const noexcept { return widthOverHeight ? w / h : h / w; }
  19521. /** Returns the rectangle's top-left position as a Point. */
  19522. const Point<ValueType> getPosition() const noexcept { return Point<ValueType> (x, y); }
  19523. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  19524. void setPosition (const Point<ValueType>& newPos) noexcept { x = newPos.getX(); y = newPos.getY(); }
  19525. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  19526. void setPosition (const ValueType newX, const ValueType newY) noexcept { x = newX; y = newY; }
  19527. /** Returns a rectangle with the same size as this one, but a new position. */
  19528. const Rectangle withPosition (const ValueType newX, const ValueType newY) const noexcept { return Rectangle (newX, newY, w, h); }
  19529. /** Returns a rectangle with the same size as this one, but a new position. */
  19530. const Rectangle withPosition (const Point<ValueType>& newPos) const noexcept { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  19531. /** Returns the rectangle's top-left position as a Point. */
  19532. const Point<ValueType> getTopLeft() const noexcept { return getPosition(); }
  19533. /** Returns the rectangle's top-right position as a Point. */
  19534. const Point<ValueType> getTopRight() const noexcept { return Point<ValueType> (x + w, y); }
  19535. /** Returns the rectangle's bottom-left position as a Point. */
  19536. const Point<ValueType> getBottomLeft() const noexcept { return Point<ValueType> (x, y + h); }
  19537. /** Returns the rectangle's bottom-right position as a Point. */
  19538. const Point<ValueType> getBottomRight() const noexcept { return Point<ValueType> (x + w, y + h); }
  19539. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  19540. void setSize (const ValueType newWidth, const ValueType newHeight) noexcept { w = newWidth; h = newHeight; }
  19541. /** Returns a rectangle with the same position as this one, but a new size. */
  19542. const Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const noexcept { return Rectangle (x, y, newWidth, newHeight); }
  19543. /** Changes all the rectangle's co-ordinates. */
  19544. void setBounds (const ValueType newX, const ValueType newY,
  19545. const ValueType newWidth, const ValueType newHeight) noexcept
  19546. {
  19547. x = newX; y = newY; w = newWidth; h = newHeight;
  19548. }
  19549. /** Changes the rectangle's X coordinate */
  19550. void setX (const ValueType newX) noexcept { x = newX; }
  19551. /** Changes the rectangle's Y coordinate */
  19552. void setY (const ValueType newY) noexcept { y = newY; }
  19553. /** Changes the rectangle's width */
  19554. void setWidth (const ValueType newWidth) noexcept { w = newWidth; }
  19555. /** Changes the rectangle's height */
  19556. void setHeight (const ValueType newHeight) noexcept { h = newHeight; }
  19557. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  19558. const Rectangle withX (const ValueType newX) const noexcept { return Rectangle (newX, y, w, h); }
  19559. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  19560. const Rectangle withY (const ValueType newY) const noexcept { return Rectangle (x, newY, w, h); }
  19561. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  19562. const Rectangle withWidth (const ValueType newWidth) const noexcept { return Rectangle (x, y, newWidth, h); }
  19563. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  19564. const Rectangle withHeight (const ValueType newHeight) const noexcept { return Rectangle (x, y, w, newHeight); }
  19565. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  19566. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  19567. @see withLeft
  19568. */
  19569. void setLeft (const ValueType newLeft) noexcept
  19570. {
  19571. w = jmax (ValueType(), x + w - newLeft);
  19572. x = newLeft;
  19573. }
  19574. /** Returns a new rectangle with a different x position, but the same right-hand edge as this one.
  19575. If the new x is beyond the right of the current right-hand edge, the width will be set to zero.
  19576. @see setLeft
  19577. */
  19578. const Rectangle withLeft (const ValueType newLeft) const noexcept { return Rectangle (newLeft, y, jmax (ValueType(), x + w - newLeft), h); }
  19579. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  19580. If the y is moved to be below the current bottom edge, the height will be set to zero.
  19581. @see withTop
  19582. */
  19583. void setTop (const ValueType newTop) noexcept
  19584. {
  19585. h = jmax (ValueType(), y + h - newTop);
  19586. y = newTop;
  19587. }
  19588. /** Returns a new rectangle with a different y position, but the same bottom edge as this one.
  19589. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  19590. @see setTop
  19591. */
  19592. const Rectangle withTop (const ValueType newTop) const noexcept { return Rectangle (x, newTop, w, jmax (ValueType(), y + h - newTop)); }
  19593. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  19594. If the new right is below the current X value, the X will be pushed down to match it.
  19595. @see getRight, withRight
  19596. */
  19597. void setRight (const ValueType newRight) noexcept
  19598. {
  19599. x = jmin (x, newRight);
  19600. w = newRight - x;
  19601. }
  19602. /** Returns a new rectangle with a different right-hand edge position, but the same left-hand edge as this one.
  19603. If the new right edge is below the current left-hand edge, the width will be set to zero.
  19604. @see setRight
  19605. */
  19606. const Rectangle withRight (const ValueType newRight) const noexcept { return Rectangle (jmin (x, newRight), y, jmax (ValueType(), newRight - x), h); }
  19607. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  19608. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  19609. @see getBottom, withBottom
  19610. */
  19611. void setBottom (const ValueType newBottom) noexcept
  19612. {
  19613. y = jmin (y, newBottom);
  19614. h = newBottom - y;
  19615. }
  19616. /** Returns a new rectangle with a different bottom edge position, but the same top edge as this one.
  19617. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  19618. @see setBottom
  19619. */
  19620. const Rectangle withBottom (const ValueType newBottom) const noexcept { return Rectangle (x, jmin (y, newBottom), w, jmax (ValueType(), newBottom - y)); }
  19621. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  19622. void translate (const ValueType deltaX,
  19623. const ValueType deltaY) noexcept
  19624. {
  19625. x += deltaX;
  19626. y += deltaY;
  19627. }
  19628. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19629. const Rectangle translated (const ValueType deltaX,
  19630. const ValueType deltaY) const noexcept
  19631. {
  19632. return Rectangle (x + deltaX, y + deltaY, w, h);
  19633. }
  19634. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19635. const Rectangle operator+ (const Point<ValueType>& deltaPosition) const noexcept
  19636. {
  19637. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  19638. }
  19639. /** Moves this rectangle by a given amount. */
  19640. Rectangle& operator+= (const Point<ValueType>& deltaPosition) noexcept
  19641. {
  19642. x += deltaPosition.getX(); y += deltaPosition.getY();
  19643. return *this;
  19644. }
  19645. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19646. const Rectangle operator- (const Point<ValueType>& deltaPosition) const noexcept
  19647. {
  19648. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  19649. }
  19650. /** Moves this rectangle by a given amount. */
  19651. Rectangle& operator-= (const Point<ValueType>& deltaPosition) noexcept
  19652. {
  19653. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  19654. return *this;
  19655. }
  19656. /** Expands the rectangle by a given amount.
  19657. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  19658. @see expanded, reduce, reduced
  19659. */
  19660. void expand (const ValueType deltaX,
  19661. const ValueType deltaY) noexcept
  19662. {
  19663. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  19664. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  19665. setBounds (x - deltaX, y - deltaY, nw, nh);
  19666. }
  19667. /** Returns a rectangle that is larger than this one by a given amount.
  19668. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  19669. @see expand, reduce, reduced
  19670. */
  19671. const Rectangle expanded (const ValueType deltaX,
  19672. const ValueType deltaY) const noexcept
  19673. {
  19674. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  19675. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  19676. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  19677. }
  19678. /** Shrinks the rectangle by a given amount.
  19679. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19680. @see reduced, expand, expanded
  19681. */
  19682. void reduce (const ValueType deltaX,
  19683. const ValueType deltaY) noexcept
  19684. {
  19685. expand (-deltaX, -deltaY);
  19686. }
  19687. /** Returns a rectangle that is smaller than this one by a given amount.
  19688. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19689. @see reduce, expand, expanded
  19690. */
  19691. const Rectangle reduced (const ValueType deltaX,
  19692. const ValueType deltaY) const noexcept
  19693. {
  19694. return expanded (-deltaX, -deltaY);
  19695. }
  19696. /** Removes a strip from the top of this rectangle, reducing this rectangle
  19697. by the specified amount and returning the section that was removed.
  19698. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19699. return (100, 100, 300, 50) and leave this rectangle as (100, 150, 300, 250).
  19700. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19701. that value.
  19702. */
  19703. const Rectangle removeFromTop (const ValueType amountToRemove) noexcept
  19704. {
  19705. const Rectangle r (x, y, w, jmin (amountToRemove, h));
  19706. y += r.h; h -= r.h;
  19707. return r;
  19708. }
  19709. /** Removes a strip from the left-hand edge of this rectangle, reducing this rectangle
  19710. by the specified amount and returning the section that was removed.
  19711. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19712. return (100, 100, 50, 300) and leave this rectangle as (150, 100, 250, 300).
  19713. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19714. that value.
  19715. */
  19716. const Rectangle removeFromLeft (const ValueType amountToRemove) noexcept
  19717. {
  19718. const Rectangle r (x, y, jmin (amountToRemove, w), h);
  19719. x += r.w; w -= r.w;
  19720. return r;
  19721. }
  19722. /** Removes a strip from the right-hand edge of this rectangle, reducing this rectangle
  19723. by the specified amount and returning the section that was removed.
  19724. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19725. return (250, 100, 50, 300) and leave this rectangle as (100, 100, 250, 300).
  19726. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19727. that value.
  19728. */
  19729. const Rectangle removeFromRight (ValueType amountToRemove) noexcept
  19730. {
  19731. amountToRemove = jmin (amountToRemove, w);
  19732. const Rectangle r (x + w - amountToRemove, y, amountToRemove, h);
  19733. w -= amountToRemove;
  19734. return r;
  19735. }
  19736. /** Removes a strip from the bottom of this rectangle, reducing this rectangle
  19737. by the specified amount and returning the section that was removed.
  19738. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19739. return (100, 250, 300, 50) and leave this rectangle as (100, 100, 300, 250).
  19740. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19741. that value.
  19742. */
  19743. const Rectangle removeFromBottom (ValueType amountToRemove) noexcept
  19744. {
  19745. amountToRemove = jmin (amountToRemove, h);
  19746. const Rectangle r (x, y + h - amountToRemove, w, amountToRemove);
  19747. h -= amountToRemove;
  19748. return r;
  19749. }
  19750. /** Returns true if the two rectangles are identical. */
  19751. bool operator== (const Rectangle& other) const noexcept
  19752. {
  19753. return x == other.x && y == other.y
  19754. && w == other.w && h == other.h;
  19755. }
  19756. /** Returns true if the two rectangles are not identical. */
  19757. bool operator!= (const Rectangle& other) const noexcept
  19758. {
  19759. return x != other.x || y != other.y
  19760. || w != other.w || h != other.h;
  19761. }
  19762. /** Returns true if this co-ordinate is inside the rectangle. */
  19763. bool contains (const ValueType xCoord, const ValueType yCoord) const noexcept
  19764. {
  19765. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  19766. }
  19767. /** Returns true if this co-ordinate is inside the rectangle. */
  19768. bool contains (const Point<ValueType>& point) const noexcept
  19769. {
  19770. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  19771. }
  19772. /** Returns true if this other rectangle is completely inside this one. */
  19773. bool contains (const Rectangle& other) const noexcept
  19774. {
  19775. return x <= other.x && y <= other.y
  19776. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  19777. }
  19778. /** Returns the nearest point to the specified point that lies within this rectangle. */
  19779. const Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const noexcept
  19780. {
  19781. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  19782. jlimit (y, y + h, point.getY()));
  19783. }
  19784. /** Returns true if any part of another rectangle overlaps this one. */
  19785. bool intersects (const Rectangle& other) const noexcept
  19786. {
  19787. return x + w > other.x
  19788. && y + h > other.y
  19789. && x < other.x + other.w
  19790. && y < other.y + other.h
  19791. && w > ValueType() && h > ValueType();
  19792. }
  19793. /** Returns the region that is the overlap between this and another rectangle.
  19794. If the two rectangles don't overlap, the rectangle returned will be empty.
  19795. */
  19796. const Rectangle getIntersection (const Rectangle& other) const noexcept
  19797. {
  19798. const ValueType nx = jmax (x, other.x);
  19799. const ValueType ny = jmax (y, other.y);
  19800. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  19801. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  19802. if (nw >= ValueType() && nh >= ValueType())
  19803. return Rectangle (nx, ny, nw, nh);
  19804. return Rectangle();
  19805. }
  19806. /** Clips a rectangle so that it lies only within this one.
  19807. This is a non-static version of intersectRectangles().
  19808. Returns false if the two regions didn't overlap.
  19809. */
  19810. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const noexcept
  19811. {
  19812. const int maxX = jmax (otherX, x);
  19813. otherW = jmin (otherX + otherW, x + w) - maxX;
  19814. if (otherW > ValueType())
  19815. {
  19816. const int maxY = jmax (otherY, y);
  19817. otherH = jmin (otherY + otherH, y + h) - maxY;
  19818. if (otherH > ValueType())
  19819. {
  19820. otherX = maxX; otherY = maxY;
  19821. return true;
  19822. }
  19823. }
  19824. return false;
  19825. }
  19826. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  19827. If either this or the other rectangle are empty, they will not be counted as
  19828. part of the resulting region.
  19829. */
  19830. const Rectangle getUnion (const Rectangle& other) const noexcept
  19831. {
  19832. if (other.isEmpty()) return *this;
  19833. if (isEmpty()) return other;
  19834. const ValueType newX = jmin (x, other.x);
  19835. const ValueType newY = jmin (y, other.y);
  19836. return Rectangle (newX, newY,
  19837. jmax (x + w, other.x + other.w) - newX,
  19838. jmax (y + h, other.y + other.h) - newY);
  19839. }
  19840. /** If this rectangle merged with another one results in a simple rectangle, this
  19841. will set this rectangle to the result, and return true.
  19842. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  19843. or if they form a complex region.
  19844. */
  19845. bool enlargeIfAdjacent (const Rectangle& other) noexcept
  19846. {
  19847. if (x == other.x && getRight() == other.getRight()
  19848. && (other.getBottom() >= y && other.y <= getBottom()))
  19849. {
  19850. const ValueType newY = jmin (y, other.y);
  19851. h = jmax (getBottom(), other.getBottom()) - newY;
  19852. y = newY;
  19853. return true;
  19854. }
  19855. else if (y == other.y && getBottom() == other.getBottom()
  19856. && (other.getRight() >= x && other.x <= getRight()))
  19857. {
  19858. const ValueType newX = jmin (x, other.x);
  19859. w = jmax (getRight(), other.getRight()) - newX;
  19860. x = newX;
  19861. return true;
  19862. }
  19863. return false;
  19864. }
  19865. /** If after removing another rectangle from this one the result is a simple rectangle,
  19866. this will set this object's bounds to be the result, and return true.
  19867. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  19868. or if removing the other one would form a complex region.
  19869. */
  19870. bool reduceIfPartlyContainedIn (const Rectangle& other) noexcept
  19871. {
  19872. int inside = 0;
  19873. const int otherR = other.getRight();
  19874. if (x >= other.x && x < otherR) inside = 1;
  19875. const int otherB = other.getBottom();
  19876. if (y >= other.y && y < otherB) inside |= 2;
  19877. const int r = x + w;
  19878. if (r >= other.x && r < otherR) inside |= 4;
  19879. const int b = y + h;
  19880. if (b >= other.y && b < otherB) inside |= 8;
  19881. switch (inside)
  19882. {
  19883. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  19884. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  19885. case 2 + 4 + 8: w = other.x - x; return true;
  19886. case 1 + 4 + 8: h = other.y - y; return true;
  19887. }
  19888. return false;
  19889. }
  19890. /** Returns the smallest rectangle that can contain the shape created by applying
  19891. a transform to this rectangle.
  19892. This should only be used on floating point rectangles.
  19893. */
  19894. const Rectangle transformed (const AffineTransform& transform) const noexcept
  19895. {
  19896. float x1 = x, y1 = y;
  19897. float x2 = x + w, y2 = y;
  19898. float x3 = x, y3 = y + h;
  19899. float x4 = x2, y4 = y3;
  19900. transform.transformPoints (x1, y1, x2, y2);
  19901. transform.transformPoints (x3, y3, x4, y4);
  19902. const float rx = jmin (x1, x2, x3, x4);
  19903. const float ry = jmin (y1, y2, y3, y4);
  19904. return Rectangle (rx, ry,
  19905. jmax (x1, x2, x3, x4) - rx,
  19906. jmax (y1, y2, y3, y4) - ry);
  19907. }
  19908. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  19909. This is only relevent for floating-point rectangles, of course.
  19910. @see toFloat()
  19911. */
  19912. const Rectangle<int> getSmallestIntegerContainer() const noexcept
  19913. {
  19914. const int x1 = (int) std::floor (static_cast<float> (x));
  19915. const int y1 = (int) std::floor (static_cast<float> (y));
  19916. const int x2 = (int) std::ceil (static_cast<float> (x + w));
  19917. const int y2 = (int) std::ceil (static_cast<float> (y + h));
  19918. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  19919. }
  19920. /** Returns the smallest Rectangle that can contain a set of points. */
  19921. static const Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) noexcept
  19922. {
  19923. if (numPoints == 0)
  19924. return Rectangle();
  19925. ValueType minX (points[0].getX());
  19926. ValueType maxX (minX);
  19927. ValueType minY (points[0].getY());
  19928. ValueType maxY (minY);
  19929. for (int i = 1; i < numPoints; ++i)
  19930. {
  19931. minX = jmin (minX, points[i].getX());
  19932. maxX = jmax (maxX, points[i].getX());
  19933. minY = jmin (minY, points[i].getY());
  19934. maxY = jmax (maxY, points[i].getY());
  19935. }
  19936. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  19937. }
  19938. /** Casts this rectangle to a Rectangle<float>.
  19939. Obviously this is mainly useful for rectangles that use integer types.
  19940. @see getSmallestIntegerContainer
  19941. */
  19942. const Rectangle<float> toFloat() const noexcept
  19943. {
  19944. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  19945. static_cast<float> (w), static_cast<float> (h));
  19946. }
  19947. /** Static utility to intersect two sets of rectangular co-ordinates.
  19948. Returns false if the two regions didn't overlap.
  19949. @see intersectRectangle
  19950. */
  19951. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  19952. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) noexcept
  19953. {
  19954. const ValueType x = jmax (x1, x2);
  19955. w1 = jmin (x1 + w1, x2 + w2) - x;
  19956. if (w1 > ValueType())
  19957. {
  19958. const ValueType y = jmax (y1, y2);
  19959. h1 = jmin (y1 + h1, y2 + h2) - y;
  19960. if (h1 > ValueType())
  19961. {
  19962. x1 = x; y1 = y;
  19963. return true;
  19964. }
  19965. }
  19966. return false;
  19967. }
  19968. /** Creates a string describing this rectangle.
  19969. The string will be of the form "x y width height", e.g. "100 100 400 200".
  19970. Coupled with the fromString() method, this is very handy for things like
  19971. storing rectangles (particularly component positions) in XML attributes.
  19972. @see fromString
  19973. */
  19974. const String toString() const
  19975. {
  19976. String s;
  19977. s.preallocateBytes (32);
  19978. s << x << ' ' << y << ' ' << w << ' ' << h;
  19979. return s;
  19980. }
  19981. /** Parses a string containing a rectangle's details.
  19982. The string should contain 4 integer tokens, in the form "x y width height". They
  19983. can be comma or whitespace separated.
  19984. This method is intended to go with the toString() method, to form an easy way
  19985. of saving/loading rectangles as strings.
  19986. @see toString
  19987. */
  19988. static const Rectangle fromString (const String& stringVersion)
  19989. {
  19990. StringArray toks;
  19991. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  19992. return Rectangle (toks[0].trim().getIntValue(),
  19993. toks[1].trim().getIntValue(),
  19994. toks[2].trim().getIntValue(),
  19995. toks[3].trim().getIntValue());
  19996. }
  19997. private:
  19998. friend class RectangleList;
  19999. ValueType x, y, w, h;
  20000. };
  20001. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  20002. /*** End of inlined file: juce_Rectangle.h ***/
  20003. /*** Start of inlined file: juce_Justification.h ***/
  20004. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  20005. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  20006. /**
  20007. Represents a type of justification to be used when positioning graphical items.
  20008. e.g. it indicates whether something should be placed top-left, top-right,
  20009. centred, etc.
  20010. It is used in various places wherever this kind of information is needed.
  20011. */
  20012. class JUCE_API Justification
  20013. {
  20014. public:
  20015. /** Creates a Justification object using a combination of flags. */
  20016. inline Justification (int flags_) noexcept : flags (flags_) {}
  20017. /** Creates a copy of another Justification object. */
  20018. Justification (const Justification& other) noexcept;
  20019. /** Copies another Justification object. */
  20020. Justification& operator= (const Justification& other) noexcept;
  20021. bool operator== (const Justification& other) const noexcept { return flags == other.flags; }
  20022. bool operator!= (const Justification& other) const noexcept { return flags != other.flags; }
  20023. /** Returns the raw flags that are set for this Justification object. */
  20024. inline int getFlags() const noexcept { return flags; }
  20025. /** Tests a set of flags for this object.
  20026. @returns true if any of the flags passed in are set on this object.
  20027. */
  20028. inline bool testFlags (int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  20029. /** Returns just the flags from this object that deal with vertical layout. */
  20030. int getOnlyVerticalFlags() const noexcept;
  20031. /** Returns just the flags from this object that deal with horizontal layout. */
  20032. int getOnlyHorizontalFlags() const noexcept;
  20033. /** Adjusts the position of a rectangle to fit it into a space.
  20034. The (x, y) position of the rectangle will be updated to position it inside the
  20035. given space according to the justification flags.
  20036. */
  20037. template <typename ValueType>
  20038. void applyToRectangle (ValueType& x, ValueType& y, ValueType w, ValueType h,
  20039. ValueType spaceX, ValueType spaceY, ValueType spaceW, ValueType spaceH) const noexcept
  20040. {
  20041. x = spaceX;
  20042. if ((flags & horizontallyCentred) != 0) x += (spaceW - w) / (ValueType) 2;
  20043. else if ((flags & right) != 0) x += spaceW - w;
  20044. y = spaceY;
  20045. if ((flags & verticallyCentred) != 0) y += (spaceH - h) / (ValueType) 2;
  20046. else if ((flags & bottom) != 0) y += spaceH - h;
  20047. }
  20048. /** Returns the new position of a rectangle that has been justified to fit within a given space.
  20049. */
  20050. template <typename ValueType>
  20051. const Rectangle<ValueType> appliedToRectangle (const Rectangle<ValueType>& areaToAdjust,
  20052. const Rectangle<ValueType>& targetSpace) const noexcept
  20053. {
  20054. ValueType x = areaToAdjust.getX(), y = areaToAdjust.getY();
  20055. applyToRectangle (x, y, areaToAdjust.getWidth(), areaToAdjust.getHeight(),
  20056. targetSpace.getX(), targetSpace.getY(), targetSpace.getWidth(), targetSpace.getHeight());
  20057. return areaToAdjust.withPosition (x, y);
  20058. }
  20059. /** Flag values that can be combined and used in the constructor. */
  20060. enum
  20061. {
  20062. /** Indicates that the item should be aligned against the left edge of the available space. */
  20063. left = 1,
  20064. /** Indicates that the item should be aligned against the right edge of the available space. */
  20065. right = 2,
  20066. /** Indicates that the item should be placed in the centre between the left and right
  20067. sides of the available space. */
  20068. horizontallyCentred = 4,
  20069. /** Indicates that the item should be aligned against the top edge of the available space. */
  20070. top = 8,
  20071. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  20072. bottom = 16,
  20073. /** Indicates that the item should be placed in the centre between the top and bottom
  20074. sides of the available space. */
  20075. verticallyCentred = 32,
  20076. /** Indicates that lines of text should be spread out to fill the maximum width
  20077. available, so that both margins are aligned vertically.
  20078. */
  20079. horizontallyJustified = 64,
  20080. /** Indicates that the item should be centred vertically and horizontally.
  20081. This is equivalent to (horizontallyCentred | verticallyCentred)
  20082. */
  20083. centred = 36,
  20084. /** Indicates that the item should be centred vertically but placed on the left hand side.
  20085. This is equivalent to (left | verticallyCentred)
  20086. */
  20087. centredLeft = 33,
  20088. /** Indicates that the item should be centred vertically but placed on the right hand side.
  20089. This is equivalent to (right | verticallyCentred)
  20090. */
  20091. centredRight = 34,
  20092. /** Indicates that the item should be centred horizontally and placed at the top.
  20093. This is equivalent to (horizontallyCentred | top)
  20094. */
  20095. centredTop = 12,
  20096. /** Indicates that the item should be centred horizontally and placed at the bottom.
  20097. This is equivalent to (horizontallyCentred | bottom)
  20098. */
  20099. centredBottom = 20,
  20100. /** Indicates that the item should be placed in the top-left corner.
  20101. This is equivalent to (left | top)
  20102. */
  20103. topLeft = 9,
  20104. /** Indicates that the item should be placed in the top-right corner.
  20105. This is equivalent to (right | top)
  20106. */
  20107. topRight = 10,
  20108. /** Indicates that the item should be placed in the bottom-left corner.
  20109. This is equivalent to (left | bottom)
  20110. */
  20111. bottomLeft = 17,
  20112. /** Indicates that the item should be placed in the bottom-left corner.
  20113. This is equivalent to (right | bottom)
  20114. */
  20115. bottomRight = 18
  20116. };
  20117. private:
  20118. int flags;
  20119. };
  20120. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  20121. /*** End of inlined file: juce_Justification.h ***/
  20122. class Image;
  20123. /**
  20124. A path is a sequence of lines and curves that may either form a closed shape
  20125. or be open-ended.
  20126. To use a path, you can create an empty one, then add lines and curves to it
  20127. to create shapes, then it can be rendered by a Graphics context or used
  20128. for geometric operations.
  20129. e.g. @code
  20130. Path myPath;
  20131. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  20132. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  20133. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  20134. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  20135. // add an ellipse as well, which will form a second sub-path within the path..
  20136. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  20137. // double the width of the whole thing..
  20138. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  20139. // and draw it to a graphics context with a 5-pixel thick outline.
  20140. g.strokePath (myPath, PathStrokeType (5.0f));
  20141. @endcode
  20142. A path object can actually contain multiple sub-paths, which may themselves
  20143. be open or closed.
  20144. @see PathFlatteningIterator, PathStrokeType, Graphics
  20145. */
  20146. class JUCE_API Path
  20147. {
  20148. public:
  20149. /** Creates an empty path. */
  20150. Path();
  20151. /** Creates a copy of another path. */
  20152. Path (const Path& other);
  20153. /** Destructor. */
  20154. ~Path();
  20155. /** Copies this path from another one. */
  20156. Path& operator= (const Path& other);
  20157. bool operator== (const Path& other) const noexcept;
  20158. bool operator!= (const Path& other) const noexcept;
  20159. /** Returns true if the path doesn't contain any lines or curves. */
  20160. bool isEmpty() const noexcept;
  20161. /** Returns the smallest rectangle that contains all points within the path.
  20162. */
  20163. const Rectangle<float> getBounds() const noexcept;
  20164. /** Returns the smallest rectangle that contains all points within the path
  20165. after it's been transformed with the given tranasform matrix.
  20166. */
  20167. const Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const noexcept;
  20168. /** Checks whether a point lies within the path.
  20169. This is only relevent for closed paths (see closeSubPath()), and
  20170. may produce false results if used on a path which has open sub-paths.
  20171. The path's winding rule is taken into account by this method.
  20172. The tolerance parameter is the maximum error allowed when flattening the path,
  20173. so this method could return a false positive when your point is up to this distance
  20174. outside the path's boundary.
  20175. @see closeSubPath, setUsingNonZeroWinding
  20176. */
  20177. bool contains (float x, float y,
  20178. float tolerance = 1.0f) const;
  20179. /** Checks whether a point lies within the path.
  20180. This is only relevent for closed paths (see closeSubPath()), and
  20181. may produce false results if used on a path which has open sub-paths.
  20182. The path's winding rule is taken into account by this method.
  20183. The tolerance parameter is the maximum error allowed when flattening the path,
  20184. so this method could return a false positive when your point is up to this distance
  20185. outside the path's boundary.
  20186. @see closeSubPath, setUsingNonZeroWinding
  20187. */
  20188. bool contains (const Point<float>& point,
  20189. float tolerance = 1.0f) const;
  20190. /** Checks whether a line crosses the path.
  20191. This will return positive if the line crosses any of the paths constituent
  20192. lines or curves. It doesn't take into account whether the line is inside
  20193. or outside the path, or whether the path is open or closed.
  20194. The tolerance parameter is the maximum error allowed when flattening the path,
  20195. so this method could return a false positive when your point is up to this distance
  20196. outside the path's boundary.
  20197. */
  20198. bool intersectsLine (const Line<float>& line,
  20199. float tolerance = 1.0f);
  20200. /** Cuts off parts of a line to keep the parts that are either inside or
  20201. outside this path.
  20202. Note that this isn't smart enough to cope with situations where the
  20203. line would need to be cut into multiple pieces to correctly clip against
  20204. a re-entrant shape.
  20205. @param line the line to clip
  20206. @param keepSectionOutsidePath if true, it's the section outside the path
  20207. that will be kept; if false its the section inside
  20208. the path
  20209. */
  20210. const Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  20211. /** Returns the length of the path.
  20212. @see getPointAlongPath
  20213. */
  20214. float getLength (const AffineTransform& transform = AffineTransform::identity) const;
  20215. /** Returns a point that is the specified distance along the path.
  20216. If the distance is greater than the total length of the path, this will return the
  20217. end point.
  20218. @see getLength
  20219. */
  20220. const Point<float> getPointAlongPath (float distanceFromStart,
  20221. const AffineTransform& transform = AffineTransform::identity) const;
  20222. /** Finds the point along the path which is nearest to a given position.
  20223. This sets pointOnPath to the nearest point, and returns the distance of this point from the start
  20224. of the path.
  20225. */
  20226. float getNearestPoint (const Point<float>& targetPoint,
  20227. Point<float>& pointOnPath,
  20228. const AffineTransform& transform = AffineTransform::identity) const;
  20229. /** Removes all lines and curves, resetting the path completely. */
  20230. void clear() noexcept;
  20231. /** Begins a new subpath with a given starting position.
  20232. This will move the path's current position to the co-ordinates passed in and
  20233. make it ready to draw lines or curves starting from this position.
  20234. After adding whatever lines and curves are needed, you can either
  20235. close the current sub-path using closeSubPath() or call startNewSubPath()
  20236. to move to a new sub-path, leaving the old one open-ended.
  20237. @see lineTo, quadraticTo, cubicTo, closeSubPath
  20238. */
  20239. void startNewSubPath (float startX, float startY);
  20240. /** Begins a new subpath with a given starting position.
  20241. This will move the path's current position to the co-ordinates passed in and
  20242. make it ready to draw lines or curves starting from this position.
  20243. After adding whatever lines and curves are needed, you can either
  20244. close the current sub-path using closeSubPath() or call startNewSubPath()
  20245. to move to a new sub-path, leaving the old one open-ended.
  20246. @see lineTo, quadraticTo, cubicTo, closeSubPath
  20247. */
  20248. void startNewSubPath (const Point<float>& start);
  20249. /** Closes a the current sub-path with a line back to its start-point.
  20250. When creating a closed shape such as a triangle, don't use 3 lineTo()
  20251. calls - instead use two lineTo() calls, followed by a closeSubPath()
  20252. to join the final point back to the start.
  20253. This ensures that closes shapes are recognised as such, and this is
  20254. important for tasks like drawing strokes, which needs to know whether to
  20255. draw end-caps or not.
  20256. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  20257. */
  20258. void closeSubPath();
  20259. /** Adds a line from the shape's last position to a new end-point.
  20260. This will connect the end-point of the last line or curve that was added
  20261. to a new point, using a straight line.
  20262. See the class description for an example of how to add lines and curves to a path.
  20263. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  20264. */
  20265. void lineTo (float endX, float endY);
  20266. /** Adds a line from the shape's last position to a new end-point.
  20267. This will connect the end-point of the last line or curve that was added
  20268. to a new point, using a straight line.
  20269. See the class description for an example of how to add lines and curves to a path.
  20270. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  20271. */
  20272. void lineTo (const Point<float>& end);
  20273. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  20274. This will connect the end-point of the last line or curve that was added
  20275. to a new point, using a quadratic spline with one control-point.
  20276. See the class description for an example of how to add lines and curves to a path.
  20277. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  20278. */
  20279. void quadraticTo (float controlPointX,
  20280. float controlPointY,
  20281. float endPointX,
  20282. float endPointY);
  20283. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  20284. This will connect the end-point of the last line or curve that was added
  20285. to a new point, using a quadratic spline with one control-point.
  20286. See the class description for an example of how to add lines and curves to a path.
  20287. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  20288. */
  20289. void quadraticTo (const Point<float>& controlPoint,
  20290. const Point<float>& endPoint);
  20291. /** Adds a cubic bezier curve from the shape's last position to a new position.
  20292. This will connect the end-point of the last line or curve that was added
  20293. to a new point, using a cubic spline with two control-points.
  20294. See the class description for an example of how to add lines and curves to a path.
  20295. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  20296. */
  20297. void cubicTo (float controlPoint1X,
  20298. float controlPoint1Y,
  20299. float controlPoint2X,
  20300. float controlPoint2Y,
  20301. float endPointX,
  20302. float endPointY);
  20303. /** Adds a cubic bezier curve from the shape's last position to a new position.
  20304. This will connect the end-point of the last line or curve that was added
  20305. to a new point, using a cubic spline with two control-points.
  20306. See the class description for an example of how to add lines and curves to a path.
  20307. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  20308. */
  20309. void cubicTo (const Point<float>& controlPoint1,
  20310. const Point<float>& controlPoint2,
  20311. const Point<float>& endPoint);
  20312. /** Returns the last point that was added to the path by one of the drawing methods.
  20313. */
  20314. const Point<float> getCurrentPosition() const;
  20315. /** Adds a rectangle to the path.
  20316. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20317. @see addRoundedRectangle, addTriangle
  20318. */
  20319. void addRectangle (float x, float y, float width, float height);
  20320. /** Adds a rectangle to the path.
  20321. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20322. @see addRoundedRectangle, addTriangle
  20323. */
  20324. template <typename ValueType>
  20325. void addRectangle (const Rectangle<ValueType>& rectangle)
  20326. {
  20327. addRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  20328. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()));
  20329. }
  20330. /** Adds a rectangle with rounded corners to the path.
  20331. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20332. @see addRectangle, addTriangle
  20333. */
  20334. void addRoundedRectangle (float x, float y, float width, float height,
  20335. float cornerSize);
  20336. /** Adds a rectangle with rounded corners to the path.
  20337. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20338. @see addRectangle, addTriangle
  20339. */
  20340. void addRoundedRectangle (float x, float y, float width, float height,
  20341. float cornerSizeX,
  20342. float cornerSizeY);
  20343. /** Adds a rectangle with rounded corners to the path.
  20344. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20345. @see addRectangle, addTriangle
  20346. */
  20347. template <typename ValueType>
  20348. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSizeX, float cornerSizeY)
  20349. {
  20350. addRoundedRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  20351. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()),
  20352. cornerSizeX, cornerSizeY);
  20353. }
  20354. /** Adds a rectangle with rounded corners to the path.
  20355. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20356. @see addRectangle, addTriangle
  20357. */
  20358. template <typename ValueType>
  20359. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSize)
  20360. {
  20361. addRoundedRectangle (rectangle, cornerSize, cornerSize);
  20362. }
  20363. /** Adds a triangle to the path.
  20364. The triangle is added as a new closed sub-path. (Any currently open paths will be left open).
  20365. Note that whether the vertices are specified in clockwise or anticlockwise
  20366. order will affect how the triangle is filled when it overlaps other
  20367. shapes (the winding order setting will affect this of course).
  20368. */
  20369. void addTriangle (float x1, float y1,
  20370. float x2, float y2,
  20371. float x3, float y3);
  20372. /** Adds a quadrilateral to the path.
  20373. The quad is added as a new closed sub-path. (Any currently open paths will be left open).
  20374. Note that whether the vertices are specified in clockwise or anticlockwise
  20375. order will affect how the quad is filled when it overlaps other
  20376. shapes (the winding order setting will affect this of course).
  20377. */
  20378. void addQuadrilateral (float x1, float y1,
  20379. float x2, float y2,
  20380. float x3, float y3,
  20381. float x4, float y4);
  20382. /** Adds an ellipse to the path.
  20383. The shape is added as a new sub-path. (Any currently open paths will be left open).
  20384. @see addArc
  20385. */
  20386. void addEllipse (float x, float y, float width, float height);
  20387. /** Adds an elliptical arc to the current path.
  20388. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20389. or anti-clockwise according to whether the end angle is greater than the start. This means
  20390. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20391. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  20392. @param y the top edge of the rectangle in which the elliptical outline fits
  20393. @param width the width of the rectangle in which the elliptical outline fits
  20394. @param height the height of the rectangle in which the elliptical outline fits
  20395. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20396. top-centre of the ellipse)
  20397. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20398. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  20399. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  20400. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  20401. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  20402. it will be added to the current sub-path, continuing from the current postition
  20403. @see addCentredArc, arcTo, addPieSegment, addEllipse
  20404. */
  20405. void addArc (float x, float y, float width, float height,
  20406. float fromRadians,
  20407. float toRadians,
  20408. bool startAsNewSubPath = false);
  20409. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  20410. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20411. or anti-clockwise according to whether the end angle is greater than the start. This means
  20412. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20413. @param centreX the centre x of the ellipse
  20414. @param centreY the centre y of the ellipse
  20415. @param radiusX the horizontal radius of the ellipse
  20416. @param radiusY the vertical radius of the ellipse
  20417. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  20418. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20419. top-centre of the ellipse)
  20420. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20421. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  20422. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  20423. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  20424. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  20425. it will be added to the current sub-path, continuing from the current postition
  20426. @see addArc, arcTo
  20427. */
  20428. void addCentredArc (float centreX, float centreY,
  20429. float radiusX, float radiusY,
  20430. float rotationOfEllipse,
  20431. float fromRadians,
  20432. float toRadians,
  20433. bool startAsNewSubPath = false);
  20434. /** Adds a "pie-chart" shape to the path.
  20435. The shape is added as a new sub-path. (Any currently open paths will be
  20436. left open).
  20437. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20438. or anti-clockwise according to whether the end angle is greater than the start. This means
  20439. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20440. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  20441. @param y the top edge of the rectangle in which the elliptical outline fits
  20442. @param width the width of the rectangle in which the elliptical outline fits
  20443. @param height the height of the rectangle in which the elliptical outline fits
  20444. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20445. top-centre of the ellipse)
  20446. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20447. top-centre of the ellipse)
  20448. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  20449. ellipse at its centre, where this value indicates the inner ellipse's size with
  20450. respect to the outer one.
  20451. @see addArc
  20452. */
  20453. void addPieSegment (float x, float y,
  20454. float width, float height,
  20455. float fromRadians,
  20456. float toRadians,
  20457. float innerCircleProportionalSize);
  20458. /** Adds a line with a specified thickness.
  20459. The line is added as a new closed sub-path. (Any currently open paths will be
  20460. left open).
  20461. @see addArrow
  20462. */
  20463. void addLineSegment (const Line<float>& line, float lineThickness);
  20464. /** Adds a line with an arrowhead on the end.
  20465. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  20466. @see PathStrokeType::createStrokeWithArrowheads
  20467. */
  20468. void addArrow (const Line<float>& line,
  20469. float lineThickness,
  20470. float arrowheadWidth,
  20471. float arrowheadLength);
  20472. /** Adds a polygon shape to the path.
  20473. @see addStar
  20474. */
  20475. void addPolygon (const Point<float>& centre,
  20476. int numberOfSides,
  20477. float radius,
  20478. float startAngle = 0.0f);
  20479. /** Adds a star shape to the path.
  20480. @see addPolygon
  20481. */
  20482. void addStar (const Point<float>& centre,
  20483. int numberOfPoints,
  20484. float innerRadius,
  20485. float outerRadius,
  20486. float startAngle = 0.0f);
  20487. /** Adds a speech-bubble shape to the path.
  20488. @param bodyX the left of the main body area of the bubble
  20489. @param bodyY the top of the main body area of the bubble
  20490. @param bodyW the width of the main body area of the bubble
  20491. @param bodyH the height of the main body area of the bubble
  20492. @param cornerSize the amount by which to round off the corners of the main body rectangle
  20493. @param arrowTipX the x position that the tip of the arrow should connect to
  20494. @param arrowTipY the y position that the tip of the arrow should connect to
  20495. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  20496. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  20497. arrow's base should be - this is a proportional distance between 0 and 1.0
  20498. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  20499. */
  20500. void addBubble (float bodyX, float bodyY,
  20501. float bodyW, float bodyH,
  20502. float cornerSize,
  20503. float arrowTipX,
  20504. float arrowTipY,
  20505. int whichSide,
  20506. float arrowPositionAlongEdgeProportional,
  20507. float arrowWidth);
  20508. /** Adds another path to this one.
  20509. The new path is added as a new sub-path. (Any currently open paths in this
  20510. path will be left open).
  20511. @param pathToAppend the path to add
  20512. */
  20513. void addPath (const Path& pathToAppend);
  20514. /** Adds another path to this one, transforming it on the way in.
  20515. The new path is added as a new sub-path, its points being transformed by the given
  20516. matrix before being added.
  20517. @param pathToAppend the path to add
  20518. @param transformToApply an optional transform to apply to the incoming vertices
  20519. */
  20520. void addPath (const Path& pathToAppend,
  20521. const AffineTransform& transformToApply);
  20522. /** Swaps the contents of this path with another one.
  20523. The internal data of the two paths is swapped over, so this is much faster than
  20524. copying it to a temp variable and back.
  20525. */
  20526. void swapWithPath (Path& other) noexcept;
  20527. /** Applies a 2D transform to all the vertices in the path.
  20528. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  20529. */
  20530. void applyTransform (const AffineTransform& transform) noexcept;
  20531. /** Rescales this path to make it fit neatly into a given space.
  20532. This is effectively a quick way of calling
  20533. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  20534. @param x the x position of the rectangle to fit the path inside
  20535. @param y the y position of the rectangle to fit the path inside
  20536. @param width the width of the rectangle to fit the path inside
  20537. @param height the height of the rectangle to fit the path inside
  20538. @param preserveProportions if true, it will fit the path into the space without altering its
  20539. horizontal/vertical scale ratio; if false, it will distort the
  20540. path to fill the specified ratio both horizontally and vertically
  20541. @see applyTransform, getTransformToScaleToFit
  20542. */
  20543. void scaleToFit (float x, float y, float width, float height,
  20544. bool preserveProportions) noexcept;
  20545. /** Returns a transform that can be used to rescale the path to fit into a given space.
  20546. @param x the x position of the rectangle to fit the path inside
  20547. @param y the y position of the rectangle to fit the path inside
  20548. @param width the width of the rectangle to fit the path inside
  20549. @param height the height of the rectangle to fit the path inside
  20550. @param preserveProportions if true, it will fit the path into the space without altering its
  20551. horizontal/vertical scale ratio; if false, it will distort the
  20552. path to fill the specified ratio both horizontally and vertically
  20553. @param justificationType if the proportions are preseved, the resultant path may be smaller
  20554. than the available rectangle, so this describes how it should be
  20555. positioned within the space.
  20556. @returns an appropriate transformation
  20557. @see applyTransform, scaleToFit
  20558. */
  20559. const AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  20560. bool preserveProportions,
  20561. const Justification& justificationType = Justification::centred) const;
  20562. /** Creates a version of this path where all sharp corners have been replaced by curves.
  20563. Wherever two lines meet at an angle, this will replace the corner with a curve
  20564. of the given radius.
  20565. */
  20566. const Path createPathWithRoundedCorners (float cornerRadius) const;
  20567. /** Changes the winding-rule to be used when filling the path.
  20568. If set to true (which is the default), then the path uses a non-zero-winding rule
  20569. to determine which points are inside the path. If set to false, it uses an
  20570. alternate-winding rule.
  20571. The winding-rule comes into play when areas of the shape overlap other
  20572. areas, and determines whether the overlapping regions are considered to be
  20573. inside or outside.
  20574. Changing this value just sets a flag - it doesn't affect the contents of the
  20575. path.
  20576. @see isUsingNonZeroWinding
  20577. */
  20578. void setUsingNonZeroWinding (bool isNonZeroWinding) noexcept;
  20579. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  20580. The default for a new path is true.
  20581. @see setUsingNonZeroWinding
  20582. */
  20583. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  20584. /** Iterates the lines and curves that a path contains.
  20585. @see Path, PathFlatteningIterator
  20586. */
  20587. class JUCE_API Iterator
  20588. {
  20589. public:
  20590. Iterator (const Path& path);
  20591. ~Iterator();
  20592. /** Moves onto the next element in the path.
  20593. If this returns false, there are no more elements. If it returns true,
  20594. the elementType variable will be set to the type of the current element,
  20595. and some of the x and y variables will be filled in with values.
  20596. */
  20597. bool next();
  20598. enum PathElementType
  20599. {
  20600. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  20601. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  20602. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  20603. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  20604. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  20605. };
  20606. PathElementType elementType;
  20607. float x1, y1, x2, y2, x3, y3;
  20608. private:
  20609. const Path& path;
  20610. size_t index;
  20611. JUCE_DECLARE_NON_COPYABLE (Iterator);
  20612. };
  20613. /** Loads a stored path from a data stream.
  20614. The data in the stream must have been written using writePathToStream().
  20615. Note that this will append the stored path to whatever is currently in
  20616. this path, so you might need to call clear() beforehand.
  20617. @see loadPathFromData, writePathToStream
  20618. */
  20619. void loadPathFromStream (InputStream& source);
  20620. /** Loads a stored path from a block of data.
  20621. This is similar to loadPathFromStream(), but just reads from a block
  20622. of data. Useful if you're including stored shapes in your code as a
  20623. block of static data.
  20624. @see loadPathFromStream, writePathToStream
  20625. */
  20626. void loadPathFromData (const void* data, int numberOfBytes);
  20627. /** Stores the path by writing it out to a stream.
  20628. After writing out a path, you can reload it using loadPathFromStream().
  20629. @see loadPathFromStream, loadPathFromData
  20630. */
  20631. void writePathToStream (OutputStream& destination) const;
  20632. /** Creates a string containing a textual representation of this path.
  20633. @see restoreFromString
  20634. */
  20635. const String toString() const;
  20636. /** Restores this path from a string that was created with the toString() method.
  20637. @see toString()
  20638. */
  20639. void restoreFromString (const String& stringVersion);
  20640. private:
  20641. friend class PathFlatteningIterator;
  20642. friend class Path::Iterator;
  20643. ArrayAllocationBase <float, DummyCriticalSection> data;
  20644. size_t numElements;
  20645. float pathXMin, pathXMax, pathYMin, pathYMax;
  20646. bool useNonZeroWinding;
  20647. static const float lineMarker;
  20648. static const float moveMarker;
  20649. static const float quadMarker;
  20650. static const float cubicMarker;
  20651. static const float closeSubPathMarker;
  20652. JUCE_LEAK_DETECTOR (Path);
  20653. };
  20654. #endif // __JUCE_PATH_JUCEHEADER__
  20655. /*** End of inlined file: juce_Path.h ***/
  20656. class Font;
  20657. class EdgeTable;
  20658. /** A typeface represents a size-independent font.
  20659. This base class is abstract, but calling createSystemTypefaceFor() will return
  20660. a platform-specific subclass that can be used.
  20661. The CustomTypeface subclass allow you to build your own typeface, and to
  20662. load and save it in the Juce typeface format.
  20663. Normally you should never need to deal directly with Typeface objects - the Font
  20664. class does everything you typically need for rendering text.
  20665. @see CustomTypeface, Font
  20666. */
  20667. class JUCE_API Typeface : public ReferenceCountedObject
  20668. {
  20669. public:
  20670. /** A handy typedef for a pointer to a typeface. */
  20671. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  20672. /** Returns the name of the typeface.
  20673. @see Font::getTypefaceName
  20674. */
  20675. const String getName() const noexcept { return name; }
  20676. /** Creates a new system typeface. */
  20677. static const Ptr createSystemTypefaceFor (const Font& font);
  20678. /** Destructor. */
  20679. virtual ~Typeface();
  20680. /** Returns true if this typeface can be used to render the specified font.
  20681. When called, the font will already have been checked to make sure that its name and
  20682. style flags match the typeface.
  20683. */
  20684. virtual bool isSuitableForFont (const Font&) const { return true; }
  20685. /** Returns the ascent of the font, as a proportion of its height.
  20686. The height is considered to always be normalised as 1.0, so this will be a
  20687. value less that 1.0, indicating the proportion of the font that lies above
  20688. its baseline.
  20689. */
  20690. virtual float getAscent() const = 0;
  20691. /** Returns the descent of the font, as a proportion of its height.
  20692. The height is considered to always be normalised as 1.0, so this will be a
  20693. value less that 1.0, indicating the proportion of the font that lies below
  20694. its baseline.
  20695. */
  20696. virtual float getDescent() const = 0;
  20697. /** Measures the width of a line of text.
  20698. The distance returned is based on the font having an normalised height of 1.0.
  20699. You should never need to call this directly! Use Font::getStringWidth() instead!
  20700. */
  20701. virtual float getStringWidth (const String& text) = 0;
  20702. /** Converts a line of text into its glyph numbers and their positions.
  20703. The distances returned are based on the font having an normalised height of 1.0.
  20704. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  20705. */
  20706. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  20707. /** Returns the outline for a glyph.
  20708. The path returned will be normalised to a font height of 1.0.
  20709. */
  20710. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  20711. /** Returns a new EdgeTable that contains the path for the givem glyph, with the specified transform applied. */
  20712. virtual EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  20713. /** Returns true if the typeface uses hinting. */
  20714. virtual bool isHinted() const { return false; }
  20715. /** Changes the number of fonts that are cached in memory. */
  20716. static void setTypefaceCacheSize (int numFontsToCache);
  20717. protected:
  20718. String name;
  20719. bool isFallbackFont;
  20720. explicit Typeface (const String& name) noexcept;
  20721. static const Ptr getFallbackTypeface();
  20722. private:
  20723. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Typeface);
  20724. };
  20725. /** A typeface that can be populated with custom glyphs.
  20726. You can create a CustomTypeface if you need one that contains your own glyphs,
  20727. or if you need to load a typeface from a Juce-formatted binary stream.
  20728. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  20729. to copy glyphs into this face.
  20730. @see Typeface, Font
  20731. */
  20732. class JUCE_API CustomTypeface : public Typeface
  20733. {
  20734. public:
  20735. /** Creates a new, empty typeface. */
  20736. CustomTypeface();
  20737. /** Loads a typeface from a previously saved stream.
  20738. The stream must have been created by writeToStream().
  20739. @see writeToStream
  20740. */
  20741. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  20742. /** Destructor. */
  20743. ~CustomTypeface();
  20744. /** Resets this typeface, deleting all its glyphs and settings. */
  20745. void clear();
  20746. /** Sets the vital statistics for the typeface.
  20747. @param name the typeface's name
  20748. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  20749. the value that will be returned by Typeface::getAscent(). The
  20750. descent is assumed to be (1.0 - ascent)
  20751. @param isBold should be true if the typeface is bold
  20752. @param isItalic should be true if the typeface is italic
  20753. @param defaultCharacter the character to be used as a replacement if there's
  20754. no glyph available for the character that's being drawn
  20755. */
  20756. void setCharacteristics (const String& name, float ascent,
  20757. bool isBold, bool isItalic,
  20758. juce_wchar defaultCharacter) noexcept;
  20759. /** Adds a glyph to the typeface.
  20760. The path that is passed in is normalised so that the font height is 1.0, and its
  20761. origin is the anchor point of the character on its baseline.
  20762. The width is the nominal width of the character, and any extra kerning values that
  20763. are specified will be added to this width.
  20764. */
  20765. void addGlyph (juce_wchar character, const Path& path, float width) noexcept;
  20766. /** Specifies an extra kerning amount to be used between a pair of characters.
  20767. The amount will be added to the nominal width of the first character when laying out a string.
  20768. */
  20769. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) noexcept;
  20770. /** Adds a range of glyphs from another typeface.
  20771. This will attempt to pull in the paths and kerning information from another typeface and
  20772. add it to this one.
  20773. */
  20774. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) noexcept;
  20775. /** Saves this typeface as a Juce-formatted font file.
  20776. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  20777. constructor.
  20778. */
  20779. bool writeToStream (OutputStream& outputStream);
  20780. // The following methods implement the basic Typeface behaviour.
  20781. float getAscent() const;
  20782. float getDescent() const;
  20783. float getStringWidth (const String& text);
  20784. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  20785. bool getOutlineForGlyph (int glyphNumber, Path& path);
  20786. EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform);
  20787. int getGlyphForCharacter (juce_wchar character);
  20788. protected:
  20789. juce_wchar defaultCharacter;
  20790. float ascent;
  20791. bool isBold, isItalic;
  20792. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  20793. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  20794. particular character and there's no corresponding glyph, they'll call this
  20795. method so that a subclass can try to add that glyph, returning true if it
  20796. manages to do so.
  20797. */
  20798. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  20799. private:
  20800. class GlyphInfo;
  20801. friend class OwnedArray<GlyphInfo>;
  20802. OwnedArray <GlyphInfo> glyphs;
  20803. short lookupTable [128];
  20804. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) noexcept;
  20805. GlyphInfo* findGlyphSubstituting (juce_wchar character) noexcept;
  20806. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomTypeface);
  20807. };
  20808. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  20809. /*** End of inlined file: juce_Typeface.h ***/
  20810. class LowLevelGraphicsContext;
  20811. /**
  20812. Represents a particular font, including its size, style, etc.
  20813. Apart from the typeface to be used, a Font object also dictates whether
  20814. the font is bold, italic, underlined, how big it is, and its kerning and
  20815. horizontal scale factor.
  20816. @see Typeface
  20817. */
  20818. class JUCE_API Font
  20819. {
  20820. public:
  20821. /** A combination of these values is used by the constructor to specify the
  20822. style of font to use.
  20823. */
  20824. enum FontStyleFlags
  20825. {
  20826. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  20827. bold = 1, /**< boldens the font. @see setStyleFlags */
  20828. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  20829. underlined = 4 /**< underlines the font. @see setStyleFlags */
  20830. };
  20831. /** Creates a sans-serif font in a given size.
  20832. @param fontHeight the height in pixels (can be fractional)
  20833. @param styleFlags the style to use - this can be a combination of the
  20834. Font::bold, Font::italic and Font::underlined, or
  20835. just Font::plain for the normal style.
  20836. @see FontStyleFlags, getDefaultSansSerifFontName
  20837. */
  20838. Font (float fontHeight, int styleFlags = plain);
  20839. /** Creates a font with a given typeface and parameters.
  20840. @param typefaceName the name of the typeface to use
  20841. @param fontHeight the height in pixels (can be fractional)
  20842. @param styleFlags the style to use - this can be a combination of the
  20843. Font::bold, Font::italic and Font::underlined, or
  20844. just Font::plain for the normal style.
  20845. @see FontStyleFlags, getDefaultSansSerifFontName
  20846. */
  20847. Font (const String& typefaceName, float fontHeight, int styleFlags);
  20848. /** Creates a copy of another Font object. */
  20849. Font (const Font& other) noexcept;
  20850. /** Creates a font for a typeface. */
  20851. Font (const Typeface::Ptr& typeface);
  20852. /** Creates a basic sans-serif font at a default height.
  20853. You should use one of the other constructors for creating a font that you're planning
  20854. on drawing with - this constructor is here to help initialise objects before changing
  20855. the font's settings later.
  20856. */
  20857. Font();
  20858. /** Copies this font from another one. */
  20859. Font& operator= (const Font& other) noexcept;
  20860. bool operator== (const Font& other) const noexcept;
  20861. bool operator!= (const Font& other) const noexcept;
  20862. /** Destructor. */
  20863. ~Font() noexcept;
  20864. /** Changes the name of the typeface family.
  20865. e.g. "Arial", "Courier", etc.
  20866. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  20867. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  20868. but are generic names that are used to represent the various default fonts.
  20869. If you need to know the exact typeface name being used, you can call
  20870. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  20871. If a suitable font isn't found on the machine, it'll just use a default instead.
  20872. */
  20873. void setTypefaceName (const String& faceName);
  20874. /** Returns the name of the typeface family that this font uses.
  20875. e.g. "Arial", "Courier", etc.
  20876. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  20877. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  20878. but are generic names that are used to represent the various default fonts.
  20879. If you need to know the exact typeface name being used, you can call
  20880. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  20881. */
  20882. const String& getTypefaceName() const noexcept { return font->typefaceName; }
  20883. /** Returns a typeface name that represents the default sans-serif font.
  20884. This is also the typeface that will be used when a font is created without
  20885. specifying any typeface details.
  20886. Note that this method just returns a generic placeholder string that means "the default
  20887. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  20888. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20889. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  20890. */
  20891. static const String getDefaultSansSerifFontName();
  20892. /** Returns a typeface name that represents the default sans-serif font.
  20893. Note that this method just returns a generic placeholder string that means "the default
  20894. serif font" - it's not the actual name of this font. To get the actual name, use
  20895. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20896. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  20897. */
  20898. static const String getDefaultSerifFontName();
  20899. /** Returns a typeface name that represents the default sans-serif font.
  20900. Note that this method just returns a generic placeholder string that means "the default
  20901. monospaced font" - it's not the actual name of this font. To get the actual name, use
  20902. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20903. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  20904. */
  20905. static const String getDefaultMonospacedFontName();
  20906. /** Returns the typeface names of the default fonts on the current platform. */
  20907. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback);
  20908. /** Returns the total height of this font.
  20909. This is the maximum height, from the top of the ascent to the bottom of the
  20910. descenders.
  20911. @see setHeight, setHeightWithoutChangingWidth, getAscent
  20912. */
  20913. float getHeight() const noexcept { return font->height; }
  20914. /** Changes the font's height.
  20915. @see getHeight, setHeightWithoutChangingWidth
  20916. */
  20917. void setHeight (float newHeight);
  20918. /** Changes the font's height without changing its width.
  20919. This alters the horizontal scale to compensate for the change in height.
  20920. */
  20921. void setHeightWithoutChangingWidth (float newHeight);
  20922. /** Returns the height of the font above its baseline.
  20923. This is the maximum height from the baseline to the top.
  20924. @see getHeight, getDescent
  20925. */
  20926. float getAscent() const;
  20927. /** Returns the amount that the font descends below its baseline.
  20928. This is calculated as (getHeight() - getAscent()).
  20929. @see getAscent, getHeight
  20930. */
  20931. float getDescent() const;
  20932. /** Returns the font's style flags.
  20933. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  20934. enum, to describe whether the font is bold, italic, etc.
  20935. @see FontStyleFlags
  20936. */
  20937. int getStyleFlags() const noexcept { return font->styleFlags; }
  20938. /** Changes the font's style.
  20939. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  20940. enum, to set the font's properties
  20941. @see FontStyleFlags
  20942. */
  20943. void setStyleFlags (int newFlags);
  20944. /** Makes the font bold or non-bold. */
  20945. void setBold (bool shouldBeBold);
  20946. /** Returns a copy of this font with the bold attribute set. */
  20947. const Font boldened() const;
  20948. /** Returns true if the font is bold. */
  20949. bool isBold() const noexcept;
  20950. /** Makes the font italic or non-italic. */
  20951. void setItalic (bool shouldBeItalic);
  20952. /** Returns a copy of this font with the italic attribute set. */
  20953. const Font italicised() const;
  20954. /** Returns true if the font is italic. */
  20955. bool isItalic() const noexcept;
  20956. /** Makes the font underlined or non-underlined. */
  20957. void setUnderline (bool shouldBeUnderlined);
  20958. /** Returns true if the font is underlined. */
  20959. bool isUnderlined() const noexcept;
  20960. /** Changes the font's horizontal scale factor.
  20961. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  20962. narrower, greater than 1.0 will be stretched out.
  20963. */
  20964. void setHorizontalScale (float scaleFactor);
  20965. /** Returns the font's horizontal scale.
  20966. A value of 1.0 is the normal scale, less than this will be narrower, greater
  20967. than 1.0 will be stretched out.
  20968. @see setHorizontalScale
  20969. */
  20970. float getHorizontalScale() const noexcept { return font->horizontalScale; }
  20971. /** Changes the font's kerning.
  20972. @param extraKerning a multiple of the font's height that will be added
  20973. to space between the characters. So a value of zero is
  20974. normal spacing, positive values spread the letters out,
  20975. negative values make them closer together.
  20976. */
  20977. void setExtraKerningFactor (float extraKerning);
  20978. /** Returns the font's kerning.
  20979. This is the extra space added between adjacent characters, as a proportion
  20980. of the font's height.
  20981. A value of zero is normal spacing, positive values will spread the letters
  20982. out more, and negative values make them closer together.
  20983. */
  20984. float getExtraKerningFactor() const noexcept { return font->kerning; }
  20985. /** Changes all the font's characteristics with one call. */
  20986. void setSizeAndStyle (float newHeight,
  20987. int newStyleFlags,
  20988. float newHorizontalScale,
  20989. float newKerningAmount);
  20990. /** Returns the total width of a string as it would be drawn using this font.
  20991. For a more accurate floating-point result, use getStringWidthFloat().
  20992. */
  20993. int getStringWidth (const String& text) const;
  20994. /** Returns the total width of a string as it would be drawn using this font.
  20995. @see getStringWidth
  20996. */
  20997. float getStringWidthFloat (const String& text) const;
  20998. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  20999. An extra x offset is added at the end of the run, to indicate where the right hand
  21000. edge of the last character is.
  21001. */
  21002. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const;
  21003. /** Returns the typeface used by this font.
  21004. Note that the object returned may go out of scope if this font is deleted
  21005. or has its style changed.
  21006. */
  21007. Typeface* getTypeface() const;
  21008. /** Creates an array of Font objects to represent all the fonts on the system.
  21009. If you just need the names of the typefaces, you can also use
  21010. findAllTypefaceNames() instead.
  21011. @param results the array to which new Font objects will be added.
  21012. */
  21013. static void findFonts (Array<Font>& results);
  21014. /** Returns a list of all the available typeface names.
  21015. The names returned can be passed into setTypefaceName().
  21016. You can use this instead of findFonts() if you only need their names, and not
  21017. font objects.
  21018. */
  21019. static const StringArray findAllTypefaceNames();
  21020. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  21021. in the requested typeface.
  21022. */
  21023. static const String getFallbackFontName();
  21024. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  21025. available in whatever font you're trying to use.
  21026. */
  21027. static void setFallbackFontName (const String& name);
  21028. /** Creates a string to describe this font.
  21029. The string will contain information to describe the font's typeface, size, and
  21030. style. To recreate the font from this string, use fromString().
  21031. */
  21032. const String toString() const;
  21033. /** Recreates a font from its stringified encoding.
  21034. This method takes a string that was created by toString(), and recreates the
  21035. original font.
  21036. */
  21037. static const Font fromString (const String& fontDescription);
  21038. private:
  21039. friend class FontGlyphAlphaMap;
  21040. friend class TypefaceCache;
  21041. class SharedFontInternal : public ReferenceCountedObject
  21042. {
  21043. public:
  21044. SharedFontInternal (float height, int styleFlags) noexcept;
  21045. SharedFontInternal (const String& typefaceName, float height, int styleFlags) noexcept;
  21046. SharedFontInternal (const Typeface::Ptr& typeface) noexcept;
  21047. SharedFontInternal (const SharedFontInternal& other) noexcept;
  21048. bool operator== (const SharedFontInternal&) const noexcept;
  21049. String typefaceName;
  21050. float height, horizontalScale, kerning, ascent;
  21051. int styleFlags;
  21052. Typeface::Ptr typeface;
  21053. };
  21054. ReferenceCountedObjectPtr <SharedFontInternal> font;
  21055. void dupeInternalIfShared();
  21056. JUCE_LEAK_DETECTOR (Font);
  21057. };
  21058. #endif // __JUCE_FONT_JUCEHEADER__
  21059. /*** End of inlined file: juce_Font.h ***/
  21060. /*** Start of inlined file: juce_PathStrokeType.h ***/
  21061. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  21062. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  21063. /**
  21064. Describes a type of stroke used to render a solid outline along a path.
  21065. A PathStrokeType object can be used directly to create the shape of an outline
  21066. around a path, and is used by Graphics::strokePath to specify the type of
  21067. stroke to draw.
  21068. @see Path, Graphics::strokePath
  21069. */
  21070. class JUCE_API PathStrokeType
  21071. {
  21072. public:
  21073. /** The type of shape to use for the corners between two adjacent line segments. */
  21074. enum JointStyle
  21075. {
  21076. mitered, /**< Indicates that corners should be drawn with sharp joints.
  21077. Note that for angles that curve back on themselves, drawing a
  21078. mitre could require extending the point too far away from the
  21079. path, so a mitre limit is imposed and any corners that exceed it
  21080. are drawn as bevelled instead. */
  21081. curved, /**< Indicates that corners should be drawn as rounded-off. */
  21082. beveled /**< Indicates that corners should be drawn with a line flattening their
  21083. outside edge. */
  21084. };
  21085. /** The type shape to use for the ends of lines. */
  21086. enum EndCapStyle
  21087. {
  21088. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  21089. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  21090. the thickness of the stroke. */
  21091. rounded /**< Ends of lines are rounded-off with a circular shape. */
  21092. };
  21093. /** Creates a stroke type.
  21094. @param strokeThickness the width of the line to use
  21095. @param jointStyle the type of joints to use for corners
  21096. @param endStyle the type of end-caps to use for the ends of open paths.
  21097. */
  21098. PathStrokeType (float strokeThickness,
  21099. JointStyle jointStyle = mitered,
  21100. EndCapStyle endStyle = butt) noexcept;
  21101. /** Createes a copy of another stroke type. */
  21102. PathStrokeType (const PathStrokeType& other) noexcept;
  21103. /** Copies another stroke onto this one. */
  21104. PathStrokeType& operator= (const PathStrokeType& other) noexcept;
  21105. /** Destructor. */
  21106. ~PathStrokeType() noexcept;
  21107. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  21108. @param destPath the resultant stroked outline shape will be copied into this path.
  21109. Note that it's ok for the source and destination Paths to be
  21110. the same object, so you can easily turn a path into a stroked version
  21111. of itself.
  21112. @param sourcePath the path to use as the source
  21113. @param transform an optional transform to apply to the points from the source path
  21114. as they are being used
  21115. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21116. a higher resolution, which improves the quality if you'll later want
  21117. to enlarge the stroked path. So for example, if you're planning on drawing
  21118. the stroke at 3x the size that you're creating it, you should set this to 3.
  21119. @see createDashedStroke
  21120. */
  21121. void createStrokedPath (Path& destPath,
  21122. const Path& sourcePath,
  21123. const AffineTransform& transform = AffineTransform::identity,
  21124. float extraAccuracy = 1.0f) const;
  21125. /** Applies this stroke type to a path, creating a dashed line.
  21126. This is similar to createStrokedPath, but uses the array passed in to
  21127. break the stroke up into a series of dashes.
  21128. @param destPath the resultant stroked outline shape will be copied into this path.
  21129. Note that it's ok for the source and destination Paths to be
  21130. the same object, so you can easily turn a path into a stroked version
  21131. of itself.
  21132. @param sourcePath the path to use as the source
  21133. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  21134. a line of length 2, then skip a length of 3, then add a line of length 4,
  21135. skip 5, and keep repeating this pattern.
  21136. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  21137. an even number, otherwise the pattern will get out of step as it
  21138. repeats.
  21139. @param transform an optional transform to apply to the points from the source path
  21140. as they are being used
  21141. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21142. a higher resolution, which improves the quality if you'll later want
  21143. to enlarge the stroked path. So for example, if you're planning on drawing
  21144. the stroke at 3x the size that you're creating it, you should set this to 3.
  21145. */
  21146. void createDashedStroke (Path& destPath,
  21147. const Path& sourcePath,
  21148. const float* dashLengths,
  21149. int numDashLengths,
  21150. const AffineTransform& transform = AffineTransform::identity,
  21151. float extraAccuracy = 1.0f) const;
  21152. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  21153. @param destPath the resultant stroked outline shape will be copied into this path.
  21154. Note that it's ok for the source and destination Paths to be
  21155. the same object, so you can easily turn a path into a stroked version
  21156. of itself.
  21157. @param sourcePath the path to use as the source
  21158. @param arrowheadStartWidth the width of the arrowhead at the start of the path
  21159. @param arrowheadStartLength the length of the arrowhead at the start of the path
  21160. @param arrowheadEndWidth the width of the arrowhead at the end of the path
  21161. @param arrowheadEndLength the length of the arrowhead at the end of the path
  21162. @param transform an optional transform to apply to the points from the source path
  21163. as they are being used
  21164. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21165. a higher resolution, which improves the quality if you'll later want
  21166. to enlarge the stroked path. So for example, if you're planning on drawing
  21167. the stroke at 3x the size that you're creating it, you should set this to 3.
  21168. @see createDashedStroke
  21169. */
  21170. void createStrokeWithArrowheads (Path& destPath,
  21171. const Path& sourcePath,
  21172. float arrowheadStartWidth, float arrowheadStartLength,
  21173. float arrowheadEndWidth, float arrowheadEndLength,
  21174. const AffineTransform& transform = AffineTransform::identity,
  21175. float extraAccuracy = 1.0f) const;
  21176. /** Returns the stroke thickness. */
  21177. float getStrokeThickness() const noexcept { return thickness; }
  21178. /** Sets the stroke thickness. */
  21179. void setStrokeThickness (float newThickness) noexcept { thickness = newThickness; }
  21180. /** Returns the joint style. */
  21181. JointStyle getJointStyle() const noexcept { return jointStyle; }
  21182. /** Sets the joint style. */
  21183. void setJointStyle (JointStyle newStyle) noexcept { jointStyle = newStyle; }
  21184. /** Returns the end-cap style. */
  21185. EndCapStyle getEndStyle() const noexcept { return endStyle; }
  21186. /** Sets the end-cap style. */
  21187. void setEndStyle (EndCapStyle newStyle) noexcept { endStyle = newStyle; }
  21188. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  21189. bool operator== (const PathStrokeType& other) const noexcept;
  21190. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  21191. bool operator!= (const PathStrokeType& other) const noexcept;
  21192. private:
  21193. float thickness;
  21194. JointStyle jointStyle;
  21195. EndCapStyle endStyle;
  21196. JUCE_LEAK_DETECTOR (PathStrokeType);
  21197. };
  21198. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  21199. /*** End of inlined file: juce_PathStrokeType.h ***/
  21200. /*** Start of inlined file: juce_Colours.h ***/
  21201. #ifndef __JUCE_COLOURS_JUCEHEADER__
  21202. #define __JUCE_COLOURS_JUCEHEADER__
  21203. /*** Start of inlined file: juce_Colour.h ***/
  21204. #ifndef __JUCE_COLOUR_JUCEHEADER__
  21205. #define __JUCE_COLOUR_JUCEHEADER__
  21206. /*** Start of inlined file: juce_PixelFormats.h ***/
  21207. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  21208. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  21209. #ifndef DOXYGEN
  21210. #if JUCE_MSVC
  21211. #pragma pack (push, 1)
  21212. #define PACKED
  21213. #elif JUCE_GCC
  21214. #define PACKED __attribute__((packed))
  21215. #else
  21216. #define PACKED
  21217. #endif
  21218. #endif
  21219. class PixelRGB;
  21220. class PixelAlpha;
  21221. /**
  21222. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  21223. operations with it.
  21224. This is used internally by the imaging classes.
  21225. @see PixelRGB
  21226. */
  21227. class JUCE_API PixelARGB
  21228. {
  21229. public:
  21230. /** Creates a pixel without defining its colour. */
  21231. PixelARGB() noexcept {}
  21232. ~PixelARGB() noexcept {}
  21233. /** Creates a pixel from a 32-bit argb value.
  21234. */
  21235. PixelARGB (const uint32 argb_) noexcept
  21236. : argb (argb_)
  21237. {
  21238. }
  21239. forcedinline uint32 getARGB() const noexcept { return argb; }
  21240. forcedinline uint32 getUnpremultipliedARGB() const noexcept { PixelARGB p (argb); p.unpremultiply(); return p.getARGB(); }
  21241. forcedinline uint32 getRB() const noexcept { return 0x00ff00ff & argb; }
  21242. forcedinline uint32 getAG() const noexcept { return 0x00ff00ff & (argb >> 8); }
  21243. forcedinline uint8 getAlpha() const noexcept { return components.a; }
  21244. forcedinline uint8 getRed() const noexcept { return components.r; }
  21245. forcedinline uint8 getGreen() const noexcept { return components.g; }
  21246. forcedinline uint8 getBlue() const noexcept { return components.b; }
  21247. /** Blends another pixel onto this one.
  21248. This takes into account the opacity of the pixel being overlaid, and blends
  21249. it accordingly.
  21250. */
  21251. forcedinline void blend (const PixelARGB& src) noexcept
  21252. {
  21253. uint32 sargb = src.getARGB();
  21254. const uint32 alpha = 0x100 - (sargb >> 24);
  21255. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21256. sargb += 0xff00ff00 & (getAG() * alpha);
  21257. argb = sargb;
  21258. }
  21259. /** Blends another pixel onto this one.
  21260. This takes into account the opacity of the pixel being overlaid, and blends
  21261. it accordingly.
  21262. */
  21263. forcedinline void blend (const PixelAlpha& src) noexcept;
  21264. /** Blends another pixel onto this one.
  21265. This takes into account the opacity of the pixel being overlaid, and blends
  21266. it accordingly.
  21267. */
  21268. forcedinline void blend (const PixelRGB& src) noexcept;
  21269. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21270. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21271. being used, so this can blend semi-transparently from a PixelRGB argument.
  21272. */
  21273. template <class Pixel>
  21274. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21275. {
  21276. ++extraAlpha;
  21277. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  21278. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  21279. const uint32 alpha = 0x100 - (sargb >> 24);
  21280. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21281. sargb += 0xff00ff00 & (getAG() * alpha);
  21282. argb = sargb;
  21283. }
  21284. /** Blends another pixel with this one, creating a colour that is somewhere
  21285. between the two, as specified by the amount.
  21286. */
  21287. template <class Pixel>
  21288. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21289. {
  21290. uint32 drb = getRB();
  21291. drb += (((src.getRB() - drb) * amount) >> 8);
  21292. drb &= 0x00ff00ff;
  21293. uint32 dag = getAG();
  21294. dag += (((src.getAG() - dag) * amount) >> 8);
  21295. dag &= 0x00ff00ff;
  21296. dag <<= 8;
  21297. dag |= drb;
  21298. argb = dag;
  21299. }
  21300. /** Copies another pixel colour over this one.
  21301. This doesn't blend it - this colour is simply replaced by the other one.
  21302. */
  21303. template <class Pixel>
  21304. forcedinline void set (const Pixel& src) noexcept
  21305. {
  21306. argb = src.getARGB();
  21307. }
  21308. /** Replaces the colour's alpha value with another one. */
  21309. forcedinline void setAlpha (const uint8 newAlpha) noexcept
  21310. {
  21311. components.a = newAlpha;
  21312. }
  21313. /** Multiplies the colour's alpha value with another one. */
  21314. forcedinline void multiplyAlpha (int multiplier) noexcept
  21315. {
  21316. ++multiplier;
  21317. argb = ((multiplier * getAG()) & 0xff00ff00)
  21318. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  21319. }
  21320. forcedinline void multiplyAlpha (const float multiplier) noexcept
  21321. {
  21322. multiplyAlpha ((int) (multiplier * 256.0f));
  21323. }
  21324. /** Sets the pixel's colour from individual components. */
  21325. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) noexcept
  21326. {
  21327. components.b = b;
  21328. components.g = g;
  21329. components.r = r;
  21330. components.a = a;
  21331. }
  21332. /** Premultiplies the pixel's RGB values by its alpha. */
  21333. forcedinline void premultiply() noexcept
  21334. {
  21335. const uint32 alpha = components.a;
  21336. if (alpha < 0xff)
  21337. {
  21338. if (alpha == 0)
  21339. {
  21340. components.b = 0;
  21341. components.g = 0;
  21342. components.r = 0;
  21343. }
  21344. else
  21345. {
  21346. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  21347. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  21348. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  21349. }
  21350. }
  21351. }
  21352. /** Unpremultiplies the pixel's RGB values. */
  21353. forcedinline void unpremultiply() noexcept
  21354. {
  21355. const uint32 alpha = components.a;
  21356. if (alpha < 0xff)
  21357. {
  21358. if (alpha == 0)
  21359. {
  21360. components.b = 0;
  21361. components.g = 0;
  21362. components.r = 0;
  21363. }
  21364. else
  21365. {
  21366. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  21367. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  21368. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  21369. }
  21370. }
  21371. }
  21372. forcedinline void desaturate() noexcept
  21373. {
  21374. if (components.a < 0xff && components.a > 0)
  21375. {
  21376. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  21377. components.r = components.g = components.b
  21378. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  21379. }
  21380. else
  21381. {
  21382. components.r = components.g = components.b
  21383. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  21384. }
  21385. }
  21386. /** The indexes of the different components in the byte layout of this type of colour. */
  21387. #if JUCE_BIG_ENDIAN
  21388. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  21389. #else
  21390. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  21391. #endif
  21392. private:
  21393. union
  21394. {
  21395. uint32 argb;
  21396. struct
  21397. {
  21398. #if JUCE_BIG_ENDIAN
  21399. uint8 a : 8, r : 8, g : 8, b : 8;
  21400. #else
  21401. uint8 b, g, r, a;
  21402. #endif
  21403. } PACKED components;
  21404. };
  21405. }
  21406. #ifndef DOXYGEN
  21407. PACKED
  21408. #endif
  21409. ;
  21410. /**
  21411. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  21412. This is used internally by the imaging classes.
  21413. @see PixelARGB
  21414. */
  21415. class JUCE_API PixelRGB
  21416. {
  21417. public:
  21418. /** Creates a pixel without defining its colour. */
  21419. PixelRGB() noexcept {}
  21420. ~PixelRGB() noexcept {}
  21421. /** Creates a pixel from a 32-bit argb value.
  21422. (The argb format is that used by PixelARGB)
  21423. */
  21424. PixelRGB (const uint32 argb) noexcept
  21425. {
  21426. r = (uint8) (argb >> 16);
  21427. g = (uint8) (argb >> 8);
  21428. b = (uint8) (argb);
  21429. }
  21430. forcedinline uint32 getARGB() const noexcept { return 0xff000000 | b | (g << 8) | (r << 16); }
  21431. forcedinline uint32 getUnpremultipliedARGB() const noexcept { return getARGB(); }
  21432. forcedinline uint32 getRB() const noexcept { return b | (uint32) (r << 16); }
  21433. forcedinline uint32 getAG() const noexcept { return 0xff0000 | g; }
  21434. forcedinline uint8 getAlpha() const noexcept { return 0xff; }
  21435. forcedinline uint8 getRed() const noexcept { return r; }
  21436. forcedinline uint8 getGreen() const noexcept { return g; }
  21437. forcedinline uint8 getBlue() const noexcept { return b; }
  21438. /** Blends another pixel onto this one.
  21439. This takes into account the opacity of the pixel being overlaid, and blends
  21440. it accordingly.
  21441. */
  21442. forcedinline void blend (const PixelARGB& src) noexcept
  21443. {
  21444. uint32 sargb = src.getARGB();
  21445. const uint32 alpha = 0x100 - (sargb >> 24);
  21446. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21447. sargb += 0x0000ff00 & (g * alpha);
  21448. r = (uint8) (sargb >> 16);
  21449. g = (uint8) (sargb >> 8);
  21450. b = (uint8) sargb;
  21451. }
  21452. forcedinline void blend (const PixelRGB& src) noexcept
  21453. {
  21454. set (src);
  21455. }
  21456. forcedinline void blend (const PixelAlpha& src) noexcept;
  21457. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21458. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21459. being used, so this can blend semi-transparently from a PixelRGB argument.
  21460. */
  21461. template <class Pixel>
  21462. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21463. {
  21464. ++extraAlpha;
  21465. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  21466. const uint32 sag = extraAlpha * src.getAG();
  21467. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  21468. const uint32 alpha = 0x100 - (sargb >> 24);
  21469. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21470. sargb += 0x0000ff00 & (g * alpha);
  21471. b = (uint8) sargb;
  21472. g = (uint8) (sargb >> 8);
  21473. r = (uint8) (sargb >> 16);
  21474. }
  21475. /** Blends another pixel with this one, creating a colour that is somewhere
  21476. between the two, as specified by the amount.
  21477. */
  21478. template <class Pixel>
  21479. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21480. {
  21481. uint32 drb = getRB();
  21482. drb += (((src.getRB() - drb) * amount) >> 8);
  21483. uint32 dag = getAG();
  21484. dag += (((src.getAG() - dag) * amount) >> 8);
  21485. b = (uint8) drb;
  21486. g = (uint8) dag;
  21487. r = (uint8) (drb >> 16);
  21488. }
  21489. /** Copies another pixel colour over this one.
  21490. This doesn't blend it - this colour is simply replaced by the other one.
  21491. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  21492. is thrown away.
  21493. */
  21494. template <class Pixel>
  21495. forcedinline void set (const Pixel& src) noexcept
  21496. {
  21497. b = src.getBlue();
  21498. g = src.getGreen();
  21499. r = src.getRed();
  21500. }
  21501. /** This method is included for compatibility with the PixelARGB class. */
  21502. forcedinline void setAlpha (const uint8) noexcept {}
  21503. /** Multiplies the colour's alpha value with another one. */
  21504. forcedinline void multiplyAlpha (int) noexcept {}
  21505. /** Sets the pixel's colour from individual components. */
  21506. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) noexcept
  21507. {
  21508. r = r_;
  21509. g = g_;
  21510. b = b_;
  21511. }
  21512. /** Premultiplies the pixel's RGB values by its alpha. */
  21513. forcedinline void premultiply() noexcept {}
  21514. /** Unpremultiplies the pixel's RGB values. */
  21515. forcedinline void unpremultiply() noexcept {}
  21516. forcedinline void desaturate() noexcept
  21517. {
  21518. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  21519. }
  21520. /** The indexes of the different components in the byte layout of this type of colour. */
  21521. #if JUCE_MAC
  21522. enum { indexR = 0, indexG = 1, indexB = 2 };
  21523. #else
  21524. enum { indexR = 2, indexG = 1, indexB = 0 };
  21525. #endif
  21526. private:
  21527. #if JUCE_MAC
  21528. uint8 r, g, b;
  21529. #else
  21530. uint8 b, g, r;
  21531. #endif
  21532. }
  21533. #ifndef DOXYGEN
  21534. PACKED
  21535. #endif
  21536. ;
  21537. forcedinline void PixelARGB::blend (const PixelRGB& src) noexcept
  21538. {
  21539. set (src);
  21540. }
  21541. /**
  21542. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  21543. This is used internally by the imaging classes.
  21544. @see PixelARGB, PixelRGB
  21545. */
  21546. class JUCE_API PixelAlpha
  21547. {
  21548. public:
  21549. /** Creates a pixel without defining its colour. */
  21550. PixelAlpha() noexcept {}
  21551. ~PixelAlpha() noexcept {}
  21552. /** Creates a pixel from a 32-bit argb value.
  21553. (The argb format is that used by PixelARGB)
  21554. */
  21555. PixelAlpha (const uint32 argb) noexcept
  21556. {
  21557. a = (uint8) (argb >> 24);
  21558. }
  21559. forcedinline uint32 getARGB() const noexcept { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  21560. forcedinline uint32 getUnpremultipliedARGB() const noexcept { return (((uint32) a) << 24) | 0xffffff; }
  21561. forcedinline uint32 getRB() const noexcept { return (((uint32) a) << 16) | a; }
  21562. forcedinline uint32 getAG() const noexcept { return (((uint32) a) << 16) | a; }
  21563. forcedinline uint8 getAlpha() const noexcept { return a; }
  21564. forcedinline uint8 getRed() const noexcept { return 0; }
  21565. forcedinline uint8 getGreen() const noexcept { return 0; }
  21566. forcedinline uint8 getBlue() const noexcept { return 0; }
  21567. /** Blends another pixel onto this one.
  21568. This takes into account the opacity of the pixel being overlaid, and blends
  21569. it accordingly.
  21570. */
  21571. template <class Pixel>
  21572. forcedinline void blend (const Pixel& src) noexcept
  21573. {
  21574. const int srcA = src.getAlpha();
  21575. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  21576. }
  21577. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21578. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21579. being used, so this can blend semi-transparently from a PixelRGB argument.
  21580. */
  21581. template <class Pixel>
  21582. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21583. {
  21584. ++extraAlpha;
  21585. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  21586. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  21587. }
  21588. /** Blends another pixel with this one, creating a colour that is somewhere
  21589. between the two, as specified by the amount.
  21590. */
  21591. template <class Pixel>
  21592. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21593. {
  21594. a += ((src,getAlpha() - a) * amount) >> 8;
  21595. }
  21596. /** Copies another pixel colour over this one.
  21597. This doesn't blend it - this colour is simply replaced by the other one.
  21598. */
  21599. template <class Pixel>
  21600. forcedinline void set (const Pixel& src) noexcept
  21601. {
  21602. a = src.getAlpha();
  21603. }
  21604. /** Replaces the colour's alpha value with another one. */
  21605. forcedinline void setAlpha (const uint8 newAlpha) noexcept
  21606. {
  21607. a = newAlpha;
  21608. }
  21609. /** Multiplies the colour's alpha value with another one. */
  21610. forcedinline void multiplyAlpha (int multiplier) noexcept
  21611. {
  21612. ++multiplier;
  21613. a = (uint8) ((a * multiplier) >> 8);
  21614. }
  21615. forcedinline void multiplyAlpha (const float multiplier) noexcept
  21616. {
  21617. a = (uint8) (a * multiplier);
  21618. }
  21619. /** Sets the pixel's colour from individual components. */
  21620. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) noexcept
  21621. {
  21622. a = a_;
  21623. }
  21624. /** Premultiplies the pixel's RGB values by its alpha. */
  21625. forcedinline void premultiply() noexcept
  21626. {
  21627. }
  21628. /** Unpremultiplies the pixel's RGB values. */
  21629. forcedinline void unpremultiply() noexcept
  21630. {
  21631. }
  21632. forcedinline void desaturate() noexcept
  21633. {
  21634. }
  21635. /** The indexes of the different components in the byte layout of this type of colour. */
  21636. enum { indexA = 0 };
  21637. private:
  21638. uint8 a : 8;
  21639. }
  21640. #ifndef DOXYGEN
  21641. PACKED
  21642. #endif
  21643. ;
  21644. forcedinline void PixelRGB::blend (const PixelAlpha& src) noexcept
  21645. {
  21646. blend (PixelARGB (src.getARGB()));
  21647. }
  21648. forcedinline void PixelARGB::blend (const PixelAlpha& src) noexcept
  21649. {
  21650. uint32 sargb = src.getARGB();
  21651. const uint32 alpha = 0x100 - (sargb >> 24);
  21652. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21653. sargb += 0xff00ff00 & (getAG() * alpha);
  21654. argb = sargb;
  21655. }
  21656. #if JUCE_MSVC
  21657. #pragma pack (pop)
  21658. #endif
  21659. #undef PACKED
  21660. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  21661. /*** End of inlined file: juce_PixelFormats.h ***/
  21662. /**
  21663. Represents a colour, also including a transparency value.
  21664. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  21665. */
  21666. class JUCE_API Colour
  21667. {
  21668. public:
  21669. /** Creates a transparent black colour. */
  21670. Colour() noexcept;
  21671. /** Creates a copy of another Colour object. */
  21672. Colour (const Colour& other) noexcept;
  21673. /** Creates a colour from a 32-bit ARGB value.
  21674. The format of this number is:
  21675. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  21676. All components in the range 0x00 to 0xff.
  21677. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21678. @see getPixelARGB
  21679. */
  21680. explicit Colour (uint32 argb) noexcept;
  21681. /** Creates an opaque colour using 8-bit red, green and blue values */
  21682. Colour (uint8 red,
  21683. uint8 green,
  21684. uint8 blue) noexcept;
  21685. /** Creates an opaque colour using 8-bit red, green and blue values */
  21686. static const Colour fromRGB (uint8 red,
  21687. uint8 green,
  21688. uint8 blue) noexcept;
  21689. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21690. Colour (uint8 red,
  21691. uint8 green,
  21692. uint8 blue,
  21693. uint8 alpha) noexcept;
  21694. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21695. static const Colour fromRGBA (uint8 red,
  21696. uint8 green,
  21697. uint8 blue,
  21698. uint8 alpha) noexcept;
  21699. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  21700. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  21701. Values outside the valid range will be clipped.
  21702. */
  21703. Colour (uint8 red,
  21704. uint8 green,
  21705. uint8 blue,
  21706. float alpha) noexcept;
  21707. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  21708. static const Colour fromRGBAFloat (uint8 red,
  21709. uint8 green,
  21710. uint8 blue,
  21711. float alpha) noexcept;
  21712. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21713. The floating point values must be between 0.0 and 1.0.
  21714. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21715. Values outside the valid range will be clipped.
  21716. */
  21717. Colour (float hue,
  21718. float saturation,
  21719. float brightness,
  21720. uint8 alpha) noexcept;
  21721. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  21722. All values must be between 0.0 and 1.0.
  21723. Numbers outside the valid range will be clipped.
  21724. */
  21725. Colour (float hue,
  21726. float saturation,
  21727. float brightness,
  21728. float alpha) noexcept;
  21729. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21730. The floating point values must be between 0.0 and 1.0.
  21731. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21732. Values outside the valid range will be clipped.
  21733. */
  21734. static const Colour fromHSV (float hue,
  21735. float saturation,
  21736. float brightness,
  21737. float alpha) noexcept;
  21738. /** Destructor. */
  21739. ~Colour() noexcept;
  21740. /** Copies another Colour object. */
  21741. Colour& operator= (const Colour& other) noexcept;
  21742. /** Compares two colours. */
  21743. bool operator== (const Colour& other) const noexcept;
  21744. /** Compares two colours. */
  21745. bool operator!= (const Colour& other) const noexcept;
  21746. /** Returns the red component of this colour.
  21747. @returns a value between 0x00 and 0xff.
  21748. */
  21749. uint8 getRed() const noexcept { return argb.getRed(); }
  21750. /** Returns the green component of this colour.
  21751. @returns a value between 0x00 and 0xff.
  21752. */
  21753. uint8 getGreen() const noexcept { return argb.getGreen(); }
  21754. /** Returns the blue component of this colour.
  21755. @returns a value between 0x00 and 0xff.
  21756. */
  21757. uint8 getBlue() const noexcept { return argb.getBlue(); }
  21758. /** Returns the red component of this colour as a floating point value.
  21759. @returns a value between 0.0 and 1.0
  21760. */
  21761. float getFloatRed() const noexcept;
  21762. /** Returns the green component of this colour as a floating point value.
  21763. @returns a value between 0.0 and 1.0
  21764. */
  21765. float getFloatGreen() const noexcept;
  21766. /** Returns the blue component of this colour as a floating point value.
  21767. @returns a value between 0.0 and 1.0
  21768. */
  21769. float getFloatBlue() const noexcept;
  21770. /** Returns a premultiplied ARGB pixel object that represents this colour.
  21771. */
  21772. const PixelARGB getPixelARGB() const noexcept;
  21773. /** Returns a 32-bit integer that represents this colour.
  21774. The format of this number is:
  21775. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  21776. */
  21777. uint32 getARGB() const noexcept;
  21778. /** Returns the colour's alpha (opacity).
  21779. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  21780. */
  21781. uint8 getAlpha() const noexcept { return argb.getAlpha(); }
  21782. /** Returns the colour's alpha (opacity) as a floating point value.
  21783. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  21784. */
  21785. float getFloatAlpha() const noexcept;
  21786. /** Returns true if this colour is completely opaque.
  21787. Equivalent to (getAlpha() == 0xff).
  21788. */
  21789. bool isOpaque() const noexcept;
  21790. /** Returns true if this colour is completely transparent.
  21791. Equivalent to (getAlpha() == 0x00).
  21792. */
  21793. bool isTransparent() const noexcept;
  21794. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21795. const Colour withAlpha (uint8 newAlpha) const noexcept;
  21796. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21797. const Colour withAlpha (float newAlpha) const noexcept;
  21798. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  21799. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  21800. */
  21801. const Colour withMultipliedAlpha (float alphaMultiplier) const noexcept;
  21802. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  21803. If the foreground colour is semi-transparent, it is blended onto this colour
  21804. accordingly.
  21805. */
  21806. const Colour overlaidWith (const Colour& foregroundColour) const noexcept;
  21807. /** Returns a colour that lies somewhere between this one and another.
  21808. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  21809. is 1.0, the result is 100% of the other colour.
  21810. */
  21811. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const noexcept;
  21812. /** Returns the colour's hue component.
  21813. The value returned is in the range 0.0 to 1.0
  21814. */
  21815. float getHue() const noexcept;
  21816. /** Returns the colour's saturation component.
  21817. The value returned is in the range 0.0 to 1.0
  21818. */
  21819. float getSaturation() const noexcept;
  21820. /** Returns the colour's brightness component.
  21821. The value returned is in the range 0.0 to 1.0
  21822. */
  21823. float getBrightness() const noexcept;
  21824. /** Returns the colour's hue, saturation and brightness components all at once.
  21825. The values returned are in the range 0.0 to 1.0
  21826. */
  21827. void getHSB (float& hue,
  21828. float& saturation,
  21829. float& brightness) const noexcept;
  21830. /** Returns a copy of this colour with a different hue. */
  21831. const Colour withHue (float newHue) const noexcept;
  21832. /** Returns a copy of this colour with a different saturation. */
  21833. const Colour withSaturation (float newSaturation) const noexcept;
  21834. /** Returns a copy of this colour with a different brightness.
  21835. @see brighter, darker, withMultipliedBrightness
  21836. */
  21837. const Colour withBrightness (float newBrightness) const noexcept;
  21838. /** Returns a copy of this colour with it hue rotated.
  21839. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  21840. @see brighter, darker, withMultipliedBrightness
  21841. */
  21842. const Colour withRotatedHue (float amountToRotate) const noexcept;
  21843. /** Returns a copy of this colour with its saturation multiplied by the given value.
  21844. The new colour's saturation is (this->getSaturation() * multiplier)
  21845. (the result is clipped to legal limits).
  21846. */
  21847. const Colour withMultipliedSaturation (float multiplier) const noexcept;
  21848. /** Returns a copy of this colour with its brightness multiplied by the given value.
  21849. The new colour's saturation is (this->getBrightness() * multiplier)
  21850. (the result is clipped to legal limits).
  21851. */
  21852. const Colour withMultipliedBrightness (float amount) const noexcept;
  21853. /** Returns a brighter version of this colour.
  21854. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  21855. unchanged, and higher values make it brighter
  21856. @see withMultipliedBrightness
  21857. */
  21858. const Colour brighter (float amountBrighter = 0.4f) const noexcept;
  21859. /** Returns a darker version of this colour.
  21860. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  21861. unchanged, and higher values make it darker
  21862. @see withMultipliedBrightness
  21863. */
  21864. const Colour darker (float amountDarker = 0.4f) const noexcept;
  21865. /** Returns a colour that will be clearly visible against this colour.
  21866. The amount parameter indicates how contrasting the new colour should
  21867. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  21868. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  21869. return white; Colours::white.contrasting (1.0f) will return black, etc.
  21870. */
  21871. const Colour contrasting (float amount = 1.0f) const noexcept;
  21872. /** Returns a colour that contrasts against two colours.
  21873. Looks for a colour that contrasts with both of the colours passed-in.
  21874. Handy for things like choosing a highlight colour in text editors, etc.
  21875. */
  21876. static const Colour contrasting (const Colour& colour1,
  21877. const Colour& colour2) noexcept;
  21878. /** Returns an opaque shade of grey.
  21879. @param brightness the level of grey to return - 0 is black, 1.0 is white
  21880. */
  21881. static const Colour greyLevel (float brightness) noexcept;
  21882. /** Returns a stringified version of this colour.
  21883. The string can be turned back into a colour using the fromString() method.
  21884. */
  21885. const String toString() const;
  21886. /** Reads the colour from a string that was created with toString().
  21887. */
  21888. static const Colour fromString (const String& encodedColourString);
  21889. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  21890. const String toDisplayString (bool includeAlphaValue) const;
  21891. private:
  21892. PixelARGB argb;
  21893. };
  21894. #endif // __JUCE_COLOUR_JUCEHEADER__
  21895. /*** End of inlined file: juce_Colour.h ***/
  21896. /**
  21897. Contains a set of predefined named colours (mostly standard HTML colours)
  21898. @see Colour, Colours::greyLevel
  21899. */
  21900. class Colours
  21901. {
  21902. public:
  21903. static JUCE_API const Colour
  21904. transparentBlack, /**< ARGB = 0x00000000 */
  21905. transparentWhite, /**< ARGB = 0x00ffffff */
  21906. black, /**< ARGB = 0xff000000 */
  21907. white, /**< ARGB = 0xffffffff */
  21908. blue, /**< ARGB = 0xff0000ff */
  21909. grey, /**< ARGB = 0xff808080 */
  21910. green, /**< ARGB = 0xff008000 */
  21911. red, /**< ARGB = 0xffff0000 */
  21912. yellow, /**< ARGB = 0xffffff00 */
  21913. aliceblue, antiquewhite, aqua, aquamarine,
  21914. azure, beige, bisque, blanchedalmond,
  21915. blueviolet, brown, burlywood, cadetblue,
  21916. chartreuse, chocolate, coral, cornflowerblue,
  21917. cornsilk, crimson, cyan, darkblue,
  21918. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  21919. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  21920. darkorchid, darkred, darksalmon, darkseagreen,
  21921. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  21922. deeppink, deepskyblue, dimgrey, dodgerblue,
  21923. firebrick, floralwhite, forestgreen, fuchsia,
  21924. gainsboro, gold, goldenrod, greenyellow,
  21925. honeydew, hotpink, indianred, indigo,
  21926. ivory, khaki, lavender, lavenderblush,
  21927. lemonchiffon, lightblue, lightcoral, lightcyan,
  21928. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  21929. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  21930. lightsteelblue, lightyellow, lime, limegreen,
  21931. linen, magenta, maroon, mediumaquamarine,
  21932. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  21933. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  21934. midnightblue, mintcream, mistyrose, navajowhite,
  21935. navy, oldlace, olive, olivedrab,
  21936. orange, orangered, orchid, palegoldenrod,
  21937. palegreen, paleturquoise, palevioletred, papayawhip,
  21938. peachpuff, peru, pink, plum,
  21939. powderblue, purple, rosybrown, royalblue,
  21940. saddlebrown, salmon, sandybrown, seagreen,
  21941. seashell, sienna, silver, skyblue,
  21942. slateblue, slategrey, snow, springgreen,
  21943. steelblue, tan, teal, thistle,
  21944. tomato, turquoise, violet, wheat,
  21945. whitesmoke, yellowgreen;
  21946. /** Attempts to look up a string in the list of known colour names, and return
  21947. the appropriate colour.
  21948. A non-case-sensitive search is made of the list of predefined colours, and
  21949. if a match is found, that colour is returned. If no match is found, the
  21950. colour passed in as the defaultColour parameter is returned.
  21951. */
  21952. static JUCE_API const Colour findColourForName (const String& colourName,
  21953. const Colour& defaultColour);
  21954. private:
  21955. // this isn't a class you should ever instantiate - it's just here for the
  21956. // static values in it.
  21957. Colours();
  21958. JUCE_DECLARE_NON_COPYABLE (Colours);
  21959. };
  21960. #endif // __JUCE_COLOURS_JUCEHEADER__
  21961. /*** End of inlined file: juce_Colours.h ***/
  21962. /*** Start of inlined file: juce_ColourGradient.h ***/
  21963. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  21964. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  21965. /**
  21966. Describes the layout and colours that should be used to paint a colour gradient.
  21967. @see Graphics::setGradientFill
  21968. */
  21969. class JUCE_API ColourGradient
  21970. {
  21971. public:
  21972. /** Creates a gradient object.
  21973. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  21974. colour2 should be. In between them there's a gradient.
  21975. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  21976. its centre.
  21977. The alpha transparencies of the colours are used, so note that
  21978. if you blend from transparent to a solid colour, the RGB of the transparent
  21979. colour will become visible in parts of the gradient. e.g. blending
  21980. from Colour::transparentBlack to Colours::white will produce a
  21981. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  21982. will be white all the way across.
  21983. @see ColourGradient
  21984. */
  21985. ColourGradient (const Colour& colour1, float x1, float y1,
  21986. const Colour& colour2, float x2, float y2,
  21987. bool isRadial);
  21988. /** Creates an uninitialised gradient.
  21989. If you use this constructor instead of the other one, be sure to set all the
  21990. object's public member variables before using it!
  21991. */
  21992. ColourGradient() noexcept;
  21993. /** Destructor */
  21994. ~ColourGradient();
  21995. /** Removes any colours that have been added.
  21996. This will also remove any start and end colours, so the gradient won't work. You'll
  21997. need to add more colours with addColour().
  21998. */
  21999. void clearColours();
  22000. /** Adds a colour at a point along the length of the gradient.
  22001. This allows the gradient to go through a spectrum of colours, instead of just a
  22002. start and end colour.
  22003. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  22004. of the distance along the line between the two points
  22005. at which the colour should occur.
  22006. @param colour the colour that should be used at this point
  22007. @returns the index at which the new point was added
  22008. */
  22009. int addColour (double proportionAlongGradient,
  22010. const Colour& colour);
  22011. /** Removes one of the colours from the gradient. */
  22012. void removeColour (int index);
  22013. /** Multiplies the alpha value of all the colours by the given scale factor */
  22014. void multiplyOpacity (float multiplier) noexcept;
  22015. /** Returns the number of colour-stops that have been added. */
  22016. int getNumColours() const noexcept;
  22017. /** Returns the position along the length of the gradient of the colour with this index.
  22018. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  22019. */
  22020. double getColourPosition (int index) const noexcept;
  22021. /** Returns the colour that was added with a given index.
  22022. The index is from 0 to getNumColours() - 1.
  22023. */
  22024. const Colour getColour (int index) const noexcept;
  22025. /** Changes the colour at a given index.
  22026. The index is from 0 to getNumColours() - 1.
  22027. */
  22028. void setColour (int index, const Colour& newColour) noexcept;
  22029. /** Returns the an interpolated colour at any position along the gradient.
  22030. @param position the position along the gradient, between 0 and 1
  22031. */
  22032. const Colour getColourAtPosition (double position) const noexcept;
  22033. /** Creates a set of interpolated premultiplied ARGB values.
  22034. This will resize the HeapBlock, fill it with the colours, and will return the number of
  22035. colours that it added.
  22036. */
  22037. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  22038. /** Returns true if all colours are opaque. */
  22039. bool isOpaque() const noexcept;
  22040. /** Returns true if all colours are completely transparent. */
  22041. bool isInvisible() const noexcept;
  22042. Point<float> point1, point2;
  22043. /** If true, the gradient should be filled circularly, centred around
  22044. point1, with point2 defining a point on the circumference.
  22045. If false, the gradient is linear between the two points.
  22046. */
  22047. bool isRadial;
  22048. bool operator== (const ColourGradient& other) const noexcept;
  22049. bool operator!= (const ColourGradient& other) const noexcept;
  22050. private:
  22051. struct ColourPoint
  22052. {
  22053. ColourPoint() noexcept {}
  22054. ColourPoint (const double position_, const Colour& colour_) noexcept
  22055. : position (position_), colour (colour_)
  22056. {}
  22057. bool operator== (const ColourPoint& other) const noexcept;
  22058. bool operator!= (const ColourPoint& other) const noexcept;
  22059. double position;
  22060. Colour colour;
  22061. };
  22062. Array <ColourPoint> colours;
  22063. JUCE_LEAK_DETECTOR (ColourGradient);
  22064. };
  22065. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  22066. /*** End of inlined file: juce_ColourGradient.h ***/
  22067. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  22068. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  22069. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  22070. /**
  22071. Defines the method used to postion some kind of rectangular object within
  22072. a rectangular viewport.
  22073. Although similar to Justification, this is more specific, and has some extra
  22074. options.
  22075. */
  22076. class JUCE_API RectanglePlacement
  22077. {
  22078. public:
  22079. /** Creates a RectanglePlacement object using a combination of flags. */
  22080. inline RectanglePlacement (int flags_) noexcept : flags (flags_) {}
  22081. /** Creates a copy of another RectanglePlacement object. */
  22082. RectanglePlacement (const RectanglePlacement& other) noexcept;
  22083. /** Copies another RectanglePlacement object. */
  22084. RectanglePlacement& operator= (const RectanglePlacement& other) noexcept;
  22085. bool operator== (const RectanglePlacement& other) const noexcept;
  22086. bool operator!= (const RectanglePlacement& other) const noexcept;
  22087. /** Flag values that can be combined and used in the constructor. */
  22088. enum
  22089. {
  22090. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  22091. xLeft = 1,
  22092. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  22093. xRight = 2,
  22094. /** Indicates that the source should be placed in the centre between the left and right
  22095. sides of the available space. */
  22096. xMid = 4,
  22097. /** Indicates that the source's top edge should be aligned with the top edge of the
  22098. destination rectangle. */
  22099. yTop = 8,
  22100. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  22101. destination rectangle. */
  22102. yBottom = 16,
  22103. /** Indicates that the source should be placed in the centre between the top and bottom
  22104. sides of the available space. */
  22105. yMid = 32,
  22106. /** If this flag is set, then the source rectangle will be resized to completely fill
  22107. the destination rectangle, and all other flags are ignored.
  22108. */
  22109. stretchToFit = 64,
  22110. /** If this flag is set, then the source rectangle will be resized so that it is the
  22111. minimum size to completely fill the destination rectangle, without changing its
  22112. aspect ratio. This means that some of the source rectangle may fall outside
  22113. the destination.
  22114. If this flag is not set, the source will be given the maximum size at which none
  22115. of it falls outside the destination rectangle.
  22116. */
  22117. fillDestination = 128,
  22118. /** Indicates that the source rectangle can be reduced in size if required, but should
  22119. never be made larger than its original size.
  22120. */
  22121. onlyReduceInSize = 256,
  22122. /** Indicates that the source rectangle can be enlarged if required, but should
  22123. never be made smaller than its original size.
  22124. */
  22125. onlyIncreaseInSize = 512,
  22126. /** Indicates that the source rectangle's size should be left unchanged.
  22127. */
  22128. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  22129. /** A shorthand value that is equivalent to (xMid | yMid). */
  22130. centred = 4 + 32
  22131. };
  22132. /** Returns the raw flags that are set for this object. */
  22133. inline int getFlags() const noexcept { return flags; }
  22134. /** Tests a set of flags for this object.
  22135. @returns true if any of the flags passed in are set on this object.
  22136. */
  22137. inline bool testFlags (int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  22138. /** Adjusts the position and size of a rectangle to fit it into a space.
  22139. The source rectangle co-ordinates will be adjusted so that they fit into
  22140. the destination rectangle based on this object's flags.
  22141. */
  22142. void applyTo (double& sourceX,
  22143. double& sourceY,
  22144. double& sourceW,
  22145. double& sourceH,
  22146. double destinationX,
  22147. double destinationY,
  22148. double destinationW,
  22149. double destinationH) const noexcept;
  22150. /** Returns the transform that should be applied to these source co-ordinates to fit them
  22151. into the destination rectangle using the current flags.
  22152. */
  22153. template <typename ValueType>
  22154. const Rectangle<ValueType> appliedTo (const Rectangle<ValueType>& source,
  22155. const Rectangle<ValueType>& destination) const noexcept
  22156. {
  22157. double x = source.getX(), y = source.getY(), w = source.getWidth(), h = source.getHeight();
  22158. applyTo (x, y, w, h, static_cast <double> (destination.getX()), static_cast <double> (destination.getY()),
  22159. static_cast <double> (destination.getWidth()), static_cast <double> (destination.getHeight()));
  22160. return Rectangle<ValueType> (static_cast <ValueType> (x), static_cast <ValueType> (y),
  22161. static_cast <ValueType> (w), static_cast <ValueType> (h));
  22162. }
  22163. /** Returns the transform that should be applied to these source co-ordinates to fit them
  22164. into the destination rectangle using the current flags.
  22165. */
  22166. const AffineTransform getTransformToFit (const Rectangle<float>& source,
  22167. const Rectangle<float>& destination) const noexcept;
  22168. private:
  22169. int flags;
  22170. };
  22171. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  22172. /*** End of inlined file: juce_RectanglePlacement.h ***/
  22173. class LowLevelGraphicsContext;
  22174. class Image;
  22175. class FillType;
  22176. class RectangleList;
  22177. /**
  22178. A graphics context, used for drawing a component or image.
  22179. When a Component needs painting, a Graphics context is passed to its
  22180. Component::paint() method, and this you then call methods within this
  22181. object to actually draw the component's content.
  22182. A Graphics can also be created from an image, to allow drawing directly onto
  22183. that image.
  22184. @see Component::paint
  22185. */
  22186. class JUCE_API Graphics
  22187. {
  22188. public:
  22189. /** Creates a Graphics object to draw directly onto the given image.
  22190. The graphics object that is created will be set up to draw onto the image,
  22191. with the context's clipping area being the entire size of the image, and its
  22192. origin being the image's origin. To draw into a subsection of an image, use the
  22193. reduceClipRegion() and setOrigin() methods.
  22194. Obviously you shouldn't delete the image before this context is deleted.
  22195. */
  22196. explicit Graphics (const Image& imageToDrawOnto);
  22197. /** Destructor. */
  22198. ~Graphics();
  22199. /** Changes the current drawing colour.
  22200. This sets the colour that will now be used for drawing operations - it also
  22201. sets the opacity to that of the colour passed-in.
  22202. If a brush is being used when this method is called, the brush will be deselected,
  22203. and any subsequent drawing will be done with a solid colour brush instead.
  22204. @see setOpacity
  22205. */
  22206. void setColour (const Colour& newColour);
  22207. /** Changes the opacity to use with the current colour.
  22208. If a solid colour is being used for drawing, this changes its opacity
  22209. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  22210. If a gradient is being used, this will have no effect on it.
  22211. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  22212. */
  22213. void setOpacity (float newOpacity);
  22214. /** Sets the context to use a gradient for its fill pattern.
  22215. */
  22216. void setGradientFill (const ColourGradient& gradient);
  22217. /** Sets the context to use a tiled image pattern for filling.
  22218. Make sure that you don't delete this image while it's still being used by
  22219. this context!
  22220. */
  22221. void setTiledImageFill (const Image& imageToUse,
  22222. int anchorX, int anchorY,
  22223. float opacity);
  22224. /** Changes the current fill settings.
  22225. @see setColour, setGradientFill, setTiledImageFill
  22226. */
  22227. void setFillType (const FillType& newFill);
  22228. /** Changes the font to use for subsequent text-drawing functions.
  22229. Note there's also a setFont (float, int) method to quickly change the size and
  22230. style of the current font.
  22231. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  22232. */
  22233. void setFont (const Font& newFont);
  22234. /** Changes the size and style of the currently-selected font.
  22235. This is a convenient shortcut that changes the context's current font to a
  22236. different size or style. The typeface won't be changed.
  22237. @see Font
  22238. */
  22239. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  22240. /** Returns the currently selected font. */
  22241. const Font getCurrentFont() const;
  22242. /** Draws a one-line text string.
  22243. This will use the current colour (or brush) to fill the text. The font is the last
  22244. one specified by setFont().
  22245. @param text the string to draw
  22246. @param startX the position to draw the left-hand edge of the text
  22247. @param baselineY the position of the text's baseline
  22248. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  22249. */
  22250. void drawSingleLineText (const String& text,
  22251. int startX, int baselineY) const;
  22252. /** Draws text across multiple lines.
  22253. This will break the text onto a new line where there's a new-line or
  22254. carriage-return character, or at a word-boundary when the text becomes wider
  22255. than the size specified by the maximumLineWidth parameter.
  22256. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  22257. */
  22258. void drawMultiLineText (const String& text,
  22259. int startX, int baselineY,
  22260. int maximumLineWidth) const;
  22261. /** Renders a string of text as a vector path.
  22262. This allows a string to be transformed with an arbitrary AffineTransform and
  22263. rendered using the current colour/brush. It's much slower than the normal text methods
  22264. but more accurate.
  22265. @see setFont
  22266. */
  22267. void drawTextAsPath (const String& text,
  22268. const AffineTransform& transform) const;
  22269. /** Draws a line of text within a specified rectangle.
  22270. The text will be positioned within the rectangle based on the justification
  22271. flags passed-in. If the string is too long to fit inside the rectangle, it will
  22272. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  22273. flag is true).
  22274. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  22275. */
  22276. void drawText (const String& text,
  22277. int x, int y, int width, int height,
  22278. const Justification& justificationType,
  22279. bool useEllipsesIfTooBig) const;
  22280. /** Tries to draw a text string inside a given space.
  22281. This does its best to make the given text readable within the specified rectangle,
  22282. so it useful for labelling things.
  22283. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  22284. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  22285. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  22286. it's been truncated.
  22287. A Justification parameter lets you specify how the text is laid out within the rectangle,
  22288. both horizontally and vertically.
  22289. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  22290. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  22291. can set this value to 1.0f.
  22292. @see GlyphArrangement::addFittedText
  22293. */
  22294. void drawFittedText (const String& text,
  22295. int x, int y, int width, int height,
  22296. const Justification& justificationFlags,
  22297. int maximumNumberOfLines,
  22298. float minimumHorizontalScale = 0.7f) const;
  22299. /** Fills the context's entire clip region with the current colour or brush.
  22300. (See also the fillAll (const Colour&) method which is a quick way of filling
  22301. it with a given colour).
  22302. */
  22303. void fillAll() const;
  22304. /** Fills the context's entire clip region with a given colour.
  22305. This leaves the context's current colour and brush unchanged, it just
  22306. uses the specified colour temporarily.
  22307. */
  22308. void fillAll (const Colour& colourToUse) const;
  22309. /** Fills a rectangle with the current colour or brush.
  22310. @see drawRect, fillRoundedRectangle
  22311. */
  22312. void fillRect (int x, int y, int width, int height) const;
  22313. /** Fills a rectangle with the current colour or brush. */
  22314. void fillRect (const Rectangle<int>& rectangle) const;
  22315. /** Fills a rectangle with the current colour or brush.
  22316. This uses sub-pixel positioning so is slower than the fillRect method which
  22317. takes integer co-ordinates.
  22318. */
  22319. void fillRect (float x, float y, float width, float height) const;
  22320. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  22321. @see drawRoundedRectangle, Path::addRoundedRectangle
  22322. */
  22323. void fillRoundedRectangle (float x, float y, float width, float height,
  22324. float cornerSize) const;
  22325. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  22326. @see drawRoundedRectangle, Path::addRoundedRectangle
  22327. */
  22328. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  22329. float cornerSize) const;
  22330. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  22331. */
  22332. void fillCheckerBoard (const Rectangle<int>& area,
  22333. int checkWidth, int checkHeight,
  22334. const Colour& colour1, const Colour& colour2) const;
  22335. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22336. The lines are drawn inside the given rectangle, and greater line thicknesses
  22337. extend inwards.
  22338. @see fillRect
  22339. */
  22340. void drawRect (int x, int y, int width, int height,
  22341. int lineThickness = 1) const;
  22342. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22343. The lines are drawn inside the given rectangle, and greater line thicknesses
  22344. extend inwards.
  22345. @see fillRect
  22346. */
  22347. void drawRect (float x, float y, float width, float height,
  22348. float lineThickness = 1.0f) const;
  22349. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22350. The lines are drawn inside the given rectangle, and greater line thicknesses
  22351. extend inwards.
  22352. @see fillRect
  22353. */
  22354. void drawRect (const Rectangle<int>& rectangle,
  22355. int lineThickness = 1) const;
  22356. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  22357. @see fillRoundedRectangle, Path::addRoundedRectangle
  22358. */
  22359. void drawRoundedRectangle (float x, float y, float width, float height,
  22360. float cornerSize, float lineThickness) const;
  22361. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  22362. @see fillRoundedRectangle, Path::addRoundedRectangle
  22363. */
  22364. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  22365. float cornerSize, float lineThickness) const;
  22366. /** Draws a 3D raised (or indented) bevel using two colours.
  22367. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  22368. extend inwards.
  22369. The top-left colour is used for the top- and left-hand edges of the
  22370. bevel; the bottom-right colour is used for the bottom- and right-hand
  22371. edges.
  22372. If useGradient is true, then the bevel fades out to make it look more curved
  22373. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  22374. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  22375. the centre edges are sharp and it fades towards the outside.
  22376. */
  22377. void drawBevel (int x, int y, int width, int height,
  22378. int bevelThickness,
  22379. const Colour& topLeftColour = Colours::white,
  22380. const Colour& bottomRightColour = Colours::black,
  22381. bool useGradient = true,
  22382. bool sharpEdgeOnOutside = true) const;
  22383. /** Draws a pixel using the current colour or brush.
  22384. */
  22385. void setPixel (int x, int y) const;
  22386. /** Fills an ellipse with the current colour or brush.
  22387. The ellipse is drawn to fit inside the given rectangle.
  22388. @see drawEllipse, Path::addEllipse
  22389. */
  22390. void fillEllipse (float x, float y, float width, float height) const;
  22391. /** Draws an elliptical stroke using the current colour or brush.
  22392. @see fillEllipse, Path::addEllipse
  22393. */
  22394. void drawEllipse (float x, float y, float width, float height,
  22395. float lineThickness) const;
  22396. /** Draws a line between two points.
  22397. The line is 1 pixel wide and drawn with the current colour or brush.
  22398. */
  22399. void drawLine (float startX, float startY, float endX, float endY) const;
  22400. /** Draws a line between two points with a given thickness.
  22401. @see Path::addLineSegment
  22402. */
  22403. void drawLine (float startX, float startY, float endX, float endY,
  22404. float lineThickness) const;
  22405. /** Draws a line between two points.
  22406. The line is 1 pixel wide and drawn with the current colour or brush.
  22407. */
  22408. void drawLine (const Line<float>& line) const;
  22409. /** Draws a line between two points with a given thickness.
  22410. @see Path::addLineSegment
  22411. */
  22412. void drawLine (const Line<float>& line, float lineThickness) const;
  22413. /** Draws a dashed line using a custom set of dash-lengths.
  22414. @param line the line to draw
  22415. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  22416. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  22417. draw 6 pixels, skip 7 pixels, and then repeat.
  22418. @param numDashLengths the number of elements in the array (this must be an even number).
  22419. @param lineThickness the thickness of the line to draw
  22420. @param dashIndexToStartFrom the index in the dash-length array to use for the first segment
  22421. @see PathStrokeType::createDashedStroke
  22422. */
  22423. void drawDashedLine (const Line<float>& line,
  22424. const float* dashLengths, int numDashLengths,
  22425. float lineThickness = 1.0f,
  22426. int dashIndexToStartFrom = 0) const;
  22427. /** Draws a vertical line of pixels at a given x position.
  22428. The x position is an integer, but the top and bottom of the line can be sub-pixel
  22429. positions, and these will be anti-aliased if necessary.
  22430. */
  22431. void drawVerticalLine (int x, float top, float bottom) const;
  22432. /** Draws a horizontal line of pixels at a given y position.
  22433. The y position is an integer, but the left and right ends of the line can be sub-pixel
  22434. positions, and these will be anti-aliased if necessary.
  22435. */
  22436. void drawHorizontalLine (int y, float left, float right) const;
  22437. /** Fills a path using the currently selected colour or brush.
  22438. */
  22439. void fillPath (const Path& path,
  22440. const AffineTransform& transform = AffineTransform::identity) const;
  22441. /** Draws a path's outline using the currently selected colour or brush.
  22442. */
  22443. void strokePath (const Path& path,
  22444. const PathStrokeType& strokeType,
  22445. const AffineTransform& transform = AffineTransform::identity) const;
  22446. /** Draws a line with an arrowhead at its end.
  22447. @param line the line to draw
  22448. @param lineThickness the thickness of the line
  22449. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  22450. @param arrowheadLength the length of the arrow head (along the length of the line)
  22451. */
  22452. void drawArrow (const Line<float>& line,
  22453. float lineThickness,
  22454. float arrowheadWidth,
  22455. float arrowheadLength) const;
  22456. /** Types of rendering quality that can be specified when drawing images.
  22457. @see blendImage, Graphics::setImageResamplingQuality
  22458. */
  22459. enum ResamplingQuality
  22460. {
  22461. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  22462. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  22463. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  22464. };
  22465. /** Changes the quality that will be used when resampling images.
  22466. By default a Graphics object will be set to mediumRenderingQuality.
  22467. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  22468. */
  22469. void setImageResamplingQuality (const ResamplingQuality newQuality);
  22470. /** Draws an image.
  22471. This will draw the whole of an image, positioning its top-left corner at the
  22472. given co-ordinates, and keeping its size the same. This is the simplest image
  22473. drawing method - the others give more control over the scaling and clipping
  22474. of the images.
  22475. Images are composited using the context's current opacity, so if you
  22476. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22477. (or setColour() with an opaque colour) before drawing images.
  22478. */
  22479. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  22480. bool fillAlphaChannelWithCurrentBrush = false) const;
  22481. /** Draws part of an image, rescaling it to fit in a given target region.
  22482. The specified area of the source image is rescaled and drawn to fill the
  22483. specifed destination rectangle.
  22484. Images are composited using the context's current opacity, so if you
  22485. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22486. (or setColour() with an opaque colour) before drawing images.
  22487. @param imageToDraw the image to overlay
  22488. @param destX the left of the destination rectangle
  22489. @param destY the top of the destination rectangle
  22490. @param destWidth the width of the destination rectangle
  22491. @param destHeight the height of the destination rectangle
  22492. @param sourceX the left of the rectangle to copy from the source image
  22493. @param sourceY the top of the rectangle to copy from the source image
  22494. @param sourceWidth the width of the rectangle to copy from the source image
  22495. @param sourceHeight the height of the rectangle to copy from the source image
  22496. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  22497. the source image's alpha channel is used as a mask with
  22498. which to fill the destination using the current colour
  22499. or brush. (If the source is has no alpha channel, then
  22500. it will just fill the target with a solid rectangle)
  22501. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  22502. */
  22503. void drawImage (const Image& imageToDraw,
  22504. int destX, int destY, int destWidth, int destHeight,
  22505. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  22506. bool fillAlphaChannelWithCurrentBrush = false) const;
  22507. /** Draws an image, having applied an affine transform to it.
  22508. This lets you throw the image around in some wacky ways, rotate it, shear,
  22509. scale it, etc.
  22510. Images are composited using the context's current opacity, so if you
  22511. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22512. (or setColour() with an opaque colour) before drawing images.
  22513. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  22514. are ignored and it is filled with the current brush, masked by its alpha channel.
  22515. If you want to render only a subsection of an image, use Image::getClippedImage() to
  22516. create the section that you need.
  22517. @see setImageResamplingQuality, drawImage
  22518. */
  22519. void drawImageTransformed (const Image& imageToDraw,
  22520. const AffineTransform& transform,
  22521. bool fillAlphaChannelWithCurrentBrush = false) const;
  22522. /** Draws an image to fit within a designated rectangle.
  22523. If the image is too big or too small for the space, it will be rescaled
  22524. to fit as nicely as it can do without affecting its aspect ratio. It will
  22525. then be placed within the target rectangle according to the justification flags
  22526. specified.
  22527. @param imageToDraw the source image to draw
  22528. @param destX top-left of the target rectangle to fit it into
  22529. @param destY top-left of the target rectangle to fit it into
  22530. @param destWidth size of the target rectangle to fit the image into
  22531. @param destHeight size of the target rectangle to fit the image into
  22532. @param placementWithinTarget this specifies how the image should be positioned
  22533. within the target rectangle - see the RectanglePlacement
  22534. class for more details about this.
  22535. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  22536. alpha channel will be used as a mask with which to
  22537. draw with the current brush or colour. This is
  22538. similar to fillAlphaMap(), and see also drawImage()
  22539. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  22540. */
  22541. void drawImageWithin (const Image& imageToDraw,
  22542. int destX, int destY, int destWidth, int destHeight,
  22543. const RectanglePlacement& placementWithinTarget,
  22544. bool fillAlphaChannelWithCurrentBrush = false) const;
  22545. /** Returns the position of the bounding box for the current clipping region.
  22546. @see getClipRegion, clipRegionIntersects
  22547. */
  22548. const Rectangle<int> getClipBounds() const;
  22549. /** Checks whether a rectangle overlaps the context's clipping region.
  22550. If this returns false, no part of the given area can be drawn onto, so this
  22551. method can be used to optimise a component's paint() method, by letting it
  22552. avoid drawing complex objects that aren't within the region being repainted.
  22553. */
  22554. bool clipRegionIntersects (const Rectangle<int>& area) const;
  22555. /** Intersects the current clipping region with another region.
  22556. @returns true if the resulting clipping region is non-zero in size
  22557. @see setOrigin, clipRegionIntersects
  22558. */
  22559. bool reduceClipRegion (int x, int y, int width, int height);
  22560. /** Intersects the current clipping region with another region.
  22561. @returns true if the resulting clipping region is non-zero in size
  22562. @see setOrigin, clipRegionIntersects
  22563. */
  22564. bool reduceClipRegion (const Rectangle<int>& area);
  22565. /** Intersects the current clipping region with a rectangle list region.
  22566. @returns true if the resulting clipping region is non-zero in size
  22567. @see setOrigin, clipRegionIntersects
  22568. */
  22569. bool reduceClipRegion (const RectangleList& clipRegion);
  22570. /** Intersects the current clipping region with a path.
  22571. @returns true if the resulting clipping region is non-zero in size
  22572. @see reduceClipRegion
  22573. */
  22574. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  22575. /** Intersects the current clipping region with an image's alpha-channel.
  22576. The current clipping path is intersected with the area covered by this image's
  22577. alpha-channel, after the image has been transformed by the specified matrix.
  22578. @param image the image whose alpha-channel should be used. If the image doesn't
  22579. have an alpha-channel, it is treated as entirely opaque.
  22580. @param transform a matrix to apply to the image
  22581. @returns true if the resulting clipping region is non-zero in size
  22582. @see reduceClipRegion
  22583. */
  22584. bool reduceClipRegion (const Image& image, const AffineTransform& transform);
  22585. /** Excludes a rectangle to stop it being drawn into. */
  22586. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  22587. /** Returns true if no drawing can be done because the clip region is zero. */
  22588. bool isClipEmpty() const;
  22589. /** Saves the current graphics state on an internal stack.
  22590. To restore the state, use restoreState().
  22591. @see ScopedSaveState
  22592. */
  22593. void saveState();
  22594. /** Restores a graphics state that was previously saved with saveState().
  22595. @see ScopedSaveState
  22596. */
  22597. void restoreState();
  22598. /** Uses RAII to save and restore the state of a graphics context.
  22599. On construction, this calls Graphics::saveState(), and on destruction it calls
  22600. Graphics::restoreState() on the Graphics object that you supply.
  22601. */
  22602. class ScopedSaveState
  22603. {
  22604. public:
  22605. ScopedSaveState (Graphics& g);
  22606. ~ScopedSaveState();
  22607. private:
  22608. Graphics& context;
  22609. JUCE_DECLARE_NON_COPYABLE (ScopedSaveState);
  22610. };
  22611. /** Begins rendering to an off-screen bitmap which will later be flattened onto the current
  22612. context with the given opacity.
  22613. The context uses an internal stack of temporary image layers to do this. When you've
  22614. finished drawing to the layer, call endTransparencyLayer() to complete the operation and
  22615. composite the finished layer. Every call to beginTransparencyLayer() MUST be matched
  22616. by a corresponding call to endTransparencyLayer()!
  22617. This call also saves the current state, and endTransparencyLayer() restores it.
  22618. */
  22619. void beginTransparencyLayer (float layerOpacity);
  22620. /** Completes a drawing operation to a temporary semi-transparent buffer.
  22621. See beginTransparencyLayer() for more details.
  22622. */
  22623. void endTransparencyLayer();
  22624. /** Moves the position of the context's origin.
  22625. This changes the position that the context considers to be (0, 0) to
  22626. the specified position.
  22627. So if you call setOrigin (100, 100), then the position that was previously
  22628. referred to as (100, 100) will subsequently be considered to be (0, 0).
  22629. @see reduceClipRegion, addTransform
  22630. */
  22631. void setOrigin (int newOriginX, int newOriginY);
  22632. /** Adds a transformation which will be performed on all the graphics operations that
  22633. the context subsequently performs.
  22634. After calling this, all the coordinates that are passed into the context will be
  22635. transformed by this matrix.
  22636. @see setOrigin
  22637. */
  22638. void addTransform (const AffineTransform& transform);
  22639. /** Resets the current colour, brush, and font to default settings. */
  22640. void resetToDefaultState();
  22641. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  22642. bool isVectorDevice() const;
  22643. /** Create a graphics that uses a given low-level renderer.
  22644. For internal use only.
  22645. NB. The context will NOT be deleted by this object when it is deleted.
  22646. */
  22647. Graphics (LowLevelGraphicsContext* internalContext) noexcept;
  22648. /** @internal */
  22649. LowLevelGraphicsContext* getInternalContext() const noexcept { return context; }
  22650. private:
  22651. LowLevelGraphicsContext* const context;
  22652. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  22653. bool saveStatePending;
  22654. void saveStateIfPending();
  22655. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Graphics);
  22656. };
  22657. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  22658. /*** End of inlined file: juce_Graphics.h ***/
  22659. /**
  22660. A graphical effect filter that can be applied to components.
  22661. An ImageEffectFilter can be applied to the image that a component
  22662. paints before it hits the screen.
  22663. This is used for adding effects like shadows, blurs, etc.
  22664. @see Component::setComponentEffect
  22665. */
  22666. class JUCE_API ImageEffectFilter
  22667. {
  22668. public:
  22669. /** Overridden to render the effect.
  22670. The implementation of this method must use the image that is passed in
  22671. as its source, and should render its output to the graphics context passed in.
  22672. @param sourceImage the image that the source component has just rendered with
  22673. its paint() method. The image may or may not have an alpha
  22674. channel, depending on whether the component is opaque.
  22675. @param destContext the graphics context to use to draw the resultant image.
  22676. @param alpha the alpha with which to draw the resultant image to the
  22677. target context
  22678. */
  22679. virtual void applyEffect (Image& sourceImage,
  22680. Graphics& destContext,
  22681. float alpha) = 0;
  22682. /** Destructor. */
  22683. virtual ~ImageEffectFilter() {}
  22684. };
  22685. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  22686. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  22687. /*** Start of inlined file: juce_Image.h ***/
  22688. #ifndef __JUCE_IMAGE_JUCEHEADER__
  22689. #define __JUCE_IMAGE_JUCEHEADER__
  22690. /**
  22691. Holds a fixed-size bitmap.
  22692. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  22693. To draw into an image, create a Graphics object for it.
  22694. e.g. @code
  22695. // create a transparent 500x500 image..
  22696. Image myImage (Image::RGB, 500, 500, true);
  22697. Graphics g (myImage);
  22698. g.setColour (Colours::red);
  22699. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  22700. @endcode
  22701. Other useful ways to create an image are with the ImageCache class, or the
  22702. ImageFileFormat, which provides a way to load common image files.
  22703. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  22704. */
  22705. class JUCE_API Image
  22706. {
  22707. public:
  22708. /**
  22709. */
  22710. enum PixelFormat
  22711. {
  22712. UnknownFormat,
  22713. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  22714. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  22715. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  22716. };
  22717. /**
  22718. */
  22719. enum ImageType
  22720. {
  22721. SoftwareImage = 0,
  22722. NativeImage
  22723. };
  22724. /** Creates a null image. */
  22725. Image();
  22726. /** Creates an image with a specified size and format.
  22727. @param format the number of colour channels in the image
  22728. @param imageWidth the desired width of the image, in pixels - this value must be
  22729. greater than zero (otherwise a width of 1 will be used)
  22730. @param imageHeight the desired width of the image, in pixels - this value must be
  22731. greater than zero (otherwise a height of 1 will be used)
  22732. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  22733. or transparent black (if it's ARGB). If false, the image may contain
  22734. junk initially, so you need to make sure you overwrite it thoroughly.
  22735. @param type the type of image - this lets you specify whether you want a purely
  22736. memory-based image, or one that may be managed by the OS if possible.
  22737. */
  22738. Image (PixelFormat format,
  22739. int imageWidth,
  22740. int imageHeight,
  22741. bool clearImage,
  22742. ImageType type = NativeImage);
  22743. /** Creates a shared reference to another image.
  22744. This won't create a duplicate of the image - when Image objects are copied, they simply
  22745. point to the same shared image data. To make sure that an Image object has its own unique,
  22746. unshared internal data, call duplicateIfShared().
  22747. */
  22748. Image (const Image& other);
  22749. /** Makes this image refer to the same underlying image as another object.
  22750. This won't create a duplicate of the image - when Image objects are copied, they simply
  22751. point to the same shared image data. To make sure that an Image object has its own unique,
  22752. unshared internal data, call duplicateIfShared().
  22753. */
  22754. Image& operator= (const Image&);
  22755. /** Destructor. */
  22756. ~Image();
  22757. /** Returns true if the two images are referring to the same internal, shared image. */
  22758. bool operator== (const Image& other) const noexcept { return image == other.image; }
  22759. /** Returns true if the two images are not referring to the same internal, shared image. */
  22760. bool operator!= (const Image& other) const noexcept { return image != other.image; }
  22761. /** Returns true if this image isn't null.
  22762. If you create an Image with the default constructor, it has no size or content, and is null
  22763. until you reassign it to an Image which contains some actual data.
  22764. The isNull() method is the opposite of isValid().
  22765. @see isNull
  22766. */
  22767. inline bool isValid() const noexcept { return image != nullptr; }
  22768. /** Returns true if this image is not valid.
  22769. If you create an Image with the default constructor, it has no size or content, and is null
  22770. until you reassign it to an Image which contains some actual data.
  22771. The isNull() method is the opposite of isValid().
  22772. @see isValid
  22773. */
  22774. inline bool isNull() const noexcept { return image == nullptr; }
  22775. /** A null Image object that can be used when you need to return an invalid image.
  22776. This object is the equivalient to an Image created with the default constructor.
  22777. */
  22778. static const Image null;
  22779. /** Returns the image's width (in pixels). */
  22780. int getWidth() const noexcept { return image == nullptr ? 0 : image->width; }
  22781. /** Returns the image's height (in pixels). */
  22782. int getHeight() const noexcept { return image == nullptr ? 0 : image->height; }
  22783. /** Returns a rectangle with the same size as this image.
  22784. The rectangle's origin is always (0, 0).
  22785. */
  22786. const Rectangle<int> getBounds() const noexcept { return image == nullptr ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  22787. /** Returns the image's pixel format. */
  22788. PixelFormat getFormat() const noexcept { return image == nullptr ? UnknownFormat : image->format; }
  22789. /** True if the image's format is ARGB. */
  22790. bool isARGB() const noexcept { return getFormat() == ARGB; }
  22791. /** True if the image's format is RGB. */
  22792. bool isRGB() const noexcept { return getFormat() == RGB; }
  22793. /** True if the image's format is a single-channel alpha map. */
  22794. bool isSingleChannel() const noexcept { return getFormat() == SingleChannel; }
  22795. /** True if the image contains an alpha-channel. */
  22796. bool hasAlphaChannel() const noexcept { return getFormat() != RGB; }
  22797. /** Clears a section of the image with a given colour.
  22798. This won't do any alpha-blending - it just sets all pixels in the image to
  22799. the given colour (which may be non-opaque if the image has an alpha channel).
  22800. */
  22801. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  22802. /** Returns a rescaled version of this image.
  22803. A new image is returned which is a copy of this one, rescaled to the given size.
  22804. Note that if the new size is identical to the existing image, this will just return
  22805. a reference to the original image, and won't actually create a duplicate.
  22806. */
  22807. const Image rescaled (int newWidth, int newHeight,
  22808. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  22809. /** Returns a version of this image with a different image format.
  22810. A new image is returned which has been converted to the specified format.
  22811. Note that if the new format is no different to the current one, this will just return
  22812. a reference to the original image, and won't actually create a copy.
  22813. */
  22814. const Image convertedToFormat (PixelFormat newFormat) const;
  22815. /** Makes sure that no other Image objects share the same underlying data as this one.
  22816. If no other Image objects refer to the same shared data as this one, this method has no
  22817. effect. But if there are other references to the data, this will create a new copy of
  22818. the data internally.
  22819. Call this if you want to draw onto the image, but want to make sure that this doesn't
  22820. affect any other code that may be sharing the same data.
  22821. @see getReferenceCount
  22822. */
  22823. void duplicateIfShared();
  22824. /** Returns an image which refers to a subsection of this image.
  22825. This will not make a copy of the original - the new image will keep a reference to it, so that
  22826. if the original image is changed, the contents of the subsection will also change. Likewise if you
  22827. draw into the subimage, you'll also be drawing onto that area of the original image. Note that if
  22828. you use operator= to make the original Image object refer to something else, the subsection image
  22829. won't pick up this change, it'll remain pointing at the original.
  22830. The area passed-in will be clipped to the bounds of this image, so this may return a smaller
  22831. image than the area you asked for, or even a null image if the area was out-of-bounds.
  22832. */
  22833. const Image getClippedImage (const Rectangle<int>& area) const;
  22834. /** Returns the colour of one of the pixels in the image.
  22835. If the co-ordinates given are beyond the image's boundaries, this will
  22836. return Colours::transparentBlack.
  22837. @see setPixelAt, Image::BitmapData::getPixelColour
  22838. */
  22839. const Colour getPixelAt (int x, int y) const;
  22840. /** Sets the colour of one of the image's pixels.
  22841. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  22842. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  22843. with the given one. The colour's opacity will be ignored if this image doesn't have
  22844. an alpha-channel.
  22845. @see getPixelAt, Image::BitmapData::setPixelColour
  22846. */
  22847. void setPixelAt (int x, int y, const Colour& colour);
  22848. /** Changes the opacity of a pixel.
  22849. This only has an effect if the image has an alpha channel and if the
  22850. given co-ordinates are inside the image's boundary.
  22851. The multiplier must be in the range 0 to 1.0, and the current alpha
  22852. at the given co-ordinates will be multiplied by this value.
  22853. @see setPixelAt
  22854. */
  22855. void multiplyAlphaAt (int x, int y, float multiplier);
  22856. /** Changes the overall opacity of the image.
  22857. This will multiply the alpha value of each pixel in the image by the given
  22858. amount (limiting the resulting alpha values between 0 and 255). This allows
  22859. you to make an image more or less transparent.
  22860. If the image doesn't have an alpha channel, this won't have any effect.
  22861. */
  22862. void multiplyAllAlphas (float amountToMultiplyBy);
  22863. /** Changes all the colours to be shades of grey, based on their current luminosity.
  22864. */
  22865. void desaturate();
  22866. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  22867. You should only use this class as a last resort - messing about with the internals of
  22868. an image is only recommended for people who really know what they're doing!
  22869. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  22870. hanging around while the image is being used elsewhere.
  22871. Depending on the way the image class is implemented, this may create a temporary buffer
  22872. which is copied back to the image when the object is deleted, or it may just get a pointer
  22873. directly into the image's raw data.
  22874. You can use the stride and data values in this class directly, but don't alter them!
  22875. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  22876. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  22877. */
  22878. class BitmapData
  22879. {
  22880. public:
  22881. enum ReadWriteMode
  22882. {
  22883. readOnly,
  22884. writeOnly,
  22885. readWrite
  22886. };
  22887. BitmapData (Image& image, int x, int y, int w, int h, ReadWriteMode mode);
  22888. BitmapData (const Image& image, int x, int y, int w, int h);
  22889. BitmapData (const Image& image, ReadWriteMode mode);
  22890. ~BitmapData();
  22891. /** Returns a pointer to the start of a line in the image.
  22892. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  22893. sure it's not out-of-range.
  22894. */
  22895. inline uint8* getLinePointer (int y) const noexcept { return data + y * lineStride; }
  22896. /** Returns a pointer to a pixel in the image.
  22897. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  22898. not out-of-range.
  22899. */
  22900. inline uint8* getPixelPointer (int x, int y) const noexcept { return data + y * lineStride + x * pixelStride; }
  22901. /** Returns the colour of a given pixel.
  22902. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  22903. repsonsibility to make sure they're within the image's size.
  22904. */
  22905. const Colour getPixelColour (int x, int y) const noexcept;
  22906. /** Sets the colour of a given pixel.
  22907. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  22908. repsonsibility to make sure they're within the image's size.
  22909. */
  22910. void setPixelColour (int x, int y, const Colour& colour) const noexcept;
  22911. uint8* data;
  22912. PixelFormat pixelFormat;
  22913. int lineStride, pixelStride, width, height;
  22914. /** Used internally by custom image types to manage pixel data lifetime. */
  22915. class BitmapDataReleaser
  22916. {
  22917. protected:
  22918. BitmapDataReleaser() {}
  22919. public:
  22920. virtual ~BitmapDataReleaser() {}
  22921. };
  22922. ScopedPointer<BitmapDataReleaser> dataReleaser;
  22923. private:
  22924. JUCE_DECLARE_NON_COPYABLE (BitmapData);
  22925. };
  22926. /** Copies some pixel values to a rectangle of the image.
  22927. The format of the pixel data must match that of the image itself, and the
  22928. rectangle supplied must be within the image's bounds.
  22929. */
  22930. void setPixelData (int destX, int destY, int destW, int destH,
  22931. const uint8* sourcePixelData, int sourceLineStride);
  22932. /** Copies a section of the image to somewhere else within itself. */
  22933. void moveImageSection (int destX, int destY,
  22934. int sourceX, int sourceY,
  22935. int width, int height);
  22936. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  22937. of the image.
  22938. @param result the list that will have the area added to it
  22939. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  22940. above this level will be considered opaque
  22941. */
  22942. void createSolidAreaMask (RectangleList& result,
  22943. float alphaThreshold = 0.5f) const;
  22944. /** Returns a NamedValueSet that is attached to the image and which can be used for
  22945. associating custom values with it.
  22946. If this is a null image, this will return a null pointer.
  22947. */
  22948. NamedValueSet* getProperties() const;
  22949. /** Creates a context suitable for drawing onto this image.
  22950. Don't call this method directly! It's used internally by the Graphics class.
  22951. */
  22952. LowLevelGraphicsContext* createLowLevelContext() const;
  22953. /** Returns the number of Image objects which are currently referring to the same internal
  22954. shared image data.
  22955. @see duplicateIfShared
  22956. */
  22957. int getReferenceCount() const noexcept { return image == nullptr ? 0 : image->getReferenceCount(); }
  22958. /** This is a base class for task-specific types of image.
  22959. Don't use this class directly! It's used internally by the Image class.
  22960. */
  22961. class SharedImage : public ReferenceCountedObject
  22962. {
  22963. public:
  22964. SharedImage (PixelFormat format, int width, int height);
  22965. ~SharedImage();
  22966. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  22967. virtual SharedImage* clone() = 0;
  22968. virtual ImageType getType() const = 0;
  22969. virtual void initialiseBitmapData (BitmapData& bitmapData, int x, int y, BitmapData::ReadWriteMode mode) = 0;
  22970. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  22971. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  22972. const PixelFormat getPixelFormat() const noexcept { return format; }
  22973. int getWidth() const noexcept { return width; }
  22974. int getHeight() const noexcept { return height; }
  22975. protected:
  22976. friend class Image;
  22977. friend class BitmapData;
  22978. const PixelFormat format;
  22979. const int width, height;
  22980. NamedValueSet userData;
  22981. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedImage);
  22982. };
  22983. /** @internal */
  22984. SharedImage* getSharedImage() const noexcept { return image; }
  22985. /** @internal */
  22986. explicit Image (SharedImage* instance);
  22987. private:
  22988. friend class SharedImage;
  22989. friend class BitmapData;
  22990. ReferenceCountedObjectPtr<SharedImage> image;
  22991. JUCE_LEAK_DETECTOR (Image);
  22992. };
  22993. #endif // __JUCE_IMAGE_JUCEHEADER__
  22994. /*** End of inlined file: juce_Image.h ***/
  22995. /*** Start of inlined file: juce_RectangleList.h ***/
  22996. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  22997. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  22998. /**
  22999. Maintains a set of rectangles as a complex region.
  23000. This class allows a set of rectangles to be treated as a solid shape, and can
  23001. add and remove rectangular sections of it, and simplify overlapping or
  23002. adjacent rectangles.
  23003. @see Rectangle
  23004. */
  23005. class JUCE_API RectangleList
  23006. {
  23007. public:
  23008. /** Creates an empty RectangleList */
  23009. RectangleList() noexcept;
  23010. /** Creates a copy of another list */
  23011. RectangleList (const RectangleList& other);
  23012. /** Creates a list containing just one rectangle. */
  23013. RectangleList (const Rectangle<int>& rect);
  23014. /** Copies this list from another one. */
  23015. RectangleList& operator= (const RectangleList& other);
  23016. /** Destructor. */
  23017. ~RectangleList();
  23018. /** Returns true if the region is empty. */
  23019. bool isEmpty() const noexcept;
  23020. /** Returns the number of rectangles in the list. */
  23021. int getNumRectangles() const noexcept { return rects.size(); }
  23022. /** Returns one of the rectangles at a particular index.
  23023. @returns the rectangle at the index, or an empty rectangle if the
  23024. index is out-of-range.
  23025. */
  23026. const Rectangle<int> getRectangle (int index) const noexcept;
  23027. /** Removes all rectangles to leave an empty region. */
  23028. void clear();
  23029. /** Merges a new rectangle into the list.
  23030. The rectangle being added will first be clipped to remove any parts of it
  23031. that overlap existing rectangles in the list.
  23032. */
  23033. void add (int x, int y, int width, int height);
  23034. /** Merges a new rectangle into the list.
  23035. The rectangle being added will first be clipped to remove any parts of it
  23036. that overlap existing rectangles in the list, and adjacent rectangles will be
  23037. merged into it.
  23038. */
  23039. void add (const Rectangle<int>& rect);
  23040. /** Dumbly adds a rectangle to the list without checking for overlaps.
  23041. This simply adds the rectangle to the end, it doesn't merge it or remove
  23042. any overlapping bits.
  23043. */
  23044. void addWithoutMerging (const Rectangle<int>& rect);
  23045. /** Merges another rectangle list into this one.
  23046. Any overlaps between the two lists will be clipped, so that the result is
  23047. the union of both lists.
  23048. */
  23049. void add (const RectangleList& other);
  23050. /** Removes a rectangular region from the list.
  23051. Any rectangles in the list which overlap this will be clipped and subdivided
  23052. if necessary.
  23053. */
  23054. void subtract (const Rectangle<int>& rect);
  23055. /** Removes all areas in another RectangleList from this one.
  23056. Any rectangles in the list which overlap this will be clipped and subdivided
  23057. if necessary.
  23058. @returns true if the resulting list is non-empty.
  23059. */
  23060. bool subtract (const RectangleList& otherList);
  23061. /** Removes any areas of the region that lie outside a given rectangle.
  23062. Any rectangles in the list which overlap this will be clipped and subdivided
  23063. if necessary.
  23064. Returns true if the resulting region is not empty, false if it is empty.
  23065. @see getIntersectionWith
  23066. */
  23067. bool clipTo (const Rectangle<int>& rect);
  23068. /** Removes any areas of the region that lie outside a given rectangle list.
  23069. Any rectangles in this object which overlap the specified list will be clipped
  23070. and subdivided if necessary.
  23071. Returns true if the resulting region is not empty, false if it is empty.
  23072. @see getIntersectionWith
  23073. */
  23074. bool clipTo (const RectangleList& other);
  23075. /** Creates a region which is the result of clipping this one to a given rectangle.
  23076. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  23077. resulting region into the list whose reference is passed-in.
  23078. Returns true if the resulting region is not empty, false if it is empty.
  23079. @see clipTo
  23080. */
  23081. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  23082. /** Swaps the contents of this and another list.
  23083. This swaps their internal pointers, so is hugely faster than using copy-by-value
  23084. to swap them.
  23085. */
  23086. void swapWith (RectangleList& otherList) noexcept;
  23087. /** Checks whether the region contains a given point.
  23088. @returns true if the point lies within one of the rectangles in the list
  23089. */
  23090. bool containsPoint (int x, int y) const noexcept;
  23091. /** Checks whether the region contains the whole of a given rectangle.
  23092. @returns true all parts of the rectangle passed in lie within the region
  23093. defined by this object
  23094. @see intersectsRectangle, containsPoint
  23095. */
  23096. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  23097. /** Checks whether the region contains any part of a given rectangle.
  23098. @returns true if any part of the rectangle passed in lies within the region
  23099. defined by this object
  23100. @see containsRectangle
  23101. */
  23102. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const noexcept;
  23103. /** Checks whether this region intersects any part of another one.
  23104. @see intersectsRectangle
  23105. */
  23106. bool intersects (const RectangleList& other) const noexcept;
  23107. /** Returns the smallest rectangle that can enclose the whole of this region. */
  23108. const Rectangle<int> getBounds() const noexcept;
  23109. /** Optimises the list into a minimum number of constituent rectangles.
  23110. This will try to combine any adjacent rectangles into larger ones where
  23111. possible, to simplify lists that might have been fragmented by repeated
  23112. add/subtract calls.
  23113. */
  23114. void consolidate();
  23115. /** Adds an x and y value to all the co-ordinates. */
  23116. void offsetAll (int dx, int dy) noexcept;
  23117. /** Creates a Path object to represent this region. */
  23118. const Path toPath() const;
  23119. /** An iterator for accessing all the rectangles in a RectangleList. */
  23120. class JUCE_API Iterator
  23121. {
  23122. public:
  23123. Iterator (const RectangleList& list) noexcept;
  23124. ~Iterator();
  23125. /** Advances to the next rectangle, and returns true if it's not finished.
  23126. Call this before using getRectangle() to find the rectangle that was returned.
  23127. */
  23128. bool next() noexcept;
  23129. /** Returns the current rectangle. */
  23130. const Rectangle<int>* getRectangle() const noexcept { return current; }
  23131. private:
  23132. const Rectangle<int>* current;
  23133. const RectangleList& owner;
  23134. int index;
  23135. JUCE_DECLARE_NON_COPYABLE (Iterator);
  23136. };
  23137. private:
  23138. friend class Iterator;
  23139. Array <Rectangle<int> > rects;
  23140. JUCE_LEAK_DETECTOR (RectangleList);
  23141. };
  23142. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  23143. /*** End of inlined file: juce_RectangleList.h ***/
  23144. /*** Start of inlined file: juce_BorderSize.h ***/
  23145. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  23146. #define __JUCE_BORDERSIZE_JUCEHEADER__
  23147. /**
  23148. Specifies a set of gaps to be left around the sides of a rectangle.
  23149. This is basically the size of the spaces at the top, bottom, left and right of
  23150. a rectangle. It's used by various component classes to specify borders.
  23151. @see Rectangle
  23152. */
  23153. template <typename ValueType>
  23154. class BorderSize
  23155. {
  23156. public:
  23157. /** Creates a null border.
  23158. All sizes are left as 0.
  23159. */
  23160. BorderSize() noexcept
  23161. : top(), left(), bottom(), right()
  23162. {
  23163. }
  23164. /** Creates a copy of another border. */
  23165. BorderSize (const BorderSize& other) noexcept
  23166. : top (other.top), left (other.left), bottom (other.bottom), right (other.right)
  23167. {
  23168. }
  23169. /** Creates a border with the given gaps. */
  23170. BorderSize (ValueType topGap, ValueType leftGap, ValueType bottomGap, ValueType rightGap) noexcept
  23171. : top (topGap), left (leftGap), bottom (bottomGap), right (rightGap)
  23172. {
  23173. }
  23174. /** Creates a border with the given gap on all sides. */
  23175. explicit BorderSize (ValueType allGaps) noexcept
  23176. : top (allGaps), left (allGaps), bottom (allGaps), right (allGaps)
  23177. {
  23178. }
  23179. /** Returns the gap that should be left at the top of the region. */
  23180. ValueType getTop() const noexcept { return top; }
  23181. /** Returns the gap that should be left at the top of the region. */
  23182. ValueType getLeft() const noexcept { return left; }
  23183. /** Returns the gap that should be left at the top of the region. */
  23184. ValueType getBottom() const noexcept { return bottom; }
  23185. /** Returns the gap that should be left at the top of the region. */
  23186. ValueType getRight() const noexcept { return right; }
  23187. /** Returns the sum of the top and bottom gaps. */
  23188. ValueType getTopAndBottom() const noexcept { return top + bottom; }
  23189. /** Returns the sum of the left and right gaps. */
  23190. ValueType getLeftAndRight() const noexcept { return left + right; }
  23191. /** Returns true if this border has no thickness along any edge. */
  23192. bool isEmpty() const noexcept { return left + right + top + bottom == ValueType(); }
  23193. /** Changes the top gap. */
  23194. void setTop (ValueType newTopGap) noexcept { top = newTopGap; }
  23195. /** Changes the left gap. */
  23196. void setLeft (ValueType newLeftGap) noexcept { left = newLeftGap; }
  23197. /** Changes the bottom gap. */
  23198. void setBottom (ValueType newBottomGap) noexcept { bottom = newBottomGap; }
  23199. /** Changes the right gap. */
  23200. void setRight (ValueType newRightGap) noexcept { right = newRightGap; }
  23201. /** Returns a rectangle with these borders removed from it. */
  23202. const Rectangle<ValueType> subtractedFrom (const Rectangle<ValueType>& original) const noexcept
  23203. {
  23204. return Rectangle<ValueType> (original.getX() + left,
  23205. original.getY() + top,
  23206. original.getWidth() - (left + right),
  23207. original.getHeight() - (top + bottom));
  23208. }
  23209. /** Removes this border from a given rectangle. */
  23210. void subtractFrom (Rectangle<ValueType>& rectangle) const noexcept
  23211. {
  23212. rectangle = subtractedFrom (rectangle);
  23213. }
  23214. /** Returns a rectangle with these borders added around it. */
  23215. const Rectangle<ValueType> addedTo (const Rectangle<ValueType>& original) const noexcept
  23216. {
  23217. return Rectangle<ValueType> (original.getX() - left,
  23218. original.getY() - top,
  23219. original.getWidth() + (left + right),
  23220. original.getHeight() + (top + bottom));
  23221. }
  23222. /** Adds this border around a given rectangle. */
  23223. void addTo (Rectangle<ValueType>& rectangle) const noexcept
  23224. {
  23225. rectangle = addedTo (rectangle);
  23226. }
  23227. bool operator== (const BorderSize& other) const noexcept
  23228. {
  23229. return top == other.top && left == other.left && bottom == other.bottom && right == other.right;
  23230. }
  23231. bool operator!= (const BorderSize& other) const noexcept
  23232. {
  23233. return ! operator== (other);
  23234. }
  23235. private:
  23236. ValueType top, left, bottom, right;
  23237. JUCE_LEAK_DETECTOR (BorderSize);
  23238. };
  23239. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  23240. /*** End of inlined file: juce_BorderSize.h ***/
  23241. /*** Start of inlined file: juce_ModalComponentManager.h ***/
  23242. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23243. #define __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23244. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  23245. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23246. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23247. /**
  23248. Classes derived from this will be automatically deleted when the application exits.
  23249. After JUCEApplication::shutdown() has been called, any objects derived from
  23250. DeletedAtShutdown which are still in existence will be deleted in the reverse
  23251. order to that in which they were created.
  23252. So if you've got a singleton and don't want to have to explicitly delete it, just
  23253. inherit from this and it'll be taken care of.
  23254. */
  23255. class JUCE_API DeletedAtShutdown
  23256. {
  23257. protected:
  23258. /** Creates a DeletedAtShutdown object. */
  23259. DeletedAtShutdown();
  23260. /** Destructor.
  23261. It's ok to delete these objects explicitly - it's only the ones left
  23262. dangling at the end that will be deleted automatically.
  23263. */
  23264. virtual ~DeletedAtShutdown();
  23265. public:
  23266. /** Deletes all extant objects.
  23267. This shouldn't be used by applications, as it's called automatically
  23268. in the shutdown code of the JUCEApplication class.
  23269. */
  23270. static void deleteAll();
  23271. private:
  23272. static Array <DeletedAtShutdown*>& getObjects();
  23273. JUCE_DECLARE_NON_COPYABLE (DeletedAtShutdown);
  23274. };
  23275. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23276. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  23277. /**
  23278. Manages the system's stack of modal components.
  23279. Normally you'll just use the Component methods to invoke modal states in components,
  23280. and won't have to deal with this class directly, but this is the singleton object that's
  23281. used internally to manage the stack.
  23282. @see Component::enterModalState, Component::exitModalState, Component::isCurrentlyModal,
  23283. Component::getCurrentlyModalComponent, Component::isCurrentlyBlockedByAnotherModalComponent
  23284. */
  23285. class JUCE_API ModalComponentManager : public AsyncUpdater,
  23286. public DeletedAtShutdown
  23287. {
  23288. public:
  23289. /** Receives callbacks when a modal component is dismissed.
  23290. You can register a callback using Component::enterModalState() or
  23291. ModalComponentManager::attachCallback().
  23292. For some quick ways of creating callback objects, see the ModalCallbackFunction class.
  23293. @see ModalCallbackFunction
  23294. */
  23295. class Callback
  23296. {
  23297. public:
  23298. /** */
  23299. Callback() {}
  23300. /** Destructor. */
  23301. virtual ~Callback() {}
  23302. /** Called to indicate that a modal component has been dismissed.
  23303. You can register a callback using Component::enterModalState() or
  23304. ModalComponentManager::attachCallback().
  23305. The returnValue parameter is the value that was passed to Component::exitModalState()
  23306. when the component was dismissed.
  23307. The callback object will be deleted shortly after this method is called.
  23308. */
  23309. virtual void modalStateFinished (int returnValue) = 0;
  23310. };
  23311. /** Returns the number of components currently being shown modally.
  23312. @see getModalComponent
  23313. */
  23314. int getNumModalComponents() const;
  23315. /** Returns one of the components being shown modally.
  23316. An index of 0 is the most recently-shown, topmost component.
  23317. */
  23318. Component* getModalComponent (int index) const;
  23319. /** Returns true if the specified component is in a modal state. */
  23320. bool isModal (Component* component) const;
  23321. /** Returns true if the specified component is currently the topmost modal component. */
  23322. bool isFrontModalComponent (Component* component) const;
  23323. /** Adds a new callback that will be called when the specified modal component is dismissed.
  23324. If the component is modal, then when it is dismissed, either by being hidden, or by calling
  23325. Component::exitModalState(), then the Callback::modalStateFinished() method will be
  23326. called.
  23327. Each component can have any number of callbacks associated with it, and this one is added
  23328. to that list.
  23329. The object that is passed in will be deleted by the manager when it's no longer needed. If
  23330. the given component is not currently modal, the callback object is deleted immediately and
  23331. no action is taken.
  23332. */
  23333. void attachCallback (Component* component, Callback* callback);
  23334. /** Brings any modal components to the front. */
  23335. void bringModalComponentsToFront (bool topOneShouldGrabFocus = true);
  23336. #if JUCE_MODAL_LOOPS_PERMITTED
  23337. /** Runs the event loop until the currently topmost modal component is dismissed, and
  23338. returns the exit code for that component.
  23339. */
  23340. int runEventLoopForCurrentComponent();
  23341. #endif
  23342. juce_DeclareSingleton_SingleThreaded_Minimal (ModalComponentManager);
  23343. protected:
  23344. /** Creates a ModalComponentManager.
  23345. You shouldn't ever call the constructor - it's a singleton, so use ModalComponentManager::getInstance()
  23346. */
  23347. ModalComponentManager();
  23348. /** Destructor. */
  23349. ~ModalComponentManager();
  23350. /** @internal */
  23351. void handleAsyncUpdate();
  23352. private:
  23353. class ModalItem;
  23354. class ReturnValueRetriever;
  23355. friend class Component;
  23356. friend class OwnedArray <ModalItem>;
  23357. OwnedArray <ModalItem> stack;
  23358. void startModal (Component* component);
  23359. void endModal (Component* component, int returnValue);
  23360. void endModal (Component* component);
  23361. JUCE_DECLARE_NON_COPYABLE (ModalComponentManager);
  23362. };
  23363. /**
  23364. This class provides some handy utility methods for creating ModalComponentManager::Callback
  23365. objects that will invoke a static function with some parameters when a modal component is dismissed.
  23366. */
  23367. class ModalCallbackFunction
  23368. {
  23369. public:
  23370. /** This is a utility function to create a ModalComponentManager::Callback that will
  23371. call a static function with a parameter.
  23372. The function that you supply must take two parameters - the first being an int, which is
  23373. the result code that was used when the modal component was dismissed, and the second
  23374. can be a custom type. Note that this custom value will be copied and stored, so it must
  23375. be a primitive type or a class that provides copy-by-value semantics.
  23376. E.g. @code
  23377. static void myCallbackFunction (int modalResult, double customValue)
  23378. {
  23379. if (modalResult == 1)
  23380. doSomethingWith (customValue);
  23381. }
  23382. Component* someKindOfComp;
  23383. ...
  23384. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0));
  23385. @endcode
  23386. @see ModalComponentManager::Callback
  23387. */
  23388. template <typename ParamType>
  23389. static ModalComponentManager::Callback* create (void (*functionToCall) (int, ParamType),
  23390. ParamType parameterValue)
  23391. {
  23392. return new FunctionCaller1 <ParamType> (functionToCall, parameterValue);
  23393. }
  23394. /** This is a utility function to create a ModalComponentManager::Callback that will
  23395. call a static function with two custom parameters.
  23396. The function that you supply must take three parameters - the first being an int, which is
  23397. the result code that was used when the modal component was dismissed, and the next two are
  23398. your custom types. Note that these custom values will be copied and stored, so they must
  23399. be primitive types or classes that provide copy-by-value semantics.
  23400. E.g. @code
  23401. static void myCallbackFunction (int modalResult, double customValue1, String customValue2)
  23402. {
  23403. if (modalResult == 1)
  23404. doSomethingWith (customValue1, customValue2);
  23405. }
  23406. Component* someKindOfComp;
  23407. ...
  23408. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0, String ("xyz")));
  23409. @endcode
  23410. @see ModalComponentManager::Callback
  23411. */
  23412. template <typename ParamType1, typename ParamType2>
  23413. static ModalComponentManager::Callback* withParam (void (*functionToCall) (int, ParamType1, ParamType2),
  23414. ParamType1 parameterValue1,
  23415. ParamType2 parameterValue2)
  23416. {
  23417. return new FunctionCaller2 <ParamType1, ParamType2> (functionToCall, parameterValue1, parameterValue2);
  23418. }
  23419. /** This is a utility function to create a ModalComponentManager::Callback that will
  23420. call a static function with a component.
  23421. The function that you supply must take two parameters - the first being an int, which is
  23422. the result code that was used when the modal component was dismissed, and the second
  23423. can be a Component class. The component will be stored as a WeakReference, so that if it gets
  23424. deleted before this callback is invoked, the pointer that is passed to the function will be null.
  23425. E.g. @code
  23426. static void myCallbackFunction (int modalResult, Slider* mySlider)
  23427. {
  23428. if (modalResult == 1 && mySlider != nullptr) // (must check that mySlider isn't null in case it was deleted..)
  23429. mySlider->setValue (0.0);
  23430. }
  23431. Component* someKindOfComp;
  23432. Slider* mySlider;
  23433. ...
  23434. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider));
  23435. @endcode
  23436. @see ModalComponentManager::Callback
  23437. */
  23438. template <class ComponentType>
  23439. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*),
  23440. ComponentType* component)
  23441. {
  23442. return new ComponentCaller1 <ComponentType> (functionToCall, component);
  23443. }
  23444. /** Creates a ModalComponentManager::Callback that will call a static function with a component.
  23445. The function that you supply must take three parameters - the first being an int, which is
  23446. the result code that was used when the modal component was dismissed, the second being a Component
  23447. class, and the third being a custom type (which must be a primitive type or have copy-by-value semantics).
  23448. The component will be stored as a WeakReference, so that if it gets deleted before this callback is
  23449. invoked, the pointer that is passed into the function will be null.
  23450. E.g. @code
  23451. static void myCallbackFunction (int modalResult, Slider* mySlider, String customParam)
  23452. {
  23453. if (modalResult == 1 && mySlider != nullptr) // (must check that mySlider isn't null in case it was deleted..)
  23454. mySlider->setName (customParam);
  23455. }
  23456. Component* someKindOfComp;
  23457. Slider* mySlider;
  23458. ...
  23459. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider, String ("hello")));
  23460. @endcode
  23461. @see ModalComponentManager::Callback
  23462. */
  23463. template <class ComponentType, typename ParamType>
  23464. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*, ParamType),
  23465. ComponentType* component,
  23466. ParamType param)
  23467. {
  23468. return new ComponentCaller2 <ComponentType, ParamType> (functionToCall, component, param);
  23469. }
  23470. private:
  23471. template <typename ParamType>
  23472. class FunctionCaller1 : public ModalComponentManager::Callback
  23473. {
  23474. public:
  23475. typedef void (*FunctionType) (int, ParamType);
  23476. FunctionCaller1 (FunctionType& function_, ParamType& param_)
  23477. : function (function_), param (param_) {}
  23478. void modalStateFinished (int returnValue) { function (returnValue, param); }
  23479. private:
  23480. const FunctionType function;
  23481. ParamType param;
  23482. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller1);
  23483. };
  23484. template <typename ParamType1, typename ParamType2>
  23485. class FunctionCaller2 : public ModalComponentManager::Callback
  23486. {
  23487. public:
  23488. typedef void (*FunctionType) (int, ParamType1, ParamType2);
  23489. FunctionCaller2 (FunctionType& function_, ParamType1& param1_, ParamType2& param2_)
  23490. : function (function_), param1 (param1_), param2 (param2_) {}
  23491. void modalStateFinished (int returnValue) { function (returnValue, param1, param2); }
  23492. private:
  23493. const FunctionType function;
  23494. ParamType1 param1;
  23495. ParamType2 param2;
  23496. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller2);
  23497. };
  23498. template <typename ComponentType>
  23499. class ComponentCaller1 : public ModalComponentManager::Callback
  23500. {
  23501. public:
  23502. typedef void (*FunctionType) (int, ComponentType*);
  23503. ComponentCaller1 (FunctionType& function_, ComponentType* comp_)
  23504. : function (function_), comp (comp_) {}
  23505. void modalStateFinished (int returnValue)
  23506. {
  23507. function (returnValue, static_cast <ComponentType*> (comp.get()));
  23508. }
  23509. private:
  23510. const FunctionType function;
  23511. WeakReference<Component> comp;
  23512. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller1);
  23513. };
  23514. template <typename ComponentType, typename ParamType1>
  23515. class ComponentCaller2 : public ModalComponentManager::Callback
  23516. {
  23517. public:
  23518. typedef void (*FunctionType) (int, ComponentType*, ParamType1);
  23519. ComponentCaller2 (FunctionType& function_, ComponentType* comp_, ParamType1 param1_)
  23520. : function (function_), comp (comp_), param1 (param1_) {}
  23521. void modalStateFinished (int returnValue)
  23522. {
  23523. function (returnValue, static_cast <ComponentType*> (comp.get()), param1);
  23524. }
  23525. private:
  23526. const FunctionType function;
  23527. WeakReference<Component> comp;
  23528. ParamType1 param1;
  23529. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller2);
  23530. };
  23531. ModalCallbackFunction();
  23532. ~ModalCallbackFunction();
  23533. JUCE_DECLARE_NON_COPYABLE (ModalCallbackFunction);
  23534. };
  23535. #endif // __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23536. /*** End of inlined file: juce_ModalComponentManager.h ***/
  23537. class LookAndFeel;
  23538. class MouseInputSource;
  23539. class MouseInputSourceInternal;
  23540. class ComponentPeer;
  23541. class MarkerList;
  23542. class RelativeRectangle;
  23543. /**
  23544. The base class for all JUCE user-interface objects.
  23545. */
  23546. class JUCE_API Component : public MouseListener
  23547. {
  23548. public:
  23549. /** Creates a component.
  23550. To get it to actually appear, you'll also need to:
  23551. - Either add it to a parent component or use the addToDesktop() method to
  23552. make it a desktop window
  23553. - Set its size and position to something sensible
  23554. - Use setVisible() to make it visible
  23555. And for it to serve any useful purpose, you'll need to write a
  23556. subclass of Component or use one of the other types of component from
  23557. the library.
  23558. */
  23559. Component();
  23560. /** Destructor.
  23561. Note that when a component is deleted, any child components it contains are NOT
  23562. automatically deleted. It's your responsibilty to manage their lifespan - you
  23563. may want to use helper methods like deleteAllChildren(), or less haphazard
  23564. approaches like using ScopedPointers or normal object aggregation to manage them.
  23565. If the component being deleted is currently the child of another one, then during
  23566. deletion, it will be removed from its parent, and the parent will receive a childrenChanged()
  23567. callback. Any ComponentListener objects that have registered with it will also have their
  23568. ComponentListener::componentBeingDeleted() methods called.
  23569. */
  23570. virtual ~Component();
  23571. /** Creates a component, setting its name at the same time.
  23572. @see getName, setName
  23573. */
  23574. explicit Component (const String& componentName);
  23575. /** Returns the name of this component.
  23576. @see setName
  23577. */
  23578. const String& getName() const noexcept { return componentName; }
  23579. /** Sets the name of this component.
  23580. When the name changes, all registered ComponentListeners will receive a
  23581. ComponentListener::componentNameChanged() callback.
  23582. @see getName
  23583. */
  23584. virtual void setName (const String& newName);
  23585. /** Returns the ID string that was set by setComponentID().
  23586. @see setComponentID
  23587. */
  23588. const String& getComponentID() const noexcept { return componentID; }
  23589. /** Sets the component's ID string.
  23590. You can retrieve the ID using getComponentID().
  23591. @see getComponentID
  23592. */
  23593. void setComponentID (const String& newID);
  23594. /** Makes the component visible or invisible.
  23595. This method will show or hide the component.
  23596. Note that components default to being non-visible when first created.
  23597. Also note that visible components won't be seen unless all their parent components
  23598. are also visible.
  23599. This method will call visibilityChanged() and also componentVisibilityChanged()
  23600. for any component listeners that are interested in this component.
  23601. @param shouldBeVisible whether to show or hide the component
  23602. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  23603. */
  23604. virtual void setVisible (bool shouldBeVisible);
  23605. /** Tests whether the component is visible or not.
  23606. this doesn't necessarily tell you whether this comp is actually on the screen
  23607. because this depends on whether all the parent components are also visible - use
  23608. isShowing() to find this out.
  23609. @see isShowing, setVisible
  23610. */
  23611. bool isVisible() const noexcept { return flags.visibleFlag; }
  23612. /** Called when this component's visiblility changes.
  23613. @see setVisible, isVisible
  23614. */
  23615. virtual void visibilityChanged();
  23616. /** Tests whether this component and all its parents are visible.
  23617. @returns true only if this component and all its parents are visible.
  23618. @see isVisible
  23619. */
  23620. bool isShowing() const;
  23621. /** Makes this component appear as a window on the desktop.
  23622. Note that before calling this, you should make sure that the component's opacity is
  23623. set correctly using setOpaque(). If the component is non-opaque, the windowing
  23624. system will try to create a special transparent window for it, which will generally take
  23625. a lot more CPU to operate (and might not even be possible on some platforms).
  23626. If the component is inside a parent component at the time this method is called, it
  23627. will be first be removed from that parent. Likewise if a component on the desktop
  23628. is subsequently added to another component, it'll be removed from the desktop.
  23629. @param windowStyleFlags a combination of the flags specified in the
  23630. ComponentPeer::StyleFlags enum, which define the
  23631. window's characteristics.
  23632. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  23633. in which the juce component should place itself. On Windows,
  23634. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  23635. supported on all platforms, and best left as 0 unless you know
  23636. what you're doing
  23637. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  23638. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  23639. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  23640. */
  23641. virtual void addToDesktop (int windowStyleFlags,
  23642. void* nativeWindowToAttachTo = nullptr);
  23643. /** If the component is currently showing on the desktop, this will hide it.
  23644. You can also use setVisible() to hide a desktop window temporarily, but
  23645. removeFromDesktop() will free any system resources that are being used up.
  23646. @see addToDesktop, isOnDesktop
  23647. */
  23648. void removeFromDesktop();
  23649. /** Returns true if this component is currently showing on the desktop.
  23650. @see addToDesktop, removeFromDesktop
  23651. */
  23652. bool isOnDesktop() const noexcept;
  23653. /** Returns the heavyweight window that contains this component.
  23654. If this component is itself on the desktop, this will return the window
  23655. object that it is using. Otherwise, it will return the window of
  23656. its top-level parent component.
  23657. This may return 0 if there isn't a desktop component.
  23658. @see addToDesktop, isOnDesktop
  23659. */
  23660. ComponentPeer* getPeer() const;
  23661. /** For components on the desktop, this is called if the system wants to close the window.
  23662. This is a signal that either the user or the system wants the window to close. The
  23663. default implementation of this method will trigger an assertion to warn you that your
  23664. component should do something about it, but you can override this to ignore the event
  23665. if you want.
  23666. */
  23667. virtual void userTriedToCloseWindow();
  23668. /** Called for a desktop component which has just been minimised or un-minimised.
  23669. This will only be called for components on the desktop.
  23670. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  23671. */
  23672. virtual void minimisationStateChanged (bool isNowMinimised);
  23673. /** Brings the component to the front of its siblings.
  23674. If some of the component's siblings have had their 'always-on-top' flag set,
  23675. then they will still be kept in front of this one (unless of course this
  23676. one is also 'always-on-top').
  23677. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  23678. to the component (see grabKeyboardFocus() for more details)
  23679. @see toBack, toBehind, setAlwaysOnTop
  23680. */
  23681. void toFront (bool shouldAlsoGainFocus);
  23682. /** Changes this component's z-order to be at the back of all its siblings.
  23683. If the component is set to be 'always-on-top', it will only be moved to the
  23684. back of the other other 'always-on-top' components.
  23685. @see toFront, toBehind, setAlwaysOnTop
  23686. */
  23687. void toBack();
  23688. /** Changes this component's z-order so that it's just behind another component.
  23689. @see toFront, toBack
  23690. */
  23691. void toBehind (Component* other);
  23692. /** Sets whether the component should always be kept at the front of its siblings.
  23693. @see isAlwaysOnTop
  23694. */
  23695. void setAlwaysOnTop (bool shouldStayOnTop);
  23696. /** Returns true if this component is set to always stay in front of its siblings.
  23697. @see setAlwaysOnTop
  23698. */
  23699. bool isAlwaysOnTop() const noexcept;
  23700. /** Returns the x coordinate of the component's left edge.
  23701. This is a distance in pixels from the left edge of the component's parent.
  23702. Note that if you've used setTransform() to apply a transform, then the component's
  23703. bounds will no longer be a direct reflection of the position at which it appears within
  23704. its parent, as the transform will be applied to its bounding box.
  23705. */
  23706. inline int getX() const noexcept { return bounds.getX(); }
  23707. /** Returns the y coordinate of the top of this component.
  23708. This is a distance in pixels from the top edge of the component's parent.
  23709. Note that if you've used setTransform() to apply a transform, then the component's
  23710. bounds will no longer be a direct reflection of the position at which it appears within
  23711. its parent, as the transform will be applied to its bounding box.
  23712. */
  23713. inline int getY() const noexcept { return bounds.getY(); }
  23714. /** Returns the component's width in pixels. */
  23715. inline int getWidth() const noexcept { return bounds.getWidth(); }
  23716. /** Returns the component's height in pixels. */
  23717. inline int getHeight() const noexcept { return bounds.getHeight(); }
  23718. /** Returns the x coordinate of the component's right-hand edge.
  23719. This is a distance in pixels from the left edge of the component's parent.
  23720. Note that if you've used setTransform() to apply a transform, then the component's
  23721. bounds will no longer be a direct reflection of the position at which it appears within
  23722. its parent, as the transform will be applied to its bounding box.
  23723. */
  23724. int getRight() const noexcept { return bounds.getRight(); }
  23725. /** Returns the component's top-left position as a Point. */
  23726. const Point<int> getPosition() const noexcept { return bounds.getPosition(); }
  23727. /** Returns the y coordinate of the bottom edge of this component.
  23728. This is a distance in pixels from the top edge of the component's parent.
  23729. Note that if you've used setTransform() to apply a transform, then the component's
  23730. bounds will no longer be a direct reflection of the position at which it appears within
  23731. its parent, as the transform will be applied to its bounding box.
  23732. */
  23733. int getBottom() const noexcept { return bounds.getBottom(); }
  23734. /** Returns this component's bounding box.
  23735. The rectangle returned is relative to the top-left of the component's parent.
  23736. Note that if you've used setTransform() to apply a transform, then the component's
  23737. bounds will no longer be a direct reflection of the position at which it appears within
  23738. its parent, as the transform will be applied to its bounding box.
  23739. */
  23740. const Rectangle<int>& getBounds() const noexcept { return bounds; }
  23741. /** Returns the component's bounds, relative to its own origin.
  23742. This is like getBounds(), but returns the rectangle in local coordinates, In practice, it'll
  23743. return a rectangle with position (0, 0), and the same size as this component.
  23744. */
  23745. const Rectangle<int> getLocalBounds() const noexcept;
  23746. /** Returns the area of this component's parent which this component covers.
  23747. The returned area is relative to the parent's coordinate space.
  23748. If the component has an affine transform specified, then the resulting area will be
  23749. the smallest rectangle that fully covers the component's transformed bounding box.
  23750. If this component has no parent, the return value will simply be the same as getBounds().
  23751. */
  23752. const Rectangle<int> getBoundsInParent() const noexcept;
  23753. /** Returns the region of this component that's not obscured by other, opaque components.
  23754. The RectangleList that is returned represents the area of this component
  23755. which isn't covered by opaque child components.
  23756. If includeSiblings is true, it will also take into account any siblings
  23757. that may be overlapping the component.
  23758. */
  23759. void getVisibleArea (RectangleList& result,
  23760. bool includeSiblings) const;
  23761. /** Returns this component's x coordinate relative the the screen's top-left origin.
  23762. @see getX, localPointToGlobal
  23763. */
  23764. int getScreenX() const;
  23765. /** Returns this component's y coordinate relative the the screen's top-left origin.
  23766. @see getY, localPointToGlobal
  23767. */
  23768. int getScreenY() const;
  23769. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  23770. @see getScreenBounds
  23771. */
  23772. const Point<int> getScreenPosition() const;
  23773. /** Returns the bounds of this component, relative to the screen's top-left.
  23774. @see getScreenPosition
  23775. */
  23776. const Rectangle<int> getScreenBounds() const;
  23777. /** Converts a point to be relative to this component's coordinate space.
  23778. This takes a point relative to a different component, and returns its position relative to this
  23779. component. If the sourceComponent parameter is null, the source point is assumed to be a global
  23780. screen coordinate.
  23781. */
  23782. const Point<int> getLocalPoint (const Component* sourceComponent,
  23783. const Point<int>& pointRelativeToSourceComponent) const;
  23784. /** Converts a rectangle to be relative to this component's coordinate space.
  23785. This takes a rectangle that is relative to a different component, and returns its position relative
  23786. to this component. If the sourceComponent parameter is null, the source rectangle is assumed to be
  23787. a screen coordinate.
  23788. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23789. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23790. the smallest rectangle that fully contains the transformed area.
  23791. */
  23792. const Rectangle<int> getLocalArea (const Component* sourceComponent,
  23793. const Rectangle<int>& areaRelativeToSourceComponent) const;
  23794. /** Converts a point relative to this component's top-left into a screen coordinate.
  23795. @see getLocalPoint, localAreaToGlobal
  23796. */
  23797. const Point<int> localPointToGlobal (const Point<int>& localPoint) const;
  23798. /** Converts a rectangle from this component's coordinate space to a screen coordinate.
  23799. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23800. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23801. the smallest rectangle that fully contains the transformed area.
  23802. @see getLocalPoint, localPointToGlobal
  23803. */
  23804. const Rectangle<int> localAreaToGlobal (const Rectangle<int>& localArea) const;
  23805. /** Moves the component to a new position.
  23806. Changes the component's top-left position (without changing its size).
  23807. The position is relative to the top-left of the component's parent.
  23808. If the component actually moves, this method will make a synchronous call to moved().
  23809. Note that if you've used setTransform() to apply a transform, then the component's
  23810. bounds will no longer be a direct reflection of the position at which it appears within
  23811. its parent, as the transform will be applied to whatever bounds you set for it.
  23812. @see setBounds, ComponentListener::componentMovedOrResized
  23813. */
  23814. void setTopLeftPosition (int x, int y);
  23815. /** Moves the component to a new position.
  23816. Changes the position of the component's top-right corner (keeping it the same size).
  23817. The position is relative to the top-left of the component's parent.
  23818. If the component actually moves, this method will make a synchronous call to moved().
  23819. Note that if you've used setTransform() to apply a transform, then the component's
  23820. bounds will no longer be a direct reflection of the position at which it appears within
  23821. its parent, as the transform will be applied to whatever bounds you set for it.
  23822. */
  23823. void setTopRightPosition (int x, int y);
  23824. /** Changes the size of the component.
  23825. A synchronous call to resized() will be occur if the size actually changes.
  23826. Note that if you've used setTransform() to apply a transform, then the component's
  23827. bounds will no longer be a direct reflection of the position at which it appears within
  23828. its parent, as the transform will be applied to whatever bounds you set for it.
  23829. */
  23830. void setSize (int newWidth, int newHeight);
  23831. /** Changes the component's position and size.
  23832. The coordinates are relative to the top-left of the component's parent, or relative
  23833. to the origin of the screen is the component is on the desktop.
  23834. If this method changes the component's top-left position, it will make a synchronous
  23835. call to moved(). If it changes the size, it will also make a call to resized().
  23836. Note that if you've used setTransform() to apply a transform, then the component's
  23837. bounds will no longer be a direct reflection of the position at which it appears within
  23838. its parent, as the transform will be applied to whatever bounds you set for it.
  23839. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  23840. */
  23841. void setBounds (int x, int y, int width, int height);
  23842. /** Changes the component's position and size.
  23843. The coordinates are relative to the top-left of the component's parent, or relative
  23844. to the origin of the screen is the component is on the desktop.
  23845. If this method changes the component's top-left position, it will make a synchronous
  23846. call to moved(). If it changes the size, it will also make a call to resized().
  23847. Note that if you've used setTransform() to apply a transform, then the component's
  23848. bounds will no longer be a direct reflection of the position at which it appears within
  23849. its parent, as the transform will be applied to whatever bounds you set for it.
  23850. @see setBounds
  23851. */
  23852. void setBounds (const Rectangle<int>& newBounds);
  23853. /** Changes the component's position and size.
  23854. This is similar to the other setBounds() methods, but uses RelativeRectangle::applyToComponent()
  23855. to set the position, This uses a Component::Positioner to make sure that any dynamic
  23856. expressions are used in the RelativeRectangle will be automatically re-applied to the
  23857. component's bounds when the source values change. See RelativeRectangle::applyToComponent()
  23858. for more details.
  23859. When using relative expressions, the following symbols are available:
  23860. - "left", "right", "top", "bottom" refer to the position of those edges in this component, so
  23861. e.g. for a component whose width is always 100, you might set the right edge to the "left + 100".
  23862. - "[id].left", "[id].right", "[id].top", "[id].bottom", "[id].width", "[id].height", where [id] is
  23863. the identifier of one of this component's siblings. A component's identifier is set with
  23864. Component::setComponentID(). So for example if you want your component to always be 50 pixels to the
  23865. right of the one called "xyz", you could set your left edge to be "xyz.right + 50".
  23866. - Instead of an [id], you can use the name "parent" to refer to this component's parent. Like
  23867. any other component, these values are relative to their component's parent, so "parent.right" won't be
  23868. very useful for positioning a component because it refers to a position with the parent's parent.. but
  23869. "parent.width" can be used for setting positions relative to the parent's size. E.g. to make a 10x10
  23870. component which remains 1 pixel away from its parent's bottom-right, you could use
  23871. "right - 10, bottom - 10, parent.width - 1, parent.height - 1".
  23872. - The name of one of the parent component's markers can also be used as a symbol. For markers to be
  23873. used, the parent component must implement its Component::getMarkers() method, and return at least one
  23874. valid MarkerList. So if you want your component's top edge to be 10 pixels below the
  23875. marker called "foobar", you'd set it to "foobar + 10".
  23876. See the Expression class for details about the operators that are supported, but for example
  23877. if you wanted to make your component remain centred within its parent with a size of 100, 100,
  23878. you could express it as:
  23879. @code myComp.setBounds (RelativeBounds ("parent.width / 2 - 50, parent.height / 2 - 50, left + 100, top + 100"));
  23880. @endcode
  23881. ..or an alternative way to achieve the same thing:
  23882. @code myComp.setBounds (RelativeBounds ("right - 100, bottom - 100, parent.width / 2 + 50, parent.height / 2 + 50"));
  23883. @endcode
  23884. Or if you wanted a 100x100 component whose top edge is lined up to a marker called "topMarker" and
  23885. which is positioned 50 pixels to the right of another component called "otherComp", you could write:
  23886. @code myComp.setBounds (RelativeBounds ("otherComp.right + 50, topMarker, left + 100, top + 100"));
  23887. @endcode
  23888. Be careful not to make your coordinate expressions recursive, though, or exceptions and assertions will
  23889. be thrown!
  23890. @see setBounds, RelativeRectangle::applyToComponent(), Expression
  23891. */
  23892. void setBounds (const RelativeRectangle& newBounds);
  23893. /** Sets the component's bounds with an expression.
  23894. The string is parsed as a RelativeRectangle expression - see the notes for
  23895. Component::setBounds (const RelativeRectangle&) for more information. This method is
  23896. basically just a shortcut for writing setBounds (RelativeRectangle ("..."))
  23897. */
  23898. void setBounds (const String& newBoundsExpression);
  23899. /** Changes the component's position and size in terms of fractions of its parent's size.
  23900. The values are factors of the parent's size, so for example
  23901. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  23902. width and height of the parent, with its top-left position 20% of
  23903. the way across and down the parent.
  23904. @see setBounds
  23905. */
  23906. void setBoundsRelative (float proportionalX, float proportionalY,
  23907. float proportionalWidth, float proportionalHeight);
  23908. /** Changes the component's position and size based on the amount of space to leave around it.
  23909. This will position the component within its parent, leaving the specified number of
  23910. pixels around each edge.
  23911. @see setBounds
  23912. */
  23913. void setBoundsInset (const BorderSize<int>& borders);
  23914. /** Positions the component within a given rectangle, keeping its proportions
  23915. unchanged.
  23916. If onlyReduceInSize is false, the component will be resized to fill as much of the
  23917. rectangle as possible without changing its aspect ratio (the component's
  23918. current size is used to determine its aspect ratio, so a zero-size component
  23919. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  23920. too big to fit inside the rectangle.
  23921. It will then be positioned within the rectangle according to the justification flags
  23922. specified.
  23923. @see setBounds
  23924. */
  23925. void setBoundsToFit (int x, int y, int width, int height,
  23926. const Justification& justification,
  23927. bool onlyReduceInSize);
  23928. /** Changes the position of the component's centre.
  23929. Leaves the component's size unchanged, but sets the position of its centre
  23930. relative to its parent's top-left.
  23931. @see setBounds
  23932. */
  23933. void setCentrePosition (int x, int y);
  23934. /** Changes the position of the component's centre.
  23935. Leaves the position unchanged, but positions its centre relative to its
  23936. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  23937. its parent.
  23938. */
  23939. void setCentreRelative (float x, float y);
  23940. /** Changes the component's size and centres it within its parent.
  23941. After changing the size, the component will be moved so that it's
  23942. centred within its parent. If the component is on the desktop (or has no
  23943. parent component), then it'll be centred within the main monitor area.
  23944. */
  23945. void centreWithSize (int width, int height);
  23946. /** Sets a transform matrix to be applied to this component.
  23947. If you set a transform for a component, the component's position will be warped by it, relative to
  23948. the component's parent's top-left origin. This means that the values you pass into setBounds() will no
  23949. longer reflect the actual area within the parent that the component covers, as the bounds will be
  23950. transformed and the component will probably end up actually appearing somewhere else within its parent.
  23951. When using transforms you need to be extremely careful when converting coordinates between the
  23952. coordinate spaces of different components or the screen - you should always use getLocalPoint(),
  23953. getLocalArea(), etc to do this, and never just manually add a component's position to a point in order to
  23954. convert it between different components (but I'm sure you would never have done that anyway...).
  23955. Currently, transforms are not supported for desktop windows, so the transform will be ignored if you
  23956. put a component on the desktop.
  23957. To remove a component's transform, simply pass AffineTransform::identity as the parameter to this method.
  23958. */
  23959. void setTransform (const AffineTransform& transform);
  23960. /** Returns the transform that is currently being applied to this component.
  23961. For more details about transforms, see setTransform().
  23962. @see setTransform
  23963. */
  23964. const AffineTransform getTransform() const;
  23965. /** Returns true if a non-identity transform is being applied to this component.
  23966. For more details about transforms, see setTransform().
  23967. @see setTransform
  23968. */
  23969. bool isTransformed() const noexcept;
  23970. /** Returns a proportion of the component's width.
  23971. This is a handy equivalent of (getWidth() * proportion).
  23972. */
  23973. int proportionOfWidth (float proportion) const noexcept;
  23974. /** Returns a proportion of the component's height.
  23975. This is a handy equivalent of (getHeight() * proportion).
  23976. */
  23977. int proportionOfHeight (float proportion) const noexcept;
  23978. /** Returns the width of the component's parent.
  23979. If the component has no parent (i.e. if it's on the desktop), this will return
  23980. the width of the screen.
  23981. */
  23982. int getParentWidth() const noexcept;
  23983. /** Returns the height of the component's parent.
  23984. If the component has no parent (i.e. if it's on the desktop), this will return
  23985. the height of the screen.
  23986. */
  23987. int getParentHeight() const noexcept;
  23988. /** Returns the screen coordinates of the monitor that contains this component.
  23989. If there's only one monitor, this will return its size - if there are multiple
  23990. monitors, it will return the area of the monitor that contains the component's
  23991. centre.
  23992. */
  23993. const Rectangle<int> getParentMonitorArea() const;
  23994. /** Returns the number of child components that this component contains.
  23995. @see getChildComponent, getIndexOfChildComponent
  23996. */
  23997. int getNumChildComponents() const noexcept;
  23998. /** Returns one of this component's child components, by it index.
  23999. The component with index 0 is at the back of the z-order, the one at the
  24000. front will have index (getNumChildComponents() - 1).
  24001. If the index is out-of-range, this will return a null pointer.
  24002. @see getNumChildComponents, getIndexOfChildComponent
  24003. */
  24004. Component* getChildComponent (int index) const noexcept;
  24005. /** Returns the index of this component in the list of child components.
  24006. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  24007. values are further towards the front.
  24008. Returns -1 if the component passed-in is not a child of this component.
  24009. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  24010. */
  24011. int getIndexOfChildComponent (const Component* child) const noexcept;
  24012. /** Adds a child component to this one.
  24013. Adding a child component does not mean that the component will own or delete the child - it's
  24014. your responsibility to delete the component. Note that it's safe to delete a component
  24015. without first removing it from its parent - doing so will automatically remove it and
  24016. send out the appropriate notifications before the deletion completes.
  24017. If the child is already a child of this component, then no action will be taken, and its
  24018. z-order will be left unchanged.
  24019. @param child the new component to add. If the component passed-in is already
  24020. the child of another component, it'll first be removed from it current parent.
  24021. @param zOrder The index in the child-list at which this component should be inserted.
  24022. A value of -1 will insert it in front of the others, 0 is the back.
  24023. @see removeChildComponent, addAndMakeVisible, getChild, ComponentListener::componentChildrenChanged
  24024. */
  24025. void addChildComponent (Component* child, int zOrder = -1);
  24026. /** Adds a child component to this one, and also makes the child visible if it isn't.
  24027. Quite a useful function, this is just the same as calling setVisible (true) on the child
  24028. and then addChildComponent(). See addChildComponent() for more details.
  24029. */
  24030. void addAndMakeVisible (Component* child, int zOrder = -1);
  24031. /** Removes one of this component's child-components.
  24032. If the child passed-in isn't actually a child of this component (either because
  24033. it's invalid or is the child of a different parent), then no action is taken.
  24034. Note that removing a child will not delete it! But it's ok to delete a component
  24035. without first removing it - doing so will automatically remove it and send out the
  24036. appropriate notifications before the deletion completes.
  24037. @see addChildComponent, ComponentListener::componentChildrenChanged
  24038. */
  24039. void removeChildComponent (Component* childToRemove);
  24040. /** Removes one of this component's child-components by index.
  24041. This will return a pointer to the component that was removed, or null if
  24042. the index was out-of-range.
  24043. Note that removing a child will not delete it! But it's ok to delete a component
  24044. without first removing it - doing so will automatically remove it and send out the
  24045. appropriate notifications before the deletion completes.
  24046. @see addChildComponent, ComponentListener::componentChildrenChanged
  24047. */
  24048. Component* removeChildComponent (int childIndexToRemove);
  24049. /** Removes all this component's children.
  24050. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  24051. */
  24052. void removeAllChildren();
  24053. /** Removes all this component's children, and deletes them.
  24054. @see removeAllChildren
  24055. */
  24056. void deleteAllChildren();
  24057. /** Returns the component which this component is inside.
  24058. If this is the highest-level component or hasn't yet been added to
  24059. a parent, this will return null.
  24060. */
  24061. Component* getParentComponent() const noexcept { return parentComponent; }
  24062. /** Searches the parent components for a component of a specified class.
  24063. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  24064. component that can be dynamically cast to a MyComp, or will return 0 if none
  24065. of the parents are suitable.
  24066. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  24067. */
  24068. template <class TargetClass>
  24069. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = nullptr) const
  24070. {
  24071. (void) dummyParameter;
  24072. Component* p = parentComponent;
  24073. while (p != nullptr)
  24074. {
  24075. TargetClass* target = dynamic_cast <TargetClass*> (p);
  24076. if (target != nullptr)
  24077. return target;
  24078. p = p->parentComponent;
  24079. }
  24080. return nullptr;
  24081. }
  24082. /** Returns the highest-level component which contains this one or its parents.
  24083. This will search upwards in the parent-hierarchy from this component, until it
  24084. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  24085. not yet added to a parent), and will return that.
  24086. */
  24087. Component* getTopLevelComponent() const noexcept;
  24088. /** Checks whether a component is anywhere inside this component or its children.
  24089. This will recursively check through this component's children to see if the
  24090. given component is anywhere inside.
  24091. */
  24092. bool isParentOf (const Component* possibleChild) const noexcept;
  24093. /** Called to indicate that the component's parents have changed.
  24094. When a component is added or removed from its parent, this method will
  24095. be called on all of its children (recursively - so all children of its
  24096. children will also be called as well).
  24097. Subclasses can override this if they need to react to this in some way.
  24098. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  24099. */
  24100. virtual void parentHierarchyChanged();
  24101. /** Subclasses can use this callback to be told when children are added or removed.
  24102. @see parentHierarchyChanged
  24103. */
  24104. virtual void childrenChanged();
  24105. /** Tests whether a given point inside the component.
  24106. Overriding this method allows you to create components which only intercept
  24107. mouse-clicks within a user-defined area.
  24108. This is called to find out whether a particular x, y coordinate is
  24109. considered to be inside the component or not, and is used by methods such
  24110. as contains() and getComponentAt() to work out which component
  24111. the mouse is clicked on.
  24112. Components with custom shapes will probably want to override it to perform
  24113. some more complex hit-testing.
  24114. The default implementation of this method returns either true or false,
  24115. depending on the value that was set by calling setInterceptsMouseClicks() (true
  24116. is the default return value).
  24117. Note that the hit-test region is not related to the opacity with which
  24118. areas of a component are painted.
  24119. Applications should never call hitTest() directly - instead use the
  24120. contains() method, because this will also test for occlusion by the
  24121. component's parent.
  24122. Note that for components on the desktop, this method will be ignored, because it's
  24123. not always possible to implement this behaviour on all platforms.
  24124. @param x the x coordinate to test, relative to the left hand edge of this
  24125. component. This value is guaranteed to be greater than or equal to
  24126. zero, and less than the component's width
  24127. @param y the y coordinate to test, relative to the top edge of this
  24128. component. This value is guaranteed to be greater than or equal to
  24129. zero, and less than the component's height
  24130. @returns true if the click is considered to be inside the component
  24131. @see setInterceptsMouseClicks, contains
  24132. */
  24133. virtual bool hitTest (int x, int y);
  24134. /** Changes the default return value for the hitTest() method.
  24135. Setting this to false is an easy way to make a component pass its mouse-clicks
  24136. through to the components behind it.
  24137. When a component is created, the default setting for this is true.
  24138. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  24139. return false (or true for child components if allowClicksOnChildComponents
  24140. is true)
  24141. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  24142. components can be clicked on as normal but clicks on this component pass
  24143. straight through; if this is false and allowClicksOnThisComponent
  24144. is false, then neither this component nor any child components can
  24145. be clicked on
  24146. @see hitTest, getInterceptsMouseClicks
  24147. */
  24148. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  24149. bool allowClicksOnChildComponents) noexcept;
  24150. /** Retrieves the current state of the mouse-click interception flags.
  24151. On return, the two parameters are set to the state used in the last call to
  24152. setInterceptsMouseClicks().
  24153. @see setInterceptsMouseClicks
  24154. */
  24155. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  24156. bool& allowsClicksOnChildComponents) const noexcept;
  24157. /** Returns true if a given point lies within this component or one of its children.
  24158. Never override this method! Use hitTest to create custom hit regions.
  24159. @param localPoint the coordinate to test, relative to this component's top-left.
  24160. @returns true if the point is within the component's hit-test area, but only if
  24161. that part of the component isn't clipped by its parent component. Note
  24162. that this won't take into account any overlapping sibling components
  24163. which might be in the way - for that, see reallyContains()
  24164. @see hitTest, reallyContains, getComponentAt
  24165. */
  24166. bool contains (const Point<int>& localPoint);
  24167. /** Returns true if a given point lies in this component, taking any overlapping
  24168. siblings into account.
  24169. @param localPoint the coordinate to test, relative to this component's top-left.
  24170. @param returnTrueIfWithinAChild if the point actually lies within a child of this component,
  24171. this determines whether that is counted as a hit.
  24172. @see contains, getComponentAt
  24173. */
  24174. bool reallyContains (const Point<int>& localPoint, bool returnTrueIfWithinAChild);
  24175. /** Returns the component at a certain point within this one.
  24176. @param x the x coordinate to test, relative to this component's left edge.
  24177. @param y the y coordinate to test, relative to this component's top edge.
  24178. @returns the component that is at this position - which may be 0, this component,
  24179. or one of its children. Note that overlapping siblings that might actually
  24180. be in the way are not taken into account by this method - to account for these,
  24181. instead call getComponentAt on the top-level parent of this component.
  24182. @see hitTest, contains, reallyContains
  24183. */
  24184. Component* getComponentAt (int x, int y);
  24185. /** Returns the component at a certain point within this one.
  24186. @param position the coordinate to test, relative to this component's top-left.
  24187. @returns the component that is at this position - which may be 0, this component,
  24188. or one of its children. Note that overlapping siblings that might actually
  24189. be in the way are not taken into account by this method - to account for these,
  24190. instead call getComponentAt on the top-level parent of this component.
  24191. @see hitTest, contains, reallyContains
  24192. */
  24193. Component* getComponentAt (const Point<int>& position);
  24194. /** Marks the whole component as needing to be redrawn.
  24195. Calling this will not do any repainting immediately, but will mark the component
  24196. as 'dirty'. At some point in the near future the operating system will send a paint
  24197. message, which will redraw all the dirty regions of all components.
  24198. There's no guarantee about how soon after calling repaint() the redraw will actually
  24199. happen, and other queued events may be delivered before a redraw is done.
  24200. If the setBufferedToImage() method has been used to cause this component
  24201. to use a buffer, the repaint() call will invalidate the component's buffer.
  24202. To redraw just a subsection of the component rather than the whole thing,
  24203. use the repaint (int, int, int, int) method.
  24204. @see paint
  24205. */
  24206. void repaint();
  24207. /** Marks a subsection of this component as needing to be redrawn.
  24208. Calling this will not do any repainting immediately, but will mark the given region
  24209. of the component as 'dirty'. At some point in the near future the operating system
  24210. will send a paint message, which will redraw all the dirty regions of all components.
  24211. There's no guarantee about how soon after calling repaint() the redraw will actually
  24212. happen, and other queued events may be delivered before a redraw is done.
  24213. The region that is passed in will be clipped to keep it within the bounds of this
  24214. component.
  24215. @see repaint()
  24216. */
  24217. void repaint (int x, int y, int width, int height);
  24218. /** Marks a subsection of this component as needing to be redrawn.
  24219. Calling this will not do any repainting immediately, but will mark the given region
  24220. of the component as 'dirty'. At some point in the near future the operating system
  24221. will send a paint message, which will redraw all the dirty regions of all components.
  24222. There's no guarantee about how soon after calling repaint() the redraw will actually
  24223. happen, and other queued events may be delivered before a redraw is done.
  24224. The region that is passed in will be clipped to keep it within the bounds of this
  24225. component.
  24226. @see repaint()
  24227. */
  24228. void repaint (const Rectangle<int>& area);
  24229. /** Makes the component use an internal buffer to optimise its redrawing.
  24230. Setting this flag to true will cause the component to allocate an
  24231. internal buffer into which it paints itself, so that when asked to
  24232. redraw itself, it can use this buffer rather than actually calling the
  24233. paint() method.
  24234. The buffer is kept until the repaint() method is called directly on
  24235. this component (or until it is resized), when the image is invalidated
  24236. and then redrawn the next time the component is painted.
  24237. Note that only the drawing that happens within the component's paint()
  24238. method is drawn into the buffer, it's child components are not buffered, and
  24239. nor is the paintOverChildren() method.
  24240. @see repaint, paint, createComponentSnapshot
  24241. */
  24242. void setBufferedToImage (bool shouldBeBuffered);
  24243. /** Generates a snapshot of part of this component.
  24244. This will return a new Image, the size of the rectangle specified,
  24245. containing a snapshot of the specified area of the component and all
  24246. its children.
  24247. The image may or may not have an alpha-channel, depending on whether the
  24248. image is opaque or not.
  24249. If the clipImageToComponentBounds parameter is true and the area is greater than
  24250. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  24251. then parts of the component beyond its bounds can be drawn.
  24252. @see paintEntireComponent
  24253. */
  24254. const Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  24255. bool clipImageToComponentBounds = true);
  24256. /** Draws this component and all its subcomponents onto the specified graphics
  24257. context.
  24258. You should very rarely have to use this method, it's simply there in case you need
  24259. to draw a component with a custom graphics context for some reason, e.g. for
  24260. creating a snapshot of the component.
  24261. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  24262. on its children in order to render the entire tree.
  24263. The graphics context may be left in an undefined state after this method returns,
  24264. so you may need to reset it if you're going to use it again.
  24265. If ignoreAlphaLevel is false, then the component will be drawn with the opacity level
  24266. specified by getAlpha(); if ignoreAlphaLevel is true, then this will be ignored and
  24267. an alpha of 1.0 will be used.
  24268. */
  24269. void paintEntireComponent (Graphics& context, bool ignoreAlphaLevel);
  24270. /** This allows you to indicate that this component doesn't require its graphics
  24271. context to be clipped when it is being painted.
  24272. Most people will never need to use this setting, but in situations where you have a very large
  24273. number of simple components being rendered, and where they are guaranteed never to do any drawing
  24274. beyond their own boundaries, setting this to true will reduce the overhead involved in clipping
  24275. the graphics context that gets passed to the component's paint() callback.
  24276. If you enable this mode, you'll need to make sure your paint method doesn't call anything like
  24277. Graphics::fillAll(), and doesn't draw beyond the component's bounds, because that'll produce
  24278. artifacts. Your component also can't have any child components that may be placed beyond its
  24279. bounds.
  24280. */
  24281. void setPaintingIsUnclipped (bool shouldPaintWithoutClipping) noexcept;
  24282. /** Adds an effect filter to alter the component's appearance.
  24283. When a component has an effect filter set, then this is applied to the
  24284. results of its paint() method. There are a few preset effects, such as
  24285. a drop-shadow or glow, but they can be user-defined as well.
  24286. The effect that is passed in will not be deleted by the component - the
  24287. caller must take care of deleting it.
  24288. To remove an effect from a component, pass a null pointer in as the parameter.
  24289. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  24290. */
  24291. void setComponentEffect (ImageEffectFilter* newEffect);
  24292. /** Returns the current component effect.
  24293. @see setComponentEffect
  24294. */
  24295. ImageEffectFilter* getComponentEffect() const noexcept { return effect; }
  24296. /** Finds the appropriate look-and-feel to use for this component.
  24297. If the component hasn't had a look-and-feel explicitly set, this will
  24298. return the parent's look-and-feel, or just the default one if there's no
  24299. parent.
  24300. @see setLookAndFeel, lookAndFeelChanged
  24301. */
  24302. LookAndFeel& getLookAndFeel() const noexcept;
  24303. /** Sets the look and feel to use for this component.
  24304. This will also change the look and feel for any child components that haven't
  24305. had their look set explicitly.
  24306. The object passed in will not be deleted by the component, so it's the caller's
  24307. responsibility to manage it. It may be used at any time until this component
  24308. has been deleted.
  24309. Calling this method will also invoke the sendLookAndFeelChange() method.
  24310. @see getLookAndFeel, lookAndFeelChanged
  24311. */
  24312. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  24313. /** Called to let the component react to a change in the look-and-feel setting.
  24314. When the look-and-feel is changed for a component, this will be called in
  24315. all its child components, recursively.
  24316. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  24317. an application uses a LookAndFeel class that might have changed internally.
  24318. @see sendLookAndFeelChange, getLookAndFeel
  24319. */
  24320. virtual void lookAndFeelChanged();
  24321. /** Calls the lookAndFeelChanged() method in this component and all its children.
  24322. This will recurse through the children and their children, calling lookAndFeelChanged()
  24323. on them all.
  24324. @see lookAndFeelChanged
  24325. */
  24326. void sendLookAndFeelChange();
  24327. /** Indicates whether any parts of the component might be transparent.
  24328. Components that always paint all of their contents with solid colour and
  24329. thus completely cover any components behind them should use this method
  24330. to tell the repaint system that they are opaque.
  24331. This information is used to optimise drawing, because it means that
  24332. objects underneath opaque windows don't need to be painted.
  24333. By default, components are considered transparent, unless this is used to
  24334. make it otherwise.
  24335. @see isOpaque, getVisibleArea
  24336. */
  24337. void setOpaque (bool shouldBeOpaque);
  24338. /** Returns true if no parts of this component are transparent.
  24339. @returns the value that was set by setOpaque, (the default being false)
  24340. @see setOpaque
  24341. */
  24342. bool isOpaque() const noexcept;
  24343. /** Indicates whether the component should be brought to the front when clicked.
  24344. Setting this flag to true will cause the component to be brought to the front
  24345. when the mouse is clicked somewhere inside it or its child components.
  24346. Note that a top-level desktop window might still be brought to the front by the
  24347. operating system when it's clicked, depending on how the OS works.
  24348. By default this is set to false.
  24349. @see setMouseClickGrabsKeyboardFocus
  24350. */
  24351. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) noexcept;
  24352. /** Indicates whether the component should be brought to the front when clicked-on.
  24353. @see setBroughtToFrontOnMouseClick
  24354. */
  24355. bool isBroughtToFrontOnMouseClick() const noexcept;
  24356. // Keyboard focus methods
  24357. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  24358. By default components aren't actually interested in gaining the
  24359. focus, but this method can be used to turn this on.
  24360. See the grabKeyboardFocus() method for details about the way a component
  24361. is chosen to receive the focus.
  24362. @see grabKeyboardFocus, getWantsKeyboardFocus
  24363. */
  24364. void setWantsKeyboardFocus (bool wantsFocus) noexcept;
  24365. /** Returns true if the component is interested in getting keyboard focus.
  24366. This returns the flag set by setWantsKeyboardFocus(). The default
  24367. setting is false.
  24368. @see setWantsKeyboardFocus
  24369. */
  24370. bool getWantsKeyboardFocus() const noexcept;
  24371. /** Chooses whether a click on this component automatically grabs the focus.
  24372. By default this is set to true, but you might want a component which can
  24373. be focused, but where you don't want the user to be able to affect it directly
  24374. by clicking.
  24375. */
  24376. void setMouseClickGrabsKeyboardFocus (bool shouldGrabFocus);
  24377. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  24378. See setMouseClickGrabsKeyboardFocus() for more info.
  24379. */
  24380. bool getMouseClickGrabsKeyboardFocus() const noexcept;
  24381. /** Tries to give keyboard focus to this component.
  24382. When the user clicks on a component or its grabKeyboardFocus()
  24383. method is called, the following procedure is used to work out which
  24384. component should get it:
  24385. - if the component that was clicked on actually wants focus (as indicated
  24386. by calling getWantsKeyboardFocus), it gets it.
  24387. - if the component itself doesn't want focus, it will try to pass it
  24388. on to whichever of its children is the default component, as determined by
  24389. KeyboardFocusTraverser::getDefaultComponent()
  24390. - if none of its children want focus at all, it will pass it up to its
  24391. parent instead, unless it's a top-level component without a parent,
  24392. in which case it just takes the focus itself.
  24393. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  24394. getCurrentlyFocusedComponent, focusGained, focusLost,
  24395. keyPressed, keyStateChanged
  24396. */
  24397. void grabKeyboardFocus();
  24398. /** Returns true if this component currently has the keyboard focus.
  24399. @param trueIfChildIsFocused if this is true, then the method returns true if
  24400. either this component or any of its children (recursively)
  24401. have the focus. If false, the method only returns true if
  24402. this component has the focus.
  24403. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  24404. focusGained, focusLost
  24405. */
  24406. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  24407. /** Returns the component that currently has the keyboard focus.
  24408. @returns the focused component, or null if nothing is focused.
  24409. */
  24410. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() noexcept;
  24411. /** Tries to move the keyboard focus to one of this component's siblings.
  24412. This will try to move focus to either the next or previous component. (This
  24413. is the method that is used when shifting focus by pressing the tab key).
  24414. Components for which getWantsKeyboardFocus() returns false are not looked at.
  24415. @param moveToNext if true, the focus will move forwards; if false, it will
  24416. move backwards
  24417. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  24418. */
  24419. void moveKeyboardFocusToSibling (bool moveToNext);
  24420. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  24421. which focus should be passed from this component.
  24422. The default implementation of this method will return a default
  24423. KeyboardFocusTraverser if this component is a focus container (as determined
  24424. by the setFocusContainer() method). If the component isn't a focus
  24425. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  24426. If you overrride this to return a custom KeyboardFocusTraverser, then
  24427. this component and all its sub-components will use the new object to
  24428. make their focusing decisions.
  24429. The method should return a new object, which the caller is required to
  24430. delete when no longer needed.
  24431. */
  24432. virtual KeyboardFocusTraverser* createFocusTraverser();
  24433. /** Returns the focus order of this component, if one has been specified.
  24434. By default components don't have a focus order - in that case, this
  24435. will return 0. Lower numbers indicate that the component will be
  24436. earlier in the focus traversal order.
  24437. To change the order, call setExplicitFocusOrder().
  24438. The focus order may be used by the KeyboardFocusTraverser class as part of
  24439. its algorithm for deciding the order in which components should be traversed.
  24440. See the KeyboardFocusTraverser class for more details on this.
  24441. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  24442. */
  24443. int getExplicitFocusOrder() const;
  24444. /** Sets the index used in determining the order in which focusable components
  24445. should be traversed.
  24446. A value of 0 or less is taken to mean that no explicit order is wanted, and
  24447. that traversal should use other factors, like the component's position.
  24448. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  24449. */
  24450. void setExplicitFocusOrder (int newFocusOrderIndex);
  24451. /** Indicates whether this component is a parent for components that can have
  24452. their focus traversed.
  24453. This flag is used by the default implementation of the createFocusTraverser()
  24454. method, which uses the flag to find the first parent component (of the currently
  24455. focused one) which wants to be a focus container.
  24456. So using this method to set the flag to 'true' causes this component to
  24457. act as the top level within which focus is passed around.
  24458. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  24459. */
  24460. void setFocusContainer (bool shouldBeFocusContainer) noexcept;
  24461. /** Returns true if this component has been marked as a focus container.
  24462. See setFocusContainer() for more details.
  24463. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  24464. */
  24465. bool isFocusContainer() const noexcept;
  24466. /** Returns true if the component (and all its parents) are enabled.
  24467. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  24468. what difference this makes to the component depends on the type. E.g. buttons
  24469. and sliders will choose to draw themselves differently, etc.
  24470. Note that if one of this component's parents is disabled, this will always
  24471. return false, even if this component itself is enabled.
  24472. @see setEnabled, enablementChanged
  24473. */
  24474. bool isEnabled() const noexcept;
  24475. /** Enables or disables this component.
  24476. Disabling a component will also cause all of its child components to become
  24477. disabled.
  24478. Similarly, enabling a component which is inside a disabled parent
  24479. component won't make any difference until the parent is re-enabled.
  24480. @see isEnabled, enablementChanged
  24481. */
  24482. void setEnabled (bool shouldBeEnabled);
  24483. /** Callback to indicate that this component has been enabled or disabled.
  24484. This can be triggered by one of the component's parent components
  24485. being enabled or disabled, as well as changes to the component itself.
  24486. The default implementation of this method does nothing; your class may
  24487. wish to repaint itself or something when this happens.
  24488. @see setEnabled, isEnabled
  24489. */
  24490. virtual void enablementChanged();
  24491. /** Changes the transparency of this component.
  24492. When painted, the entire component and all its children will be rendered
  24493. with this as the overall opacity level, where 0 is completely invisible, and
  24494. 1.0 is fully opaque (i.e. normal).
  24495. @see getAlpha
  24496. */
  24497. void setAlpha (float newAlpha);
  24498. /** Returns the component's current transparancy level.
  24499. See setAlpha() for more details.
  24500. */
  24501. float getAlpha() const;
  24502. /** Changes the mouse cursor shape to use when the mouse is over this component.
  24503. Note that the cursor set by this method can be overridden by the getMouseCursor
  24504. method.
  24505. @see MouseCursor
  24506. */
  24507. void setMouseCursor (const MouseCursor& cursorType);
  24508. /** Returns the mouse cursor shape to use when the mouse is over this component.
  24509. The default implementation will return the cursor that was set by setCursor()
  24510. but can be overridden for more specialised purposes, e.g. returning different
  24511. cursors depending on the mouse position.
  24512. @see MouseCursor
  24513. */
  24514. virtual const MouseCursor getMouseCursor();
  24515. /** Forces the current mouse cursor to be updated.
  24516. If you're overriding the getMouseCursor() method to control which cursor is
  24517. displayed, then this will only be checked each time the user moves the mouse. So
  24518. if you want to force the system to check that the cursor being displayed is
  24519. up-to-date (even if the mouse is just sitting there), call this method.
  24520. (If you're changing the cursor using setMouseCursor(), you don't need to bother
  24521. calling this).
  24522. */
  24523. void updateMouseCursor() const;
  24524. /** Components can override this method to draw their content.
  24525. The paint() method gets called when a region of a component needs redrawing,
  24526. either because the component's repaint() method has been called, or because
  24527. something has happened on the screen that means a section of a window needs
  24528. to be redrawn.
  24529. Any child components will draw themselves over whatever this method draws. If
  24530. you need to paint over the top of your child components, you can also implement
  24531. the paintOverChildren() method to do this.
  24532. If you want to cause a component to redraw itself, this is done asynchronously -
  24533. calling the repaint() method marks a region of the component as "dirty", and the
  24534. paint() method will automatically be called sometime later, by the message thread,
  24535. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  24536. you never redraw something synchronously.
  24537. You should never need to call this method directly - to take a snapshot of the
  24538. component you could use createComponentSnapshot() or paintEntireComponent().
  24539. @param g the graphics context that must be used to do the drawing operations.
  24540. @see repaint, paintOverChildren, Graphics
  24541. */
  24542. virtual void paint (Graphics& g);
  24543. /** Components can override this method to draw over the top of their children.
  24544. For most drawing operations, it's better to use the normal paint() method,
  24545. but if you need to overlay something on top of the children, this can be
  24546. used.
  24547. @see paint, Graphics
  24548. */
  24549. virtual void paintOverChildren (Graphics& g);
  24550. /** Called when the mouse moves inside this component.
  24551. If the mouse button isn't pressed and the mouse moves over a component,
  24552. this will be called to let the component react to this.
  24553. A component will always get a mouseEnter callback before a mouseMove.
  24554. @param e details about the position and status of the mouse event
  24555. @see mouseEnter, mouseExit, mouseDrag, contains
  24556. */
  24557. virtual void mouseMove (const MouseEvent& e);
  24558. /** Called when the mouse first enters this component.
  24559. If the mouse button isn't pressed and the mouse moves into a component,
  24560. this will be called to let the component react to this.
  24561. When the mouse button is pressed and held down while being moved in
  24562. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  24563. mouseDrag messages are sent to the component that the mouse was originally
  24564. clicked on, until the button is released.
  24565. If you're writing a component that needs to repaint itself when the mouse
  24566. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  24567. method.
  24568. @param e details about the position and status of the mouse event
  24569. @see mouseExit, mouseDrag, mouseMove, contains
  24570. */
  24571. virtual void mouseEnter (const MouseEvent& e);
  24572. /** Called when the mouse moves out of this component.
  24573. This will be called when the mouse moves off the edge of this
  24574. component.
  24575. If the mouse button was pressed, and it was then dragged off the
  24576. edge of the component and released, then this callback will happen
  24577. when the button is released, after the mouseUp callback.
  24578. If you're writing a component that needs to repaint itself when the mouse
  24579. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  24580. method.
  24581. @param e details about the position and status of the mouse event
  24582. @see mouseEnter, mouseDrag, mouseMove, contains
  24583. */
  24584. virtual void mouseExit (const MouseEvent& e);
  24585. /** Called when a mouse button is pressed while it's over this component.
  24586. The MouseEvent object passed in contains lots of methods for finding out
  24587. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  24588. were held down at the time.
  24589. Once a button is held down, the mouseDrag method will be called when the
  24590. mouse moves, until the button is released.
  24591. @param e details about the position and status of the mouse event
  24592. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  24593. */
  24594. virtual void mouseDown (const MouseEvent& e);
  24595. /** Called when the mouse is moved while a button is held down.
  24596. When a mouse button is pressed inside a component, that component
  24597. receives mouseDrag callbacks each time the mouse moves, even if the
  24598. mouse strays outside the component's bounds.
  24599. If you want to be able to drag things off the edge of a component
  24600. and have the component scroll when you get to the edges, the
  24601. beginDragAutoRepeat() method might be useful.
  24602. @param e details about the position and status of the mouse event
  24603. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  24604. */
  24605. virtual void mouseDrag (const MouseEvent& e);
  24606. /** Called when a mouse button is released.
  24607. A mouseUp callback is sent to the component in which a button was pressed
  24608. even if the mouse is actually over a different component when the
  24609. button is released.
  24610. The MouseEvent object passed in contains lots of methods for finding out
  24611. which buttons were down just before they were released.
  24612. @param e details about the position and status of the mouse event
  24613. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  24614. */
  24615. virtual void mouseUp (const MouseEvent& e);
  24616. /** Called when a mouse button has been double-clicked in this component.
  24617. The MouseEvent object passed in contains lots of methods for finding out
  24618. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  24619. were held down at the time.
  24620. For altering the time limit used to detect double-clicks,
  24621. see MouseEvent::setDoubleClickTimeout.
  24622. @param e details about the position and status of the mouse event
  24623. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  24624. MouseEvent::getDoubleClickTimeout
  24625. */
  24626. virtual void mouseDoubleClick (const MouseEvent& e);
  24627. /** Called when the mouse-wheel is moved.
  24628. This callback is sent to the component that the mouse is over when the
  24629. wheel is moved.
  24630. If not overridden, the component will forward this message to its parent, so
  24631. that parent components can collect mouse-wheel messages that happen to
  24632. child components which aren't interested in them.
  24633. @param e details about the position and status of the mouse event
  24634. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  24635. value means the wheel has been pushed to the right, negative means it
  24636. was pushed to the left
  24637. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  24638. value means the wheel has been pushed upwards, negative means it
  24639. was pushed downwards
  24640. */
  24641. virtual void mouseWheelMove (const MouseEvent& e,
  24642. float wheelIncrementX,
  24643. float wheelIncrementY);
  24644. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  24645. current mouse-drag operation.
  24646. This allows you to make sure that mouseDrag() events are sent continuously, even
  24647. when the mouse isn't moving. This can be useful for things like auto-scrolling
  24648. components when the mouse is near an edge.
  24649. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  24650. minimum interval between consecutive mouse drag callbacks. The callbacks
  24651. will continue until the mouse is released, and then the interval will be reset,
  24652. so you need to make sure it's called every time you begin a drag event.
  24653. Passing an interval of 0 or less will cancel the auto-repeat.
  24654. @see mouseDrag, Desktop::beginDragAutoRepeat
  24655. */
  24656. static void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  24657. /** Causes automatic repaints when the mouse enters or exits this component.
  24658. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  24659. on the component, it will trigger a repaint.
  24660. This is handy for things like buttons that need to draw themselves differently when
  24661. the mouse moves over them, and it avoids having to override all the different mouse
  24662. callbacks and call repaint().
  24663. @see mouseEnter, mouseExit, mouseDown, mouseUp
  24664. */
  24665. void setRepaintsOnMouseActivity (bool shouldRepaint) noexcept;
  24666. /** Registers a listener to be told when mouse events occur in this component.
  24667. If you need to get informed about mouse events in a component but can't or
  24668. don't want to override its methods, you can attach any number of listeners
  24669. to the component, and these will get told about the events in addition to
  24670. the component's own callbacks being called.
  24671. Note that a MouseListener can also be attached to more than one component.
  24672. @param newListener the listener to register
  24673. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  24674. for events that happen to any child component
  24675. within this component, including deeply-nested
  24676. child components. If false, it will only be
  24677. told about events that this component handles.
  24678. @see MouseListener, removeMouseListener
  24679. */
  24680. void addMouseListener (MouseListener* newListener,
  24681. bool wantsEventsForAllNestedChildComponents);
  24682. /** Deregisters a mouse listener.
  24683. @see addMouseListener, MouseListener
  24684. */
  24685. void removeMouseListener (MouseListener* listenerToRemove);
  24686. /** Adds a listener that wants to hear about keypresses that this component receives.
  24687. The listeners that are registered with a component are called by its keyPressed() or
  24688. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  24689. If you add an object as a key listener, be careful to remove it when the object
  24690. is deleted, or the component will be left with a dangling pointer.
  24691. @see keyPressed, keyStateChanged, removeKeyListener
  24692. */
  24693. void addKeyListener (KeyListener* newListener);
  24694. /** Removes a previously-registered key listener.
  24695. @see addKeyListener
  24696. */
  24697. void removeKeyListener (KeyListener* listenerToRemove);
  24698. /** Called when a key is pressed.
  24699. When a key is pressed, the component that has the keyboard focus will have this
  24700. method called. Remember that a component will only be given the focus if its
  24701. setWantsKeyboardFocus() method has been used to enable this.
  24702. If your implementation returns true, the event will be consumed and not passed
  24703. on to any other listeners. If it returns false, the key will be passed to any
  24704. KeyListeners that have been registered with this component. As soon as one of these
  24705. returns true, the process will stop, but if they all return false, the event will
  24706. be passed upwards to this component's parent, and so on.
  24707. The default implementation of this method does nothing and returns false.
  24708. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  24709. */
  24710. virtual bool keyPressed (const KeyPress& key);
  24711. /** Called when a key is pressed or released.
  24712. Whenever a key on the keyboard is pressed or released (including modifier keys
  24713. like shift and ctrl), this method will be called on the component that currently
  24714. has the keyboard focus. Remember that a component will only be given the focus if
  24715. its setWantsKeyboardFocus() method has been used to enable this.
  24716. If your implementation returns true, the event will be consumed and not passed
  24717. on to any other listeners. If it returns false, then any KeyListeners that have
  24718. been registered with this component will have their keyStateChanged methods called.
  24719. As soon as one of these returns true, the process will stop, but if they all return
  24720. false, the event will be passed upwards to this component's parent, and so on.
  24721. The default implementation of this method does nothing and returns false.
  24722. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  24723. method.
  24724. @param isKeyDown true if a key has been pressed; false if it has been released
  24725. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  24726. */
  24727. virtual bool keyStateChanged (bool isKeyDown);
  24728. /** Called when a modifier key is pressed or released.
  24729. Whenever the shift, control, alt or command keys are pressed or released,
  24730. this method will be called on the component that currently has the keyboard focus.
  24731. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  24732. method has been used to enable this.
  24733. The default implementation of this method actually calls its parent's modifierKeysChanged
  24734. method, so that focused components which aren't interested in this will give their
  24735. parents a chance to act on the event instead.
  24736. @see keyStateChanged, ModifierKeys
  24737. */
  24738. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  24739. /** Enumeration used by the focusChanged() and focusLost() methods. */
  24740. enum FocusChangeType
  24741. {
  24742. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  24743. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  24744. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  24745. };
  24746. /** Called to indicate that this component has just acquired the keyboard focus.
  24747. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24748. */
  24749. virtual void focusGained (FocusChangeType cause);
  24750. /** Called to indicate that this component has just lost the keyboard focus.
  24751. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24752. */
  24753. virtual void focusLost (FocusChangeType cause);
  24754. /** Called to indicate that one of this component's children has been focused or unfocused.
  24755. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  24756. changed. It happens when focus moves from one of this component's children (at any depth)
  24757. to a component that isn't contained in this one, (or vice-versa).
  24758. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24759. */
  24760. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  24761. /** Returns true if the mouse is currently over this component.
  24762. If the mouse isn't over the component, this will return false, even if the
  24763. mouse is currently being dragged - so you can use this in your mouseDrag
  24764. method to find out whether it's really over the component or not.
  24765. Note that when the mouse button is being held down, then the only component
  24766. for which this method will return true is the one that was originally
  24767. clicked on.
  24768. If includeChildren is true, then this will also return true if the mouse is over
  24769. any of the component's children (recursively) as well as the component itself.
  24770. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  24771. */
  24772. bool isMouseOver (bool includeChildren = false) const;
  24773. /** Returns true if the mouse button is currently held down in this component.
  24774. Note that this is a test to see whether the mouse is being pressed in this
  24775. component, so it'll return false if called on component A when the mouse
  24776. is actually being dragged in component B.
  24777. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  24778. */
  24779. bool isMouseButtonDown() const noexcept;
  24780. /** True if the mouse is over this component, or if it's being dragged in this component.
  24781. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  24782. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  24783. */
  24784. bool isMouseOverOrDragging() const noexcept;
  24785. /** Returns true if a mouse button is currently down.
  24786. Unlike isMouseButtonDown, this will test the current state of the
  24787. buttons without regard to which component (if any) it has been
  24788. pressed in.
  24789. @see isMouseButtonDown, ModifierKeys
  24790. */
  24791. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() noexcept;
  24792. /** Returns the mouse's current position, relative to this component.
  24793. The return value is relative to the component's top-left corner.
  24794. */
  24795. const Point<int> getMouseXYRelative() const;
  24796. /** Called when this component's size has been changed.
  24797. A component can implement this method to do things such as laying out its
  24798. child components when its width or height changes.
  24799. The method is called synchronously as a result of the setBounds or setSize
  24800. methods, so repeatedly changing a components size will repeatedly call its
  24801. resized method (unlike things like repainting, where multiple calls to repaint
  24802. are coalesced together).
  24803. If the component is a top-level window on the desktop, its size could also
  24804. be changed by operating-system factors beyond the application's control.
  24805. @see moved, setSize
  24806. */
  24807. virtual void resized();
  24808. /** Called when this component's position has been changed.
  24809. This is called when the position relative to its parent changes, not when
  24810. its absolute position on the screen changes (so it won't be called for
  24811. all child components when a parent component is moved).
  24812. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  24813. or any of the other repositioning methods, and like resized(), it will be
  24814. called each time those methods are called.
  24815. If the component is a top-level window on the desktop, its position could also
  24816. be changed by operating-system factors beyond the application's control.
  24817. @see resized, setBounds
  24818. */
  24819. virtual void moved();
  24820. /** Called when one of this component's children is moved or resized.
  24821. If the parent wants to know about changes to its immediate children (not
  24822. to children of its children), this is the method to override.
  24823. @see moved, resized, parentSizeChanged
  24824. */
  24825. virtual void childBoundsChanged (Component* child);
  24826. /** Called when this component's immediate parent has been resized.
  24827. If the component is a top-level window, this indicates that the screen size
  24828. has changed.
  24829. @see childBoundsChanged, moved, resized
  24830. */
  24831. virtual void parentSizeChanged();
  24832. /** Called when this component has been moved to the front of its siblings.
  24833. The component may have been brought to the front by the toFront() method, or
  24834. by the operating system if it's a top-level window.
  24835. @see toFront
  24836. */
  24837. virtual void broughtToFront();
  24838. /** Adds a listener to be told about changes to the component hierarchy or position.
  24839. Component listeners get called when this component's size, position or children
  24840. change - see the ComponentListener class for more details.
  24841. @param newListener the listener to register - if this is already registered, it
  24842. will be ignored.
  24843. @see ComponentListener, removeComponentListener
  24844. */
  24845. void addComponentListener (ComponentListener* newListener);
  24846. /** Removes a component listener.
  24847. @see addComponentListener
  24848. */
  24849. void removeComponentListener (ComponentListener* listenerToRemove);
  24850. /** Dispatches a numbered message to this component.
  24851. This is a quick and cheap way of allowing simple asynchronous messages to
  24852. be sent to components. It's also safe, because if the component that you
  24853. send the message to is a null or dangling pointer, this won't cause an error.
  24854. The command ID is later delivered to the component's handleCommandMessage() method by
  24855. the application's message queue.
  24856. @see handleCommandMessage
  24857. */
  24858. void postCommandMessage (int commandId);
  24859. /** Called to handle a command that was sent by postCommandMessage().
  24860. This is called by the message thread when a command message arrives, and
  24861. the component can override this method to process it in any way it needs to.
  24862. @see postCommandMessage
  24863. */
  24864. virtual void handleCommandMessage (int commandId);
  24865. /** Runs a component modally, waiting until the loop terminates.
  24866. This method first makes the component visible, brings it to the front and
  24867. gives it the keyboard focus.
  24868. It then runs a loop, dispatching messages from the system message queue, but
  24869. blocking all mouse or keyboard messages from reaching any components other
  24870. than this one and its children.
  24871. This loop continues until the component's exitModalState() method is called (or
  24872. the component is deleted), and then this method returns, returning the value
  24873. passed into exitModalState().
  24874. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  24875. isCurrentlyBlockedByAnotherModalComponent, ModalComponentManager
  24876. */
  24877. #if JUCE_MODAL_LOOPS_PERMITTED
  24878. int runModalLoop();
  24879. #endif
  24880. /** Puts the component into a modal state.
  24881. This makes the component modal, so that messages are blocked from reaching
  24882. any components other than this one and its children, but unlike runModalLoop(),
  24883. this method returns immediately.
  24884. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  24885. get the focus, which is usually what you'll want it to do. If not, it will leave
  24886. the focus unchanged.
  24887. The callback is an optional object which will receive a callback when the modal
  24888. component loses its modal status, either by being hidden or when exitModalState()
  24889. is called. If you pass an object in here, the system will take care of deleting it
  24890. later, after making the callback
  24891. If deleteWhenDismissed is true, then when it is dismissed, the component will be
  24892. deleted and then the callback will be called. (This will safely handle the situation
  24893. where the component is deleted before its exitModalState() method is called).
  24894. @see exitModalState, runModalLoop, ModalComponentManager::attachCallback
  24895. */
  24896. void enterModalState (bool takeKeyboardFocus = true,
  24897. ModalComponentManager::Callback* callback = nullptr,
  24898. bool deleteWhenDismissed = false);
  24899. /** Ends a component's modal state.
  24900. If this component is currently modal, this will turn of its modalness, and return
  24901. a value to the runModalLoop() method that might have be running its modal loop.
  24902. @see runModalLoop, enterModalState, isCurrentlyModal
  24903. */
  24904. void exitModalState (int returnValue);
  24905. /** Returns true if this component is the modal one.
  24906. It's possible to have nested modal components, e.g. a pop-up dialog box
  24907. that launches another pop-up, but this will only return true for
  24908. the one at the top of the stack.
  24909. @see getCurrentlyModalComponent
  24910. */
  24911. bool isCurrentlyModal() const noexcept;
  24912. /** Returns the number of components that are currently in a modal state.
  24913. @see getCurrentlyModalComponent
  24914. */
  24915. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() noexcept;
  24916. /** Returns one of the components that are currently modal.
  24917. The index specifies which of the possible modal components to return. The order
  24918. of the components in this list is the reverse of the order in which they became
  24919. modal - so the component at index 0 is always the active component, and the others
  24920. are progressively earlier ones that are themselves now blocked by later ones.
  24921. @returns the modal component, or null if no components are modal (or if the
  24922. index is out of range)
  24923. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  24924. */
  24925. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) noexcept;
  24926. /** Checks whether there's a modal component somewhere that's stopping this one
  24927. from receiving messages.
  24928. If there is a modal component, its canModalEventBeSentToComponent() method
  24929. will be called to see if it will still allow this component to receive events.
  24930. @see runModalLoop, getCurrentlyModalComponent
  24931. */
  24932. bool isCurrentlyBlockedByAnotherModalComponent() const;
  24933. /** When a component is modal, this callback allows it to choose which other
  24934. components can still receive events.
  24935. When a modal component is active and the user clicks on a non-modal component,
  24936. this method is called on the modal component, and if it returns true, the
  24937. event is allowed to reach its target. If it returns false, the event is blocked
  24938. and the inputAttemptWhenModal() callback is made.
  24939. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  24940. implementation just returns false in all cases.
  24941. */
  24942. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  24943. /** Called when the user tries to click on a component that is blocked by another
  24944. modal component.
  24945. When a component is modal and the user clicks on one of the other components,
  24946. the modal component will receive this callback.
  24947. The default implementation of this method will play a beep, and bring the currently
  24948. modal component to the front, but it can be overridden to do other tasks.
  24949. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  24950. */
  24951. virtual void inputAttemptWhenModal();
  24952. /** Returns the set of properties that belong to this component.
  24953. Each component has a NamedValueSet object which you can use to attach arbitrary
  24954. items of data to it.
  24955. */
  24956. NamedValueSet& getProperties() noexcept { return properties; }
  24957. /** Returns the set of properties that belong to this component.
  24958. Each component has a NamedValueSet object which you can use to attach arbitrary
  24959. items of data to it.
  24960. */
  24961. const NamedValueSet& getProperties() const noexcept { return properties; }
  24962. /** Looks for a colour that has been registered with the given colour ID number.
  24963. If a colour has been set for this ID number using setColour(), then it is
  24964. returned. If none has been set, the method will try calling the component's
  24965. LookAndFeel class's findColour() method. If none has been registered with the
  24966. look-and-feel either, it will just return black.
  24967. The colour IDs for various purposes are stored as enums in the components that
  24968. they are relevent to - for an example, see Slider::ColourIds,
  24969. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  24970. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  24971. */
  24972. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  24973. /** Registers a colour to be used for a particular purpose.
  24974. Changing a colour will cause a synchronous callback to the colourChanged()
  24975. method, which your component can override if it needs to do something when
  24976. colours are altered.
  24977. For more details about colour IDs, see the comments for findColour().
  24978. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  24979. */
  24980. void setColour (int colourId, const Colour& colour);
  24981. /** If a colour has been set with setColour(), this will remove it.
  24982. This allows you to make a colour revert to its default state.
  24983. */
  24984. void removeColour (int colourId);
  24985. /** Returns true if the specified colour ID has been explicitly set for this
  24986. component using the setColour() method.
  24987. */
  24988. bool isColourSpecified (int colourId) const;
  24989. /** This looks for any colours that have been specified for this component,
  24990. and copies them to the specified target component.
  24991. */
  24992. void copyAllExplicitColoursTo (Component& target) const;
  24993. /** This method is called when a colour is changed by the setColour() method.
  24994. @see setColour, findColour
  24995. */
  24996. virtual void colourChanged();
  24997. /** Components can implement this method to provide a MarkerList.
  24998. The default implementation of this method returns 0, but you can override it to
  24999. return a pointer to the component's marker list. If xAxis is true, it should
  25000. return the X marker list; if false, it should return the Y markers.
  25001. */
  25002. virtual MarkerList* getMarkers (bool xAxis);
  25003. /** Returns the underlying native window handle for this component.
  25004. This is platform-dependent and strictly for power-users only!
  25005. */
  25006. void* getWindowHandle() const;
  25007. /** Holds a pointer to some type of Component, which automatically becomes null if
  25008. the component is deleted.
  25009. If you're using a component which may be deleted by another event that's outside
  25010. of your control, use a SafePointer instead of a normal pointer to refer to it,
  25011. and you can test whether it's null before using it to see if something has deleted
  25012. it.
  25013. The ComponentType typedef must be Component, or some subclass of Component.
  25014. You may also want to use a WeakReference<Component> object for the same purpose.
  25015. */
  25016. template <class ComponentType>
  25017. class SafePointer
  25018. {
  25019. public:
  25020. /** Creates a null SafePointer. */
  25021. SafePointer() noexcept {}
  25022. /** Creates a SafePointer that points at the given component. */
  25023. SafePointer (ComponentType* const component) : weakRef (component) {}
  25024. /** Creates a copy of another SafePointer. */
  25025. SafePointer (const SafePointer& other) noexcept : weakRef (other.weakRef) {}
  25026. /** Copies another pointer to this one. */
  25027. SafePointer& operator= (const SafePointer& other) { weakRef = other.weakRef; return *this; }
  25028. /** Copies another pointer to this one. */
  25029. SafePointer& operator= (ComponentType* const newComponent) { weakRef = newComponent; return *this; }
  25030. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25031. ComponentType* getComponent() const noexcept { return dynamic_cast <ComponentType*> (weakRef.get()); }
  25032. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25033. operator ComponentType*() const noexcept { return getComponent(); }
  25034. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25035. ComponentType* operator->() noexcept { return getComponent(); }
  25036. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25037. const ComponentType* operator->() const noexcept { return getComponent(); }
  25038. /** If the component is valid, this deletes it and sets this pointer to null. */
  25039. void deleteAndZero() { delete getComponent(); jassert (getComponent() == nullptr); }
  25040. bool operator== (ComponentType* component) const noexcept { return weakRef == component; }
  25041. bool operator!= (ComponentType* component) const noexcept { return weakRef != component; }
  25042. private:
  25043. WeakReference<Component> weakRef;
  25044. };
  25045. /** A class to keep an eye on a component and check for it being deleted.
  25046. This is designed for use with the ListenerList::callChecked() methods, to allow
  25047. the list iterator to stop cleanly if the component is deleted by a listener callback
  25048. while the list is still being iterated.
  25049. */
  25050. class JUCE_API BailOutChecker
  25051. {
  25052. public:
  25053. /** Creates a checker that watches one component. */
  25054. BailOutChecker (Component* component);
  25055. /** Returns true if either of the two components have been deleted since this object was created. */
  25056. bool shouldBailOut() const noexcept;
  25057. private:
  25058. const WeakReference<Component> safePointer;
  25059. JUCE_DECLARE_NON_COPYABLE (BailOutChecker);
  25060. };
  25061. /**
  25062. Base class for objects that can be used to automatically position a component according to
  25063. some kind of algorithm.
  25064. The component class simply holds onto a reference to a Positioner, but doesn't actually do
  25065. anything with it - all the functionality must be implemented by the positioner itself (e.g.
  25066. it might choose to watch some kind of value and move the component when the value changes).
  25067. */
  25068. class JUCE_API Positioner
  25069. {
  25070. public:
  25071. /** Creates a Positioner which can control the specified component. */
  25072. explicit Positioner (Component& component) noexcept;
  25073. /** Destructor. */
  25074. virtual ~Positioner() {}
  25075. /** Returns the component that this positioner controls. */
  25076. Component& getComponent() const noexcept { return component; }
  25077. /** Attempts to set the component's position to the given rectangle.
  25078. Unlike simply calling Component::setBounds(), this may involve the positioner
  25079. being smart enough to adjust itself to fit the new bounds, e.g. a RelativeRectangle's
  25080. positioner may try to reverse the expressions used to make them fit these new coordinates.
  25081. */
  25082. virtual void applyNewBounds (const Rectangle<int>& newBounds) = 0;
  25083. private:
  25084. Component& component;
  25085. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  25086. };
  25087. /** Returns the Positioner object that has been set for this component.
  25088. @see setPositioner()
  25089. */
  25090. Positioner* getPositioner() const noexcept;
  25091. /** Sets a new Positioner object for this component.
  25092. If there's currently another positioner set, it will be deleted. The object that is passed in
  25093. will be deleted automatically by this component when it's no longer required. Pass a null pointer
  25094. to clear the current positioner.
  25095. @see getPositioner()
  25096. */
  25097. void setPositioner (Positioner* newPositioner);
  25098. #ifndef DOXYGEN
  25099. // These methods are deprecated - use localPointToGlobal, getLocalPoint, getLocalPoint, etc instead.
  25100. JUCE_DEPRECATED (const Point<int> relativePositionToGlobal (const Point<int>&) const);
  25101. JUCE_DEPRECATED (const Point<int> globalPositionToRelative (const Point<int>&) const);
  25102. JUCE_DEPRECATED (const Point<int> relativePositionToOtherComponent (const Component*, const Point<int>&) const);
  25103. #endif
  25104. private:
  25105. friend class ComponentPeer;
  25106. friend class MouseInputSource;
  25107. friend class MouseInputSourceInternal;
  25108. #ifndef DOXYGEN
  25109. static Component* currentlyFocusedComponent;
  25110. String componentName, componentID;
  25111. Component* parentComponent;
  25112. Rectangle<int> bounds;
  25113. ScopedPointer <Positioner> positioner;
  25114. ScopedPointer <AffineTransform> affineTransform;
  25115. Array <Component*> childComponentList;
  25116. LookAndFeel* lookAndFeel;
  25117. MouseCursor cursor;
  25118. ImageEffectFilter* effect;
  25119. Image bufferedImage;
  25120. class MouseListenerList;
  25121. friend class MouseListenerList;
  25122. friend class ScopedPointer <MouseListenerList>;
  25123. ScopedPointer <MouseListenerList> mouseListeners;
  25124. ScopedPointer <Array <KeyListener*> > keyListeners;
  25125. ListenerList <ComponentListener> componentListeners;
  25126. NamedValueSet properties;
  25127. friend class WeakReference<Component>;
  25128. WeakReference<Component>::Master weakReferenceMaster;
  25129. const WeakReference<Component>::SharedRef& getWeakReference();
  25130. struct ComponentFlags
  25131. {
  25132. bool hasHeavyweightPeerFlag : 1;
  25133. bool visibleFlag : 1;
  25134. bool opaqueFlag : 1;
  25135. bool ignoresMouseClicksFlag : 1;
  25136. bool allowChildMouseClicksFlag : 1;
  25137. bool wantsFocusFlag : 1;
  25138. bool isFocusContainerFlag : 1;
  25139. bool dontFocusOnMouseClickFlag : 1;
  25140. bool alwaysOnTopFlag : 1;
  25141. bool bufferToImageFlag : 1;
  25142. bool bringToFrontOnClickFlag : 1;
  25143. bool repaintOnMouseActivityFlag : 1;
  25144. bool mouseDownFlag : 1;
  25145. bool mouseOverFlag : 1;
  25146. bool mouseInsideFlag : 1;
  25147. bool currentlyModalFlag : 1;
  25148. bool isDisabledFlag : 1;
  25149. bool childCompFocusedFlag : 1;
  25150. bool dontClipGraphicsFlag : 1;
  25151. #if JUCE_DEBUG
  25152. bool isInsidePaintCall : 1;
  25153. #endif
  25154. };
  25155. union
  25156. {
  25157. uint32 componentFlags;
  25158. ComponentFlags flags;
  25159. };
  25160. uint8 componentTransparency;
  25161. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25162. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25163. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25164. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  25165. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25166. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25167. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  25168. void internalBroughtToFront();
  25169. void internalFocusGain (const FocusChangeType cause, const WeakReference<Component>&);
  25170. void internalFocusGain (const FocusChangeType cause);
  25171. void internalFocusLoss (const FocusChangeType cause);
  25172. void internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>&);
  25173. void internalModalInputAttempt();
  25174. void internalModifierKeysChanged();
  25175. void internalChildrenChanged();
  25176. void internalHierarchyChanged();
  25177. Component* removeChildComponent (int index, bool sendParentEvents, bool sendChildEvents);
  25178. void moveChildInternal (int sourceIndex, int destIndex);
  25179. void paintComponentAndChildren (Graphics& g);
  25180. void paintComponent (Graphics& g);
  25181. void paintWithinParentContext (Graphics& g);
  25182. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  25183. void repaintParent();
  25184. void sendFakeMouseMove() const;
  25185. void takeKeyboardFocus (const FocusChangeType cause);
  25186. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  25187. static void giveAwayFocus (bool sendFocusLossEvent);
  25188. void sendEnablementChangeMessage();
  25189. void sendVisibilityChangeMessage();
  25190. class ComponentHelpers;
  25191. friend class ComponentHelpers;
  25192. /* Components aren't allowed to have copy constructors, as this would mess up parent hierarchies.
  25193. You might need to give your subclasses a private dummy constructor to avoid compiler warnings.
  25194. */
  25195. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Component);
  25196. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  25197. // This is included here just to cause a compile error if your code is still handling
  25198. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  25199. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  25200. // implement its methods instead of this Component method).
  25201. virtual void filesDropped (const StringArray&, int, int) {}
  25202. // This is included here to cause an error if you use or overload it - it has been deprecated in
  25203. // favour of contains (const Point<int>&)
  25204. void contains (int, int);
  25205. #endif
  25206. protected:
  25207. /** @internal */
  25208. virtual void internalRepaint (int x, int y, int w, int h);
  25209. /** @internal */
  25210. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  25211. #endif
  25212. };
  25213. #endif // __JUCE_COMPONENT_JUCEHEADER__
  25214. /*** End of inlined file: juce_Component.h ***/
  25215. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  25216. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25217. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25218. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  25219. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25220. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25221. /** A type used to hold the unique ID for an application command.
  25222. This is a numeric type, so it can be stored as an integer.
  25223. @see ApplicationCommandInfo, ApplicationCommandManager,
  25224. ApplicationCommandTarget, KeyPressMappingSet
  25225. */
  25226. typedef int CommandID;
  25227. /** A set of general-purpose application command IDs.
  25228. Because these commands are likely to be used in most apps, they're defined
  25229. here to help different apps to use the same numeric values for them.
  25230. Of course you don't have to use these, but some of them are used internally by
  25231. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  25232. @see ApplicationCommandInfo, ApplicationCommandManager,
  25233. ApplicationCommandTarget, KeyPressMappingSet
  25234. */
  25235. namespace StandardApplicationCommandIDs
  25236. {
  25237. /** This command ID should be used to send a "Quit the App" command.
  25238. This command is recognised by the JUCEApplication class, so if it is invoked
  25239. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  25240. object will catch it and call JUCEApplication::systemRequestedQuit().
  25241. */
  25242. static const CommandID quit = 0x1001;
  25243. /** The command ID that should be used to send a "Delete" command. */
  25244. static const CommandID del = 0x1002;
  25245. /** The command ID that should be used to send a "Cut" command. */
  25246. static const CommandID cut = 0x1003;
  25247. /** The command ID that should be used to send a "Copy to clipboard" command. */
  25248. static const CommandID copy = 0x1004;
  25249. /** The command ID that should be used to send a "Paste from clipboard" command. */
  25250. static const CommandID paste = 0x1005;
  25251. /** The command ID that should be used to send a "Select all" command. */
  25252. static const CommandID selectAll = 0x1006;
  25253. /** The command ID that should be used to send a "Deselect all" command. */
  25254. static const CommandID deselectAll = 0x1007;
  25255. }
  25256. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25257. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  25258. /**
  25259. Holds information describing an application command.
  25260. This object is used to pass information about a particular command, such as its
  25261. name, description and other usage flags.
  25262. When an ApplicationCommandTarget is asked to provide information about the commands
  25263. it can perform, this is the structure gets filled-in to describe each one.
  25264. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  25265. ApplicationCommandManager
  25266. */
  25267. struct JUCE_API ApplicationCommandInfo
  25268. {
  25269. explicit ApplicationCommandInfo (CommandID commandID) noexcept;
  25270. /** Sets a number of the structures values at once.
  25271. The meanings of each of the parameters is described below, in the appropriate
  25272. member variable's description.
  25273. */
  25274. void setInfo (const String& shortName,
  25275. const String& description,
  25276. const String& categoryName,
  25277. int flags) noexcept;
  25278. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  25279. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  25280. is false, the bit is set.
  25281. */
  25282. void setActive (bool isActive) noexcept;
  25283. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  25284. */
  25285. void setTicked (bool isTicked) noexcept;
  25286. /** Handy method for adding a keypress to the defaultKeypresses array.
  25287. This is just so you can write things like:
  25288. @code
  25289. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  25290. @endcode
  25291. instead of
  25292. @code
  25293. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  25294. @endcode
  25295. */
  25296. void addDefaultKeypress (int keyCode,
  25297. const ModifierKeys& modifiers) noexcept;
  25298. /** The command's unique ID number.
  25299. */
  25300. CommandID commandID;
  25301. /** A short name to describe the command.
  25302. This should be suitable for use in menus, on buttons that trigger the command, etc.
  25303. You can use the setInfo() method to quickly set this and some of the command's
  25304. other properties.
  25305. */
  25306. String shortName;
  25307. /** A longer description of the command.
  25308. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  25309. pop-up tooltip describing what the command does.
  25310. You can use the setInfo() method to quickly set this and some of the command's
  25311. other properties.
  25312. */
  25313. String description;
  25314. /** A named category that the command fits into.
  25315. You can give your commands any category you like, and these will be displayed in
  25316. contexts such as the KeyMappingEditorComponent, where the category is used to group
  25317. commands together.
  25318. You can use the setInfo() method to quickly set this and some of the command's
  25319. other properties.
  25320. */
  25321. String categoryName;
  25322. /** A list of zero or more keypresses that should be used as the default keys for
  25323. this command.
  25324. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  25325. this list to initialise the default set of key-to-command mappings.
  25326. @see addDefaultKeypress
  25327. */
  25328. Array <KeyPress> defaultKeypresses;
  25329. /** Flags describing the ways in which this command should be used.
  25330. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  25331. variable.
  25332. */
  25333. enum CommandFlags
  25334. {
  25335. /** Indicates that the command can't currently be performed.
  25336. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  25337. not currently permissable to perform the command. If the flag is set, then
  25338. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  25339. command or show themselves as not being enabled.
  25340. @see ApplicationCommandInfo::setActive
  25341. */
  25342. isDisabled = 1 << 0,
  25343. /** Indicates that the command should have a tick next to it on a menu.
  25344. If your command is shown on a menu and this is set, it'll show a tick next to
  25345. it. Other components such as buttons may also use this flag to indicate that it
  25346. is a value that can be toggled, and is currently in the 'on' state.
  25347. @see ApplicationCommandInfo::setTicked
  25348. */
  25349. isTicked = 1 << 1,
  25350. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  25351. it will call the command twice, once on key-down and again on key-up.
  25352. @see ApplicationCommandTarget::InvocationInfo
  25353. */
  25354. wantsKeyUpDownCallbacks = 1 << 2,
  25355. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  25356. command in its list.
  25357. */
  25358. hiddenFromKeyEditor = 1 << 3,
  25359. /** If this flag is present, then a KeyMappingEditorComponent will display the
  25360. command in its list, but won't allow the assigned keypress to be changed.
  25361. */
  25362. readOnlyInKeyEditor = 1 << 4,
  25363. /** If this flag is present and the command is invoked from a keypress, then any
  25364. buttons or menus that are also connected to the command will not flash to
  25365. indicate that they've been triggered.
  25366. */
  25367. dontTriggerVisualFeedback = 1 << 5
  25368. };
  25369. /** A bitwise-OR of the values specified in the CommandFlags enum.
  25370. You can use the setInfo() method to quickly set this and some of the command's
  25371. other properties.
  25372. */
  25373. int flags;
  25374. };
  25375. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25376. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  25377. /*** Start of inlined file: juce_MessageListener.h ***/
  25378. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  25379. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  25380. /**
  25381. MessageListener subclasses can post and receive Message objects.
  25382. @see Message, MessageManager, ActionListener, ChangeListener
  25383. */
  25384. class JUCE_API MessageListener
  25385. {
  25386. protected:
  25387. /** Creates a MessageListener. */
  25388. MessageListener() noexcept;
  25389. public:
  25390. /** Destructor.
  25391. When a MessageListener is deleted, it removes itself from a global list
  25392. of registered listeners, so that the isValidMessageListener() method
  25393. will no longer return true.
  25394. */
  25395. virtual ~MessageListener();
  25396. /** This is the callback method that receives incoming messages.
  25397. This is called by the MessageManager from its dispatch loop.
  25398. @see postMessage
  25399. */
  25400. virtual void handleMessage (const Message& message) = 0;
  25401. /** Sends a message to the message queue, for asynchronous delivery to this listener
  25402. later on.
  25403. This method can be called safely by any thread.
  25404. @param message the message object to send - this will be deleted
  25405. automatically by the message queue, so don't keep any
  25406. references to it after calling this method.
  25407. @see handleMessage
  25408. */
  25409. void postMessage (Message* message) const noexcept;
  25410. /** Checks whether this MessageListener has been deleted.
  25411. Although not foolproof, this method is safe to call on dangling or null
  25412. pointers. A list of active MessageListeners is kept internally, so this
  25413. checks whether the object is on this list or not.
  25414. Note that it's possible to get a false-positive here, if an object is
  25415. deleted and another is subsequently created that happens to be at the
  25416. exact same memory location, but I can't think of a good way of avoiding
  25417. this.
  25418. */
  25419. bool isValidMessageListener() const noexcept;
  25420. };
  25421. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  25422. /*** End of inlined file: juce_MessageListener.h ***/
  25423. /**
  25424. A command target publishes a list of command IDs that it can perform.
  25425. An ApplicationCommandManager despatches commands to targets, which must be
  25426. able to provide information about what commands they can handle.
  25427. To create a target, you'll need to inherit from this class, implementing all of
  25428. its pure virtual methods.
  25429. For info about how a target is chosen to receive a command, see
  25430. ApplicationCommandManager::getFirstCommandTarget().
  25431. @see ApplicationCommandManager, ApplicationCommandInfo
  25432. */
  25433. class JUCE_API ApplicationCommandTarget
  25434. {
  25435. public:
  25436. /** Creates a command target. */
  25437. ApplicationCommandTarget();
  25438. /** Destructor. */
  25439. virtual ~ApplicationCommandTarget();
  25440. /**
  25441. */
  25442. struct JUCE_API InvocationInfo
  25443. {
  25444. InvocationInfo (const CommandID commandID);
  25445. /** The UID of the command that should be performed. */
  25446. CommandID commandID;
  25447. /** The command's flags.
  25448. See ApplicationCommandInfo for a description of these flag values.
  25449. */
  25450. int commandFlags;
  25451. /** The types of context in which the command might be called. */
  25452. enum InvocationMethod
  25453. {
  25454. direct = 0, /**< The command is being invoked directly by a piece of code. */
  25455. fromKeyPress, /**< The command is being invoked by a key-press. */
  25456. fromMenu, /**< The command is being invoked by a menu selection. */
  25457. fromButton /**< The command is being invoked by a button click. */
  25458. };
  25459. /** The type of event that triggered this command. */
  25460. InvocationMethod invocationMethod;
  25461. /** If triggered by a keypress or menu, this will be the component that had the
  25462. keyboard focus at the time.
  25463. If triggered by a button, it may be set to that component, or it may be null.
  25464. */
  25465. Component* originatingComponent;
  25466. /** The keypress that was used to invoke it.
  25467. Note that this will be an invalid keypress if the command was invoked
  25468. by some other means than a keyboard shortcut.
  25469. */
  25470. KeyPress keyPress;
  25471. /** True if the callback is being invoked when the key is pressed,
  25472. false if the key is being released.
  25473. @see KeyPressMappingSet::addCommand()
  25474. */
  25475. bool isKeyDown;
  25476. /** If the key is being released, this indicates how long it had been held
  25477. down for.
  25478. (Only relevant if isKeyDown is false.)
  25479. */
  25480. int millisecsSinceKeyPressed;
  25481. };
  25482. /** This must return the next target to try after this one.
  25483. When a command is being sent, and the first target can't handle
  25484. that command, this method is used to determine the next target that should
  25485. be tried.
  25486. It may return 0 if it doesn't know of another target.
  25487. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  25488. method to return a parent component that might want to handle it.
  25489. @see invoke
  25490. */
  25491. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  25492. /** This must return a complete list of commands that this target can handle.
  25493. Your target should add all the command IDs that it handles to the array that is
  25494. passed-in.
  25495. */
  25496. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  25497. /** This must provide details about one of the commands that this target can perform.
  25498. This will be called with one of the command IDs that the target provided in its
  25499. getAllCommands() methods.
  25500. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  25501. suitable information about the command. (The commandID field will already have been filled-in
  25502. by the caller).
  25503. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  25504. set all the fields at once.
  25505. If the command is currently inactive for some reason, this method must use
  25506. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  25507. bit of the ApplicationCommandInfo::flags field).
  25508. Any default key-presses for the command should be appended to the
  25509. ApplicationCommandInfo::defaultKeypresses field.
  25510. Note that if you change something that affects the status of the commands
  25511. that would be returned by this method (e.g. something that makes some commands
  25512. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  25513. to cause the manager to refresh its status.
  25514. */
  25515. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  25516. /** This must actually perform the specified command.
  25517. If this target is able to perform the command specified by the commandID field of the
  25518. InvocationInfo structure, then it should do so, and must return true.
  25519. If it can't handle this command, it should return false, which tells the caller to pass
  25520. the command on to the next target in line.
  25521. @see invoke, ApplicationCommandManager::invoke
  25522. */
  25523. virtual bool perform (const InvocationInfo& info) = 0;
  25524. /** Makes this target invoke a command.
  25525. Your code can call this method to invoke a command on this target, but normally
  25526. you'd call it indirectly via ApplicationCommandManager::invoke() or
  25527. ApplicationCommandManager::invokeDirectly().
  25528. If this target can perform the given command, it will call its perform() method to
  25529. do so. If not, then getNextCommandTarget() will be used to determine the next target
  25530. to try, and the command will be passed along to it.
  25531. @param invocationInfo this must be correctly filled-in, describing the context for
  25532. the invocation.
  25533. @param asynchronously if false, the command will be performed before this method returns.
  25534. If true, a message will be posted so that the command will be performed
  25535. later on the message thread, and this method will return immediately.
  25536. @see perform, ApplicationCommandManager::invoke
  25537. */
  25538. bool invoke (const InvocationInfo& invocationInfo,
  25539. const bool asynchronously);
  25540. /** Invokes a given command directly on this target.
  25541. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  25542. structure.
  25543. */
  25544. bool invokeDirectly (const CommandID commandID,
  25545. const bool asynchronously);
  25546. /** Searches this target and all subsequent ones for the first one that can handle
  25547. the specified command.
  25548. This will use getNextCommandTarget() to determine the chain of targets to try
  25549. after this one.
  25550. */
  25551. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  25552. /** Checks whether this command can currently be performed by this target.
  25553. This will return true only if a call to getCommandInfo() doesn't set the
  25554. isDisabled flag to indicate that the command is inactive.
  25555. */
  25556. bool isCommandActive (const CommandID commandID);
  25557. /** If this object is a Component, this method will seach upwards in its current
  25558. UI hierarchy for the next parent component that implements the
  25559. ApplicationCommandTarget class.
  25560. If your target is a Component, this is a very handy method to use in your
  25561. getNextCommandTarget() implementation.
  25562. */
  25563. ApplicationCommandTarget* findFirstTargetParentComponent();
  25564. private:
  25565. // (for async invocation of commands)
  25566. class CommandTargetMessageInvoker : public MessageListener
  25567. {
  25568. public:
  25569. CommandTargetMessageInvoker (ApplicationCommandTarget* owner);
  25570. ~CommandTargetMessageInvoker();
  25571. void handleMessage (const Message& message);
  25572. private:
  25573. ApplicationCommandTarget* const owner;
  25574. JUCE_DECLARE_NON_COPYABLE (CommandTargetMessageInvoker);
  25575. };
  25576. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  25577. friend class CommandTargetMessageInvoker;
  25578. bool tryToInvoke (const InvocationInfo& info, bool async);
  25579. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandTarget);
  25580. };
  25581. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  25582. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  25583. /*** Start of inlined file: juce_ActionListener.h ***/
  25584. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  25585. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  25586. /**
  25587. Receives callbacks to indicate that some kind of event has occurred.
  25588. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  25589. about something that's happened.
  25590. @see ActionBroadcaster, ChangeListener
  25591. */
  25592. class JUCE_API ActionListener
  25593. {
  25594. public:
  25595. /** Destructor. */
  25596. virtual ~ActionListener() {}
  25597. /** Overridden by your subclass to receive the callback.
  25598. @param message the string that was specified when the event was triggered
  25599. by a call to ActionBroadcaster::sendActionMessage()
  25600. */
  25601. virtual void actionListenerCallback (const String& message) = 0;
  25602. };
  25603. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  25604. /*** End of inlined file: juce_ActionListener.h ***/
  25605. /**
  25606. An instance of this class is used to specify initialisation and shutdown
  25607. code for the application.
  25608. An application that wants to run in the JUCE framework needs to declare a
  25609. subclass of JUCEApplication and implement its various pure virtual methods.
  25610. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  25611. to declare an instance of this class and generate a suitable platform-specific
  25612. main() function.
  25613. e.g. @code
  25614. class MyJUCEApp : public JUCEApplication
  25615. {
  25616. public:
  25617. MyJUCEApp()
  25618. {
  25619. }
  25620. ~MyJUCEApp()
  25621. {
  25622. }
  25623. void initialise (const String& commandLine)
  25624. {
  25625. myMainWindow = new MyApplicationWindow();
  25626. myMainWindow->setBounds (100, 100, 400, 500);
  25627. myMainWindow->setVisible (true);
  25628. }
  25629. void shutdown()
  25630. {
  25631. myMainWindow = 0;
  25632. }
  25633. const String getApplicationName()
  25634. {
  25635. return "Super JUCE-o-matic";
  25636. }
  25637. const String getApplicationVersion()
  25638. {
  25639. return "1.0";
  25640. }
  25641. private:
  25642. ScopedPointer <MyApplicationWindow> myMainWindow;
  25643. };
  25644. // this creates wrapper code to actually launch the app properly.
  25645. START_JUCE_APPLICATION (MyJUCEApp)
  25646. @endcode
  25647. @see MessageManager, DeletedAtShutdown
  25648. */
  25649. class JUCE_API JUCEApplication : public ApplicationCommandTarget
  25650. {
  25651. protected:
  25652. /** Constructs a JUCE app object.
  25653. If subclasses implement a constructor or destructor, they shouldn't call any
  25654. JUCE code in there - put your startup/shutdown code in initialise() and
  25655. shutdown() instead.
  25656. */
  25657. JUCEApplication();
  25658. public:
  25659. /** Destructor.
  25660. If subclasses implement a constructor or destructor, they shouldn't call any
  25661. JUCE code in there - put your startup/shutdown code in initialise() and
  25662. shutdown() instead.
  25663. */
  25664. virtual ~JUCEApplication();
  25665. /** Returns the global instance of the application object being run. */
  25666. static JUCEApplication* getInstance() noexcept { return appInstance; }
  25667. /** Called when the application starts.
  25668. This will be called once to let the application do whatever initialisation
  25669. it needs, create its windows, etc.
  25670. After the method returns, the normal event-dispatch loop will be run,
  25671. until the quit() method is called, at which point the shutdown()
  25672. method will be called to let the application clear up anything it needs
  25673. to delete.
  25674. If during the initialise() method, the application decides not to start-up
  25675. after all, it can just call the quit() method and the event loop won't be run.
  25676. @param commandLineParameters the line passed in does not include the
  25677. name of the executable, just the parameter list.
  25678. @see shutdown, quit
  25679. */
  25680. virtual void initialise (const String& commandLineParameters) = 0;
  25681. /** Returns true if the application hasn't yet completed its initialise() method
  25682. and entered the main event loop.
  25683. This is handy for things like splash screens to know when the app's up-and-running
  25684. properly.
  25685. */
  25686. bool isInitialising() const noexcept { return stillInitialising; }
  25687. /* Called to allow the application to clear up before exiting.
  25688. After JUCEApplication::quit() has been called, the event-dispatch loop will
  25689. terminate, and this method will get called to allow the app to sort itself
  25690. out.
  25691. Be careful that nothing happens in this method that might rely on messages
  25692. being sent, or any kind of window activity, because the message loop is no
  25693. longer running at this point.
  25694. @see DeletedAtShutdown
  25695. */
  25696. virtual void shutdown() = 0;
  25697. /** Returns the application's name.
  25698. An application must implement this to name itself.
  25699. */
  25700. virtual const String getApplicationName() = 0;
  25701. /** Returns the application's version number.
  25702. */
  25703. virtual const String getApplicationVersion() = 0;
  25704. /** Checks whether multiple instances of the app are allowed.
  25705. If you application class returns true for this, more than one instance is
  25706. permitted to run (except on the Mac where this isn't possible).
  25707. If it's false, the second instance won't start, but it you will still get a
  25708. callback to anotherInstanceStarted() to tell you about this - which
  25709. gives you a chance to react to what the user was trying to do.
  25710. */
  25711. virtual bool moreThanOneInstanceAllowed();
  25712. /** Indicates that the user has tried to start up another instance of the app.
  25713. This will get called even if moreThanOneInstanceAllowed() is false.
  25714. */
  25715. virtual void anotherInstanceStarted (const String& commandLine);
  25716. /** Called when the operating system is trying to close the application.
  25717. The default implementation of this method is to call quit(), but it may
  25718. be overloaded to ignore the request or do some other special behaviour
  25719. instead. For example, you might want to offer the user the chance to save
  25720. their changes before quitting, and give them the chance to cancel.
  25721. If you want to send a quit signal to your app, this is the correct method
  25722. to call, because it means that requests that come from the system get handled
  25723. in the same way as those from your own application code. So e.g. you'd
  25724. call this method from a "quit" item on a menu bar.
  25725. */
  25726. virtual void systemRequestedQuit();
  25727. /** If any unhandled exceptions make it through to the message dispatch loop, this
  25728. callback will be triggered, in case you want to log them or do some other
  25729. type of error-handling.
  25730. If the type of exception is derived from the std::exception class, the pointer
  25731. passed-in will be valid. If the exception is of unknown type, this pointer
  25732. will be null.
  25733. */
  25734. virtual void unhandledException (const std::exception* e,
  25735. const String& sourceFilename,
  25736. int lineNumber);
  25737. /** Signals that the main message loop should stop and the application should terminate.
  25738. This isn't synchronous, it just posts a quit message to the main queue, and
  25739. when this message arrives, the message loop will stop, the shutdown() method
  25740. will be called, and the app will exit.
  25741. Note that this will cause an unconditional quit to happen, so if you need an
  25742. extra level before this, e.g. to give the user the chance to save their work
  25743. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  25744. method - see that method's help for more info.
  25745. @see MessageManager, DeletedAtShutdown
  25746. */
  25747. static void quit();
  25748. /** Sets the value that should be returned as the application's exit code when the
  25749. app quits.
  25750. This is the value that's returned by the main() function. Normally you'd leave this
  25751. as 0 unless you want to indicate an error code.
  25752. @see getApplicationReturnValue
  25753. */
  25754. void setApplicationReturnValue (int newReturnValue) noexcept;
  25755. /** Returns the value that has been set as the application's exit code.
  25756. @see setApplicationReturnValue
  25757. */
  25758. int getApplicationReturnValue() const noexcept { return appReturnValue; }
  25759. /** Returns the application's command line params.
  25760. */
  25761. const String getCommandLineParameters() const noexcept { return commandLineParameters; }
  25762. /** Returns true if this executable is running as an app (as opposed to being a plugin
  25763. or other kind of shared library. */
  25764. static inline bool isStandaloneApp() noexcept { return createInstance != 0; }
  25765. /** @internal */
  25766. ApplicationCommandTarget* getNextCommandTarget();
  25767. /** @internal */
  25768. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  25769. /** @internal */
  25770. void getAllCommands (Array <CommandID>& commands);
  25771. /** @internal */
  25772. bool perform (const InvocationInfo& info);
  25773. #ifndef DOXYGEN
  25774. // The following methods are internal calls - not for public use.
  25775. static int main (const String& commandLine);
  25776. static int main (int argc, const char* argv[]);
  25777. static void sendUnhandledException (const std::exception* e, const char* sourceFile, int lineNumber);
  25778. bool initialiseApp (const String& commandLine);
  25779. int shutdownApp();
  25780. static void appWillTerminateByForce();
  25781. typedef JUCEApplication* (*CreateInstanceFunction)();
  25782. static CreateInstanceFunction createInstance;
  25783. #endif
  25784. private:
  25785. static JUCEApplication* appInstance;
  25786. String commandLineParameters;
  25787. ScopedPointer<InterProcessLock> appLock;
  25788. ScopedPointer<ActionListener> broadcastCallback;
  25789. int appReturnValue;
  25790. bool stillInitialising;
  25791. JUCE_DECLARE_NON_COPYABLE (JUCEApplication);
  25792. };
  25793. #endif // __JUCE_APPLICATION_JUCEHEADER__
  25794. /*** End of inlined file: juce_Application.h ***/
  25795. #endif
  25796. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25797. #endif
  25798. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25799. #endif
  25800. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25801. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  25802. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25803. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25804. /*** Start of inlined file: juce_Desktop.h ***/
  25805. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  25806. #define __JUCE_DESKTOP_JUCEHEADER__
  25807. /*** Start of inlined file: juce_Timer.h ***/
  25808. #ifndef __JUCE_TIMER_JUCEHEADER__
  25809. #define __JUCE_TIMER_JUCEHEADER__
  25810. class InternalTimerThread;
  25811. /**
  25812. Makes repeated callbacks to a virtual method at a specified time interval.
  25813. A Timer's timerCallback() method will be repeatedly called at a given
  25814. interval. When you create a Timer object, it will do nothing until the
  25815. startTimer() method is called, which will cause the message thread to
  25816. start making callbacks at the specified interval, until stopTimer() is called
  25817. or the object is deleted.
  25818. The time interval isn't guaranteed to be precise to any more than maybe
  25819. 10-20ms, and the intervals may end up being much longer than requested if the
  25820. system is busy. Because the callbacks are made by the main message thread,
  25821. anything that blocks the message queue for a period of time will also prevent
  25822. any timers from running until it can carry on.
  25823. If you need to have a single callback that is shared by multiple timers with
  25824. different frequencies, then the MultiTimer class allows you to do that - its
  25825. structure is very similar to the Timer class, but contains multiple timers
  25826. internally, each one identified by an ID number.
  25827. @see MultiTimer
  25828. */
  25829. class JUCE_API Timer
  25830. {
  25831. protected:
  25832. /** Creates a Timer.
  25833. When created, the timer is stopped, so use startTimer() to get it going.
  25834. */
  25835. Timer() noexcept;
  25836. /** Creates a copy of another timer.
  25837. Note that this timer won't be started, even if the one you're copying
  25838. is running.
  25839. */
  25840. Timer (const Timer& other) noexcept;
  25841. public:
  25842. /** Destructor. */
  25843. virtual ~Timer();
  25844. /** The user-defined callback routine that actually gets called periodically.
  25845. It's perfectly ok to call startTimer() or stopTimer() from within this
  25846. callback to change the subsequent intervals.
  25847. */
  25848. virtual void timerCallback() = 0;
  25849. /** Starts the timer and sets the length of interval required.
  25850. If the timer is already started, this will reset it, so the
  25851. time between calling this method and the next timer callback
  25852. will not be less than the interval length passed in.
  25853. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  25854. rounded up to 1)
  25855. */
  25856. void startTimer (int intervalInMilliseconds) noexcept;
  25857. /** Stops the timer.
  25858. No more callbacks will be made after this method returns.
  25859. If this is called from a different thread, any callbacks that may
  25860. be currently executing may be allowed to finish before the method
  25861. returns.
  25862. */
  25863. void stopTimer() noexcept;
  25864. /** Checks if the timer has been started.
  25865. @returns true if the timer is running.
  25866. */
  25867. bool isTimerRunning() const noexcept { return periodMs > 0; }
  25868. /** Returns the timer's interval.
  25869. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  25870. */
  25871. int getTimerInterval() const noexcept { return periodMs; }
  25872. private:
  25873. friend class InternalTimerThread;
  25874. int countdownMs, periodMs;
  25875. Timer* previous;
  25876. Timer* next;
  25877. Timer& operator= (const Timer&);
  25878. };
  25879. #endif // __JUCE_TIMER_JUCEHEADER__
  25880. /*** End of inlined file: juce_Timer.h ***/
  25881. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  25882. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25883. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25884. /**
  25885. Animates a set of components, moving them to a new position and/or fading their
  25886. alpha levels.
  25887. To animate a component, create a ComponentAnimator instance or (preferably) use the
  25888. global animator object provided by Desktop::getAnimator(), and call its animateComponent()
  25889. method to commence the movement.
  25890. If you're using your own ComponentAnimator instance, you'll need to make sure it isn't
  25891. deleted before it finishes moving the components, or they'll be abandoned before reaching their
  25892. destinations.
  25893. It's ok to delete components while they're being animated - the animator will detect this
  25894. and safely stop using them.
  25895. The class is a ChangeBroadcaster and sends a notification when any components
  25896. start or finish being animated.
  25897. @see Desktop::getAnimator
  25898. */
  25899. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  25900. private Timer
  25901. {
  25902. public:
  25903. /** Creates a ComponentAnimator. */
  25904. ComponentAnimator();
  25905. /** Destructor. */
  25906. ~ComponentAnimator();
  25907. /** Starts a component moving from its current position to a specified position.
  25908. If the component is already in the middle of an animation, that will be abandoned,
  25909. and a new animation will begin, moving the component from its current location.
  25910. The start and end speed parameters let you apply some acceleration to the component's
  25911. movement.
  25912. @param component the component to move
  25913. @param finalBounds the destination bounds to which the component should move. To leave the
  25914. component in the same place, just pass component->getBounds() for this value
  25915. @param finalAlpha the alpha value that the component should have at the end of the animation
  25916. @param animationDurationMilliseconds how long the animation should last, in milliseconds
  25917. @param useProxyComponent if true, this means the component should be replaced by an internally
  25918. managed temporary component which is a snapshot of the original component.
  25919. This avoids the component having to paint itself as it moves, so may
  25920. be more efficient. This option also allows you to delete the original
  25921. component immediately after starting the animation, because the animation
  25922. can proceed without it. If you use a proxy, the original component will be
  25923. made invisible by this call, and then will become visible again at the end
  25924. of the animation. It'll also mean that the proxy component will be temporarily
  25925. added to the component's parent, so avoid it if this might confuse the parent
  25926. component, or if there's a chance the parent might decide to delete its children.
  25927. @param startSpeed a value to indicate the relative start speed of the animation. If this is 0,
  25928. the component will start by accelerating from rest; higher values mean that it
  25929. will have an initial speed greater than zero. If the value if greater than 1, it
  25930. will decelerate towards the middle of its journey. To move the component at a
  25931. constant rate for its entire animation, set both the start and end speeds to 1.0
  25932. @param endSpeed a relative speed at which the component should be moving when the animation finishes.
  25933. If this is 0, the component will decelerate to a standstill at its final position;
  25934. higher values mean the component will still be moving when it stops. To move the component
  25935. at a constant rate for its entire animation, set both the start and end speeds to 1.0
  25936. */
  25937. void animateComponent (Component* component,
  25938. const Rectangle<int>& finalBounds,
  25939. float finalAlpha,
  25940. int animationDurationMilliseconds,
  25941. bool useProxyComponent,
  25942. double startSpeed,
  25943. double endSpeed);
  25944. /** Begins a fade-out of this components alpha level.
  25945. This is a quick way of invoking animateComponent() with a target alpha value of 0.0f, using
  25946. a proxy. You're safe to delete the component after calling this method, and this won't
  25947. interfere with the animation's progress.
  25948. */
  25949. void fadeOut (Component* component, int millisecondsToTake);
  25950. /** Begins a fade-in of a component.
  25951. This is a quick way of invoking animateComponent() with a target alpha value of 1.0f.
  25952. */
  25953. void fadeIn (Component* component, int millisecondsToTake);
  25954. /** Stops a component if it's currently being animated.
  25955. If moveComponentToItsFinalPosition is true, then the component will
  25956. be immediately moved to its destination position and size. If false, it will be
  25957. left in whatever location it currently occupies.
  25958. */
  25959. void cancelAnimation (Component* component,
  25960. bool moveComponentToItsFinalPosition);
  25961. /** Clears all of the active animations.
  25962. If moveComponentsToTheirFinalPositions is true, all the components will
  25963. be immediately set to their final positions. If false, they will be
  25964. left in whatever locations they currently occupy.
  25965. */
  25966. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  25967. /** Returns the destination position for a component.
  25968. If the component is being animated, this will return the target position that
  25969. was specified when animateComponent() was called.
  25970. If the specified component isn't currently being animated, this method will just
  25971. return its current position.
  25972. */
  25973. const Rectangle<int> getComponentDestination (Component* component);
  25974. /** Returns true if the specified component is currently being animated. */
  25975. bool isAnimating (Component* component) const;
  25976. private:
  25977. class AnimationTask;
  25978. OwnedArray <AnimationTask> tasks;
  25979. uint32 lastTime;
  25980. AnimationTask* findTaskFor (Component* component) const;
  25981. void timerCallback();
  25982. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentAnimator);
  25983. };
  25984. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25985. /*** End of inlined file: juce_ComponentAnimator.h ***/
  25986. class MouseInputSource;
  25987. class MouseInputSourceInternal;
  25988. class MouseListener;
  25989. /**
  25990. Classes can implement this interface and register themselves with the Desktop class
  25991. to receive callbacks when the currently focused component changes.
  25992. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  25993. */
  25994. class JUCE_API FocusChangeListener
  25995. {
  25996. public:
  25997. /** Destructor. */
  25998. virtual ~FocusChangeListener() {}
  25999. /** Callback to indicate that the currently focused component has changed. */
  26000. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  26001. };
  26002. /**
  26003. Describes and controls aspects of the computer's desktop.
  26004. */
  26005. class JUCE_API Desktop : private DeletedAtShutdown,
  26006. private Timer,
  26007. private AsyncUpdater
  26008. {
  26009. public:
  26010. /** There's only one dektop object, and this method will return it.
  26011. */
  26012. static Desktop& JUCE_CALLTYPE getInstance();
  26013. /** Returns a list of the positions of all the monitors available.
  26014. The first rectangle in the list will be the main monitor area.
  26015. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  26016. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  26017. */
  26018. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const;
  26019. /** Returns the position and size of the main monitor.
  26020. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  26021. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  26022. */
  26023. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const noexcept;
  26024. /** Returns the position and size of the monitor which contains this co-ordinate.
  26025. If none of the monitors contains the point, this will just return the
  26026. main monitor.
  26027. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  26028. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  26029. */
  26030. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  26031. /** Returns the mouse position.
  26032. The co-ordinates are relative to the top-left of the main monitor.
  26033. Note that this is just a shortcut for calling getMainMouseSource().getScreenPosition(), and
  26034. you should only resort to grabbing the global mouse position if there's really no
  26035. way to get the coordinates via a mouse event callback instead.
  26036. */
  26037. static const Point<int> getMousePosition();
  26038. /** Makes the mouse pointer jump to a given location.
  26039. The co-ordinates are relative to the top-left of the main monitor.
  26040. */
  26041. static void setMousePosition (const Point<int>& newPosition);
  26042. /** Returns the last position at which a mouse button was pressed.
  26043. Note that this is just a shortcut for calling getMainMouseSource().getLastMouseDownPosition(),
  26044. and in a multi-touch environment, it doesn't make much sense. ALWAYS prefer to
  26045. get this information via other means, such as MouseEvent::getMouseDownScreenPosition()
  26046. if possible, and only ever call this as a last resort.
  26047. */
  26048. static const Point<int> getLastMouseDownPosition();
  26049. /** Returns the number of times the mouse button has been clicked since the
  26050. app started.
  26051. Each mouse-down event increments this number by 1.
  26052. */
  26053. static int getMouseButtonClickCounter();
  26054. /** This lets you prevent the screensaver from becoming active.
  26055. Handy if you're running some sort of presentation app where having a screensaver
  26056. appear would be annoying.
  26057. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  26058. won't enable a screensaver unless the user has actually set one up).
  26059. The disablement will only happen while the Juce application is the foreground
  26060. process - if another task is running in front of it, then the screensaver will
  26061. be unaffected.
  26062. @see isScreenSaverEnabled
  26063. */
  26064. static void setScreenSaverEnabled (bool isEnabled);
  26065. /** Returns true if the screensaver has not been turned off.
  26066. This will return the last value passed into setScreenSaverEnabled(). Note that
  26067. it won't tell you whether the user is actually using a screen saver, just
  26068. whether this app is deliberately preventing one from running.
  26069. @see setScreenSaverEnabled
  26070. */
  26071. static bool isScreenSaverEnabled();
  26072. /** Registers a MouseListener that will receive all mouse events that occur on
  26073. any component.
  26074. @see removeGlobalMouseListener
  26075. */
  26076. void addGlobalMouseListener (MouseListener* listener);
  26077. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  26078. method.
  26079. @see addGlobalMouseListener
  26080. */
  26081. void removeGlobalMouseListener (MouseListener* listener);
  26082. /** Registers a MouseListener that will receive a callback whenever the focused
  26083. component changes.
  26084. */
  26085. void addFocusChangeListener (FocusChangeListener* listener);
  26086. /** Unregisters a listener that was added with addFocusChangeListener(). */
  26087. void removeFocusChangeListener (FocusChangeListener* listener);
  26088. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  26089. The component must already be on the desktop for this method to work. It will
  26090. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  26091. etc will be hidden.
  26092. To exit kiosk mode, just call setKioskModeComponent (nullptr). When this is called,
  26093. the component that's currently being used will be resized back to the size
  26094. and position it was in before being put into this mode.
  26095. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  26096. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  26097. to hide as much on-screen paraphenalia as possible.
  26098. */
  26099. void setKioskModeComponent (Component* componentToUse,
  26100. bool allowMenusAndBars = true);
  26101. /** Returns the component that is currently being used in kiosk-mode.
  26102. This is the component that was last set by setKioskModeComponent(). If none
  26103. has been set, this returns 0.
  26104. */
  26105. Component* getKioskModeComponent() const noexcept { return kioskModeComponent; }
  26106. /** Returns the number of components that are currently active as top-level
  26107. desktop windows.
  26108. @see getComponent, Component::addToDesktop
  26109. */
  26110. int getNumComponents() const noexcept;
  26111. /** Returns one of the top-level desktop window components.
  26112. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  26113. index is out-of-range.
  26114. @see getNumComponents, Component::addToDesktop
  26115. */
  26116. Component* getComponent (int index) const noexcept;
  26117. /** Finds the component at a given screen location.
  26118. This will drill down into top-level windows to find the child component at
  26119. the given position.
  26120. Returns 0 if the co-ordinates are inside a non-Juce window.
  26121. */
  26122. Component* findComponentAt (const Point<int>& screenPosition) const;
  26123. /** The Desktop object has a ComponentAnimator instance which can be used for performing
  26124. your animations.
  26125. Having a single shared ComponentAnimator object makes it more efficient when multiple
  26126. components are being moved around simultaneously. It's also more convenient than having
  26127. to manage your own instance of one.
  26128. @see ComponentAnimator
  26129. */
  26130. ComponentAnimator& getAnimator() noexcept { return animator; }
  26131. /** Returns the number of MouseInputSource objects the system has at its disposal.
  26132. In a traditional single-mouse system, there might be only one object. On a multi-touch
  26133. system, there could be one input source per potential finger.
  26134. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  26135. @see getMouseSource
  26136. */
  26137. int getNumMouseSources() const noexcept { return mouseSources.size(); }
  26138. /** Returns one of the system's MouseInputSource objects.
  26139. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  26140. a null pointer.
  26141. In a traditional single-mouse system, there might be only one object. On a multi-touch
  26142. system, there could be one input source per potential finger.
  26143. */
  26144. MouseInputSource* getMouseSource (int index) const noexcept { return mouseSources [index]; }
  26145. /** Returns the main mouse input device that the system is using.
  26146. @see getNumMouseSources()
  26147. */
  26148. MouseInputSource& getMainMouseSource() const noexcept { return *mouseSources.getUnchecked(0); }
  26149. /** Returns the number of mouse-sources that are currently being dragged.
  26150. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  26151. juce component has the button down on it. In a multi-touch system, this could
  26152. be any number from 0 to the number of simultaneous touches that can be detected.
  26153. */
  26154. int getNumDraggingMouseSources() const noexcept;
  26155. /** Returns one of the mouse sources that's currently being dragged.
  26156. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  26157. out of range, or if no mice or fingers are down, this will return a null pointer.
  26158. */
  26159. MouseInputSource* getDraggingMouseSource (int index) const noexcept;
  26160. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  26161. current mouse-drag operation.
  26162. This allows you to make sure that mouseDrag() events are sent continuously, even
  26163. when the mouse isn't moving. This can be useful for things like auto-scrolling
  26164. components when the mouse is near an edge.
  26165. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  26166. minimum interval between consecutive mouse drag callbacks. The callbacks
  26167. will continue until the mouse is released, and then the interval will be reset,
  26168. so you need to make sure it's called every time you begin a drag event.
  26169. Passing an interval of 0 or less will cancel the auto-repeat.
  26170. @see mouseDrag
  26171. */
  26172. void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  26173. /** In a tablet device which can be turned around, this is used to inidicate the orientation. */
  26174. enum DisplayOrientation
  26175. {
  26176. upright = 1, /**< Indicates that the display is the normal way up. */
  26177. upsideDown = 2, /**< Indicates that the display is upside-down. */
  26178. rotatedClockwise = 4, /**< Indicates that the display is turned 90 degrees clockwise from its upright position. */
  26179. rotatedAntiClockwise = 8, /**< Indicates that the display is turned 90 degrees anti-clockwise from its upright position. */
  26180. allOrientations = 1 + 2 + 4 + 8 /**< A combination of all the orientation values */
  26181. };
  26182. /** In a tablet device which can be turned around, this returns the current orientation. */
  26183. DisplayOrientation getCurrentOrientation() const;
  26184. /** Sets which orientations the display is allowed to auto-rotate to.
  26185. For devices that support rotating desktops, this lets you specify which of the orientations your app can use.
  26186. The parameter is a bitwise or-ed combination of the values in DisplayOrientation, and must contain at least one
  26187. set bit.
  26188. */
  26189. void setOrientationsEnabled (int allowedOrientations);
  26190. /** Returns whether the display is allowed to auto-rotate to the given orientation.
  26191. Each orientation can be enabled using setOrientationEnabled(). By default, all orientations are allowed.
  26192. */
  26193. bool isOrientationEnabled (DisplayOrientation orientation) const noexcept;
  26194. /** Tells this object to refresh its idea of what the screen resolution is.
  26195. (Called internally by the native code).
  26196. */
  26197. void refreshMonitorSizes();
  26198. /** True if the OS supports semitransparent windows */
  26199. static bool canUseSemiTransparentWindows() noexcept;
  26200. private:
  26201. static Desktop* instance;
  26202. friend class Component;
  26203. friend class ComponentPeer;
  26204. friend class MouseInputSource;
  26205. friend class MouseInputSourceInternal;
  26206. friend class DeletedAtShutdown;
  26207. friend class TopLevelWindowManager;
  26208. OwnedArray <MouseInputSource> mouseSources;
  26209. void createMouseInputSources();
  26210. ListenerList <MouseListener> mouseListeners;
  26211. ListenerList <FocusChangeListener> focusListeners;
  26212. Array <Component*> desktopComponents;
  26213. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  26214. Point<int> lastFakeMouseMove;
  26215. void sendMouseMove();
  26216. int mouseClickCounter;
  26217. void incrementMouseClickCounter() noexcept;
  26218. ScopedPointer<Timer> dragRepeater;
  26219. Component* kioskModeComponent;
  26220. Rectangle<int> kioskComponentOriginalBounds;
  26221. int allowedOrientations;
  26222. ComponentAnimator animator;
  26223. void timerCallback();
  26224. void resetTimer();
  26225. int getNumDisplayMonitors() const noexcept;
  26226. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const noexcept;
  26227. static void getCurrentMonitorPositions (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea);
  26228. void addDesktopComponent (Component* c);
  26229. void removeDesktopComponent (Component* c);
  26230. void componentBroughtToFront (Component* c);
  26231. static void setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  26232. void triggerFocusCallback();
  26233. void handleAsyncUpdate();
  26234. Desktop();
  26235. ~Desktop();
  26236. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Desktop);
  26237. };
  26238. #endif // __JUCE_DESKTOP_JUCEHEADER__
  26239. /*** End of inlined file: juce_Desktop.h ***/
  26240. class KeyPressMappingSet;
  26241. class ApplicationCommandManagerListener;
  26242. /**
  26243. One of these objects holds a list of all the commands your app can perform,
  26244. and despatches these commands when needed.
  26245. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  26246. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  26247. to invoke automatically, which means you don't have to handle the result of a menu
  26248. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  26249. which can choose which events they want to handle.
  26250. This architecture also allows for nested ApplicationCommandTargets, so that for example
  26251. you could have two different objects, one inside the other, both of which can respond to
  26252. a "delete" command. Depending on which one has focus, the command will be sent to the
  26253. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  26254. method.
  26255. To set up your app to use commands, you'll need to do the following:
  26256. - Create a global ApplicationCommandManager to hold the list of all possible
  26257. commands. (This will also manage a set of key-mappings for them).
  26258. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  26259. This allows the object to provide a list of commands that it can perform, and
  26260. to handle them.
  26261. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  26262. or ApplicationCommandManager::registerCommand().
  26263. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  26264. method to access the key-mapper object, which you will need to register as a key-listener
  26265. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  26266. about setting this up.
  26267. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  26268. cause these commands to be invoked automatically.
  26269. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  26270. When a command is invoked, the ApplicationCommandManager will try to choose the best
  26271. ApplicationCommandTarget to receive the specified command. To do this it will use the
  26272. current keyboard focus to see which component might be interested, and will search the
  26273. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  26274. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  26275. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  26276. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  26277. point if the command still hasn't been performed, it will be passed to the current
  26278. JUCEApplication object (which is itself an ApplicationCommandTarget).
  26279. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  26280. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  26281. the object yourself.
  26282. @see ApplicationCommandTarget, ApplicationCommandInfo
  26283. */
  26284. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  26285. private FocusChangeListener
  26286. {
  26287. public:
  26288. /** Creates an ApplicationCommandManager.
  26289. Once created, you'll need to register all your app's commands with it, using
  26290. ApplicationCommandManager::registerAllCommandsForTarget() or
  26291. ApplicationCommandManager::registerCommand().
  26292. */
  26293. ApplicationCommandManager();
  26294. /** Destructor.
  26295. Make sure that you don't delete this if pointers to it are still being used by
  26296. objects such as PopupMenus or Buttons.
  26297. */
  26298. virtual ~ApplicationCommandManager();
  26299. /** Clears the current list of all commands.
  26300. Note that this will also clear the contents of the KeyPressMappingSet.
  26301. */
  26302. void clearCommands();
  26303. /** Adds a command to the list of registered commands.
  26304. @see registerAllCommandsForTarget
  26305. */
  26306. void registerCommand (const ApplicationCommandInfo& newCommand);
  26307. /** Adds all the commands that this target publishes to the manager's list.
  26308. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  26309. to get details about all the commands that this target can do, and will call
  26310. registerCommand() to add each one to the manger's list.
  26311. @see registerCommand
  26312. */
  26313. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  26314. /** Removes the command with a specified ID.
  26315. Note that this will also remove any key mappings that are mapped to the command.
  26316. */
  26317. void removeCommand (CommandID commandID);
  26318. /** This should be called to tell the manager that one of its registered commands may have changed
  26319. its active status.
  26320. Because the command manager only finds out whether a command is active or inactive by querying
  26321. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  26322. allows things like buttons to update their enablement, etc.
  26323. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  26324. for any registered listeners.
  26325. */
  26326. void commandStatusChanged();
  26327. /** Returns the number of commands that have been registered.
  26328. @see registerCommand
  26329. */
  26330. int getNumCommands() const noexcept { return commands.size(); }
  26331. /** Returns the details about one of the registered commands.
  26332. The index is between 0 and (getNumCommands() - 1).
  26333. */
  26334. const ApplicationCommandInfo* getCommandForIndex (int index) const noexcept { return commands [index]; }
  26335. /** Returns the details about a given command ID.
  26336. This will search the list of registered commands for one with the given command
  26337. ID number, and return its associated info. If no matching command is found, this
  26338. will return 0.
  26339. */
  26340. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const noexcept;
  26341. /** Returns the name field for a command.
  26342. An empty string is returned if no command with this ID has been registered.
  26343. @see getDescriptionOfCommand
  26344. */
  26345. const String getNameOfCommand (CommandID commandID) const noexcept;
  26346. /** Returns the description field for a command.
  26347. An empty string is returned if no command with this ID has been registered. If the
  26348. command has no description, this will return its short name field instead.
  26349. @see getNameOfCommand
  26350. */
  26351. const String getDescriptionOfCommand (CommandID commandID) const noexcept;
  26352. /** Returns the list of categories.
  26353. This will go through all registered commands, and return a list of all the distict
  26354. categoryName values from their ApplicationCommandInfo structure.
  26355. @see getCommandsInCategory()
  26356. */
  26357. const StringArray getCommandCategories() const;
  26358. /** Returns a list of all the command UIDs in a particular category.
  26359. @see getCommandCategories()
  26360. */
  26361. const Array <CommandID> getCommandsInCategory (const String& categoryName) const;
  26362. /** Returns the manager's internal set of key mappings.
  26363. This object can be used to edit the keypresses. To actually link this object up
  26364. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  26365. class.
  26366. @see KeyPressMappingSet
  26367. */
  26368. KeyPressMappingSet* getKeyMappings() const noexcept { return keyMappings; }
  26369. /** Invokes the given command directly, sending it to the default target.
  26370. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  26371. structure.
  26372. */
  26373. bool invokeDirectly (CommandID commandID, bool asynchronously);
  26374. /** Sends a command to the default target.
  26375. This will choose a target using getFirstCommandTarget(), and send the specified command
  26376. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  26377. first target can't handle the command, it will be passed on to targets further down the
  26378. chain (see ApplicationCommandTarget::invoke() for more info).
  26379. @param invocationInfo this must be correctly filled-in, describing the context for
  26380. the invocation.
  26381. @param asynchronously if false, the command will be performed before this method returns.
  26382. If true, a message will be posted so that the command will be performed
  26383. later on the message thread, and this method will return immediately.
  26384. @see ApplicationCommandTarget::invoke
  26385. */
  26386. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  26387. bool asynchronously);
  26388. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  26389. Whenever the manager needs to know which target a command should be sent to, it calls
  26390. this method to determine the first one to try.
  26391. By default, this method will return the target that was set by calling setFirstCommandTarget().
  26392. If no target is set, it will return the result of findDefaultComponentTarget().
  26393. If you need to make sure all commands go via your own custom target, then you can
  26394. either use setFirstCommandTarget() to specify a single target, or override this method
  26395. if you need more complex logic to choose one.
  26396. It may return 0 if no targets are available.
  26397. @see getTargetForCommand, invoke, invokeDirectly
  26398. */
  26399. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  26400. /** Sets a target to be returned by getFirstCommandTarget().
  26401. If this is set to 0, then getFirstCommandTarget() will by default return the
  26402. result of findDefaultComponentTarget().
  26403. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  26404. deleting the target object.
  26405. */
  26406. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) noexcept;
  26407. /** Tries to find the best target to use to perform a given command.
  26408. This will call getFirstCommandTarget() to find the preferred target, and will
  26409. check whether that target can handle the given command. If it can't, then it'll use
  26410. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  26411. so on until no more are available.
  26412. If no targets are found that can perform the command, this method will return 0.
  26413. If a target is found, then it will get the target to fill-in the upToDateInfo
  26414. structure with the latest info about that command, so that the caller can see
  26415. whether the command is disabled, ticked, etc.
  26416. */
  26417. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  26418. ApplicationCommandInfo& upToDateInfo);
  26419. /** Registers a listener that will be called when various events occur. */
  26420. void addListener (ApplicationCommandManagerListener* listener);
  26421. /** Deregisters a previously-added listener. */
  26422. void removeListener (ApplicationCommandManagerListener* listener);
  26423. /** Looks for a suitable command target based on which Components have the keyboard focus.
  26424. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  26425. but is exposed here in case it's useful.
  26426. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  26427. windows, etc., and using the findTargetForComponent() method.
  26428. */
  26429. static ApplicationCommandTarget* findDefaultComponentTarget();
  26430. /** Examines this component and all its parents in turn, looking for the first one
  26431. which is a ApplicationCommandTarget.
  26432. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  26433. that class.
  26434. */
  26435. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  26436. private:
  26437. OwnedArray <ApplicationCommandInfo> commands;
  26438. ListenerList <ApplicationCommandManagerListener> listeners;
  26439. ScopedPointer <KeyPressMappingSet> keyMappings;
  26440. ApplicationCommandTarget* firstTarget;
  26441. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  26442. void handleAsyncUpdate();
  26443. void globalFocusChanged (Component*);
  26444. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  26445. // This is just here to cause a compile error in old code that hasn't been changed to use the new
  26446. // version of this method.
  26447. virtual short getFirstCommandTarget() { return 0; }
  26448. #endif
  26449. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandManager);
  26450. };
  26451. /**
  26452. A listener that receives callbacks from an ApplicationCommandManager when
  26453. commands are invoked or the command list is changed.
  26454. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  26455. */
  26456. class JUCE_API ApplicationCommandManagerListener
  26457. {
  26458. public:
  26459. /** Destructor. */
  26460. virtual ~ApplicationCommandManagerListener() {}
  26461. /** Called when an app command is about to be invoked. */
  26462. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  26463. /** Called when commands are registered or deregistered from the
  26464. command manager, or when commands are made active or inactive.
  26465. Note that if you're using this to watch for changes to whether a command is disabled,
  26466. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  26467. whenever the status of your command might have changed.
  26468. */
  26469. virtual void applicationCommandListChanged() = 0;
  26470. };
  26471. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  26472. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  26473. #endif
  26474. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  26475. #endif
  26476. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26477. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  26478. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26479. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26480. /*** Start of inlined file: juce_PropertiesFile.h ***/
  26481. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  26482. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  26483. /** Wrapper on a file that stores a list of key/value data pairs.
  26484. Useful for storing application settings, etc. See the PropertySet class for
  26485. the interfaces that read and write values.
  26486. Not designed for very large amounts of data, as it keeps all the values in
  26487. memory and writes them out to disk lazily when they are changed.
  26488. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  26489. with it, and these will be signalled when a value changes.
  26490. @see PropertySet
  26491. */
  26492. class JUCE_API PropertiesFile : public PropertySet,
  26493. public ChangeBroadcaster,
  26494. private Timer
  26495. {
  26496. public:
  26497. enum FileFormatOptions
  26498. {
  26499. ignoreCaseOfKeyNames = 1,
  26500. storeAsBinary = 2,
  26501. storeAsCompressedBinary = 4,
  26502. storeAsXML = 8
  26503. };
  26504. /**
  26505. Creates a PropertiesFile object.
  26506. @param file the file to use
  26507. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  26508. is changed, the object will wait for this amount
  26509. of time and then save the file. If zero, the file
  26510. will be written to disk immediately on being changed
  26511. (which might be slow, as it'll re-write synchronously
  26512. each time a value-change method is called). If it is
  26513. less than zero, the file won't be saved until
  26514. save() or saveIfNeeded() are explicitly called.
  26515. @param optionFlags a combination of the flags in the FileFormatOptions
  26516. enum, which specify the type of file to save, and other
  26517. options.
  26518. @param processLock an optional InterprocessLock object that will be used to
  26519. prevent multiple threads or processes from writing to the file
  26520. at the same time. The PropertiesFile will keep a pointer to
  26521. this object but will not take ownership of it - the caller is
  26522. responsible for making sure that the lock doesn't get deleted
  26523. before the PropertiesFile has been deleted.
  26524. */
  26525. PropertiesFile (const File& file,
  26526. int millisecondsBeforeSaving,
  26527. int optionFlags,
  26528. InterProcessLock* processLock = nullptr);
  26529. /** Destructor.
  26530. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  26531. */
  26532. ~PropertiesFile();
  26533. /** Returns true if this file was created from a valid (or non-existent) file.
  26534. If the file failed to load correctly because it was corrupt or had insufficient
  26535. access, this will be false.
  26536. */
  26537. bool isValidFile() const noexcept { return loadedOk; }
  26538. /** This will flush all the values to disk if they've changed since the last
  26539. time they were saved.
  26540. Returns false if it fails to write to the file for some reason (maybe because
  26541. it's read-only or the directory doesn't exist or something).
  26542. @see save
  26543. */
  26544. bool saveIfNeeded();
  26545. /** This will force a write-to-disk of the current values, regardless of whether
  26546. anything has changed since the last save.
  26547. Returns false if it fails to write to the file for some reason (maybe because
  26548. it's read-only or the directory doesn't exist or something).
  26549. @see saveIfNeeded
  26550. */
  26551. bool save();
  26552. /** Returns true if the properties have been altered since the last time they were saved.
  26553. The file is flagged as needing to be saved when you change a value, but you can
  26554. explicitly set this flag with setNeedsToBeSaved().
  26555. */
  26556. bool needsToBeSaved() const;
  26557. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  26558. @see needsToBeSaved
  26559. */
  26560. void setNeedsToBeSaved (bool needsToBeSaved);
  26561. /** Returns the file that's being used. */
  26562. const File getFile() const { return file; }
  26563. /** Handy utility to create a properties file in whatever the standard OS-specific
  26564. location is for these things.
  26565. This uses getDefaultAppSettingsFile() to decide what file to create, then
  26566. creates a PropertiesFile object with the specified properties. See
  26567. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  26568. what the parameters do.
  26569. @see getDefaultAppSettingsFile
  26570. */
  26571. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  26572. const String& fileNameSuffix,
  26573. const String& folderName,
  26574. bool commonToAllUsers,
  26575. int millisecondsBeforeSaving,
  26576. int propertiesFileOptions,
  26577. InterProcessLock* processLock = nullptr);
  26578. /** Handy utility to choose a file in the standard OS-dependent location for application
  26579. settings files.
  26580. So on a Mac, this will return a file called:
  26581. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  26582. On Windows it'll return something like:
  26583. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  26584. On Linux it'll return
  26585. ~/.[folderName]/[applicationName].[fileNameSuffix]
  26586. If you pass an empty string as the folder name, it'll use the app name for this (or
  26587. omit the folder name on the Mac).
  26588. If commonToAllUsers is true, then this will return the same file for all users of the
  26589. computer, regardless of the current user. If it is false, the file will be specific to
  26590. only the current user. Use this to choose whether you're saving settings that are common
  26591. or user-specific.
  26592. */
  26593. static const File getDefaultAppSettingsFile (const String& applicationName,
  26594. const String& fileNameSuffix,
  26595. const String& folderName,
  26596. bool commonToAllUsers);
  26597. protected:
  26598. virtual void propertyChanged();
  26599. private:
  26600. File file;
  26601. int timerInterval;
  26602. const int options;
  26603. bool loadedOk, needsWriting;
  26604. InterProcessLock* processLock;
  26605. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  26606. InterProcessLock::ScopedLockType* createProcessLock() const;
  26607. void timerCallback();
  26608. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertiesFile);
  26609. };
  26610. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  26611. /*** End of inlined file: juce_PropertiesFile.h ***/
  26612. /**
  26613. Manages a collection of properties.
  26614. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  26615. as a singleton.
  26616. It holds two different PropertiesFile objects internally, one for user-specific
  26617. settings (stored in your user directory), and one for settings that are common to
  26618. all users (stored in a folder accessible to all users).
  26619. The class manages the creation of these files on-demand, allowing access via the
  26620. getUserSettings() and getCommonSettings() methods. It also has a few handy
  26621. methods like testWriteAccess() to check that the files can be saved.
  26622. If you're using one of these as a singleton, then your app's start-up code should
  26623. first of all call setStorageParameters() to tell it the parameters to use to create
  26624. the properties files.
  26625. @see PropertiesFile
  26626. */
  26627. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  26628. {
  26629. public:
  26630. /**
  26631. Creates an ApplicationProperties object.
  26632. Before using it, you must call setStorageParameters() to give it the info
  26633. it needs to create the property files.
  26634. */
  26635. ApplicationProperties();
  26636. /** Destructor. */
  26637. ~ApplicationProperties();
  26638. juce_DeclareSingleton (ApplicationProperties, false)
  26639. /** Gives the object the information it needs to create the appropriate properties files.
  26640. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  26641. info about how these parameters are used.
  26642. */
  26643. void setStorageParameters (const String& applicationName,
  26644. const String& fileNameSuffix,
  26645. const String& folderName,
  26646. int millisecondsBeforeSaving,
  26647. int propertiesFileOptions,
  26648. InterProcessLock* processLock = nullptr);
  26649. /** Tests whether the files can be successfully written to, and can show
  26650. an error message if not.
  26651. Returns true if none of the tests fail.
  26652. @param testUserSettings if true, the user settings file will be tested
  26653. @param testCommonSettings if true, the common settings file will be tested
  26654. @param showWarningDialogOnFailure if true, the method will show a helpful error
  26655. message box if either of the tests fail
  26656. */
  26657. bool testWriteAccess (bool testUserSettings,
  26658. bool testCommonSettings,
  26659. bool showWarningDialogOnFailure);
  26660. /** Returns the user settings file.
  26661. The first time this is called, it will create and load the properties file.
  26662. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  26663. the common settings are used as a second-chance place to look. This is done via the
  26664. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  26665. to the fallback for the user settings.
  26666. @see getCommonSettings
  26667. */
  26668. PropertiesFile* getUserSettings();
  26669. /** Returns the common settings file.
  26670. The first time this is called, it will create and load the properties file.
  26671. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  26672. read-only (e.g. because the user doesn't have permission to write
  26673. to shared files), then this will return the user settings instead,
  26674. (like getUserSettings() would do). This is handy if you'd like to
  26675. write a value to the common settings, but if that's no possible,
  26676. then you'd rather write to the user settings than none at all.
  26677. If returnUserPropsIfReadOnly is false, this method will always return
  26678. the common settings, even if any changes to them can't be saved.
  26679. @see getUserSettings
  26680. */
  26681. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly);
  26682. /** Saves both files if they need to be saved.
  26683. @see PropertiesFile::saveIfNeeded
  26684. */
  26685. bool saveIfNeeded();
  26686. /** Flushes and closes both files if they are open.
  26687. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  26688. and closes both files. They will then be re-opened the next time getUserSettings()
  26689. or getCommonSettings() is called.
  26690. */
  26691. void closeFiles();
  26692. private:
  26693. ScopedPointer <PropertiesFile> userProps, commonProps;
  26694. String appName, fileSuffix, folderName;
  26695. int msBeforeSaving, options;
  26696. int commonSettingsAreReadOnly;
  26697. InterProcessLock* processLock;
  26698. void openFiles();
  26699. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationProperties);
  26700. };
  26701. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26702. /*** End of inlined file: juce_ApplicationProperties.h ***/
  26703. #endif
  26704. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26705. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  26706. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26707. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26708. /*** Start of inlined file: juce_AudioFormat.h ***/
  26709. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26710. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  26711. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  26712. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26713. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26714. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  26715. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26716. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26717. /**
  26718. This class a container which holds all the classes pertaining to the AudioData::Pointer
  26719. audio sample format class.
  26720. @see AudioData::Pointer.
  26721. */
  26722. class JUCE_API AudioData
  26723. {
  26724. public:
  26725. // These types can be used as the SampleFormat template parameter for the AudioData::Pointer class.
  26726. class Int8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit integer packed data format. */
  26727. class UInt8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit unsigned integer packed data format. */
  26728. class Int16; /**< Used as a template parameter for AudioData::Pointer. Indicates an 16-bit integer packed data format. */
  26729. class Int24; /**< Used as a template parameter for AudioData::Pointer. Indicates an 24-bit integer packed data format. */
  26730. class Int32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit integer packed data format. */
  26731. class Float32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit float data format. */
  26732. // These types can be used as the Endianness template parameter for the AudioData::Pointer class.
  26733. class BigEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in big-endian order. */
  26734. class LittleEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in little-endian order. */
  26735. class NativeEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in the CPU's native endianness. */
  26736. // These types can be used as the InterleavingType template parameter for the AudioData::Pointer class.
  26737. class NonInterleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored contiguously. */
  26738. class Interleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are interleaved with a number of other channels. */
  26739. // These types can be used as the Constness template parameter for the AudioData::Pointer class.
  26740. class NonConst; /**< Used as a template parameter for AudioData::Pointer. Indicates that the pointer can be used for non-const data. */
  26741. class Const; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples can only be used for const data.. */
  26742. #ifndef DOXYGEN
  26743. class BigEndian
  26744. {
  26745. public:
  26746. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) noexcept { return s.getAsFloatBE(); }
  26747. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) noexcept { s.setAsFloatBE (newValue); }
  26748. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) noexcept { return s.getAsInt32BE(); }
  26749. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) noexcept { s.setAsInt32BE (newValue); }
  26750. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) noexcept { dest.copyFromBE (source); }
  26751. enum { isBigEndian = 1 };
  26752. };
  26753. class LittleEndian
  26754. {
  26755. public:
  26756. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) noexcept { return s.getAsFloatLE(); }
  26757. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) noexcept { s.setAsFloatLE (newValue); }
  26758. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) noexcept { return s.getAsInt32LE(); }
  26759. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) noexcept { s.setAsInt32LE (newValue); }
  26760. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) noexcept { dest.copyFromLE (source); }
  26761. enum { isBigEndian = 0 };
  26762. };
  26763. #if JUCE_BIG_ENDIAN
  26764. class NativeEndian : public BigEndian {};
  26765. #else
  26766. class NativeEndian : public LittleEndian {};
  26767. #endif
  26768. class Int8
  26769. {
  26770. public:
  26771. inline Int8 (void* data_) noexcept : data (static_cast <int8*> (data_)) {}
  26772. inline void advance() noexcept { ++data; }
  26773. inline void skip (int numSamples) noexcept { data += numSamples; }
  26774. inline float getAsFloatLE() const noexcept { return (float) (*data * (1.0 / (1.0 + maxValue))); }
  26775. inline float getAsFloatBE() const noexcept { return getAsFloatLE(); }
  26776. inline void setAsFloatLE (float newValue) noexcept { *data = (int8) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))); }
  26777. inline void setAsFloatBE (float newValue) noexcept { setAsFloatLE (newValue); }
  26778. inline int32 getAsInt32LE() const noexcept { return (int) (*data << 24); }
  26779. inline int32 getAsInt32BE() const noexcept { return getAsInt32LE(); }
  26780. inline void setAsInt32LE (int newValue) noexcept { *data = (int8) (newValue >> 24); }
  26781. inline void setAsInt32BE (int newValue) noexcept { setAsInt32LE (newValue); }
  26782. inline void clear() noexcept { *data = 0; }
  26783. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26784. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26785. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26786. inline void copyFromSameType (Int8& source) noexcept { *data = *source.data; }
  26787. int8* data;
  26788. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26789. };
  26790. class UInt8
  26791. {
  26792. public:
  26793. inline UInt8 (void* data_) noexcept : data (static_cast <uint8*> (data_)) {}
  26794. inline void advance() noexcept { ++data; }
  26795. inline void skip (int numSamples) noexcept { data += numSamples; }
  26796. inline float getAsFloatLE() const noexcept { return (float) ((*data - 128) * (1.0 / (1.0 + maxValue))); }
  26797. inline float getAsFloatBE() const noexcept { return getAsFloatLE(); }
  26798. inline void setAsFloatLE (float newValue) noexcept { *data = (uint8) jlimit (0, 255, 128 + roundToInt (newValue * (1.0 + maxValue))); }
  26799. inline void setAsFloatBE (float newValue) noexcept { setAsFloatLE (newValue); }
  26800. inline int32 getAsInt32LE() const noexcept { return (int) ((*data - 128) << 24); }
  26801. inline int32 getAsInt32BE() const noexcept { return getAsInt32LE(); }
  26802. inline void setAsInt32LE (int newValue) noexcept { *data = (uint8) (128 + (newValue >> 24)); }
  26803. inline void setAsInt32BE (int newValue) noexcept { setAsInt32LE (newValue); }
  26804. inline void clear() noexcept { *data = 128; }
  26805. inline void clearMultiple (int num) noexcept { memset (data, 128, num) ;}
  26806. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26807. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26808. inline void copyFromSameType (UInt8& source) noexcept { *data = *source.data; }
  26809. uint8* data;
  26810. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26811. };
  26812. class Int16
  26813. {
  26814. public:
  26815. inline Int16 (void* data_) noexcept : data (static_cast <uint16*> (data_)) {}
  26816. inline void advance() noexcept { ++data; }
  26817. inline void skip (int numSamples) noexcept { data += numSamples; }
  26818. inline float getAsFloatLE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfBigEndian (*data)); }
  26819. inline float getAsFloatBE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfLittleEndian (*data)); }
  26820. inline void setAsFloatLE (float newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26821. inline void setAsFloatBE (float newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26822. inline int32 getAsInt32LE() const noexcept { return (int32) (ByteOrder::swapIfBigEndian ((uint16) *data) << 16); }
  26823. inline int32 getAsInt32BE() const noexcept { return (int32) (ByteOrder::swapIfLittleEndian ((uint16) *data) << 16); }
  26824. inline void setAsInt32LE (int32 newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint16) (newValue >> 16)); }
  26825. inline void setAsInt32BE (int32 newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint16) (newValue >> 16)); }
  26826. inline void clear() noexcept { *data = 0; }
  26827. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26828. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26829. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26830. inline void copyFromSameType (Int16& source) noexcept { *data = *source.data; }
  26831. uint16* data;
  26832. enum { bytesPerSample = 2, maxValue = 0x7fff, resolution = (1 << 16), isFloat = 0 };
  26833. };
  26834. class Int24
  26835. {
  26836. public:
  26837. inline Int24 (void* data_) noexcept : data (static_cast <char*> (data_)) {}
  26838. inline void advance() noexcept { data += 3; }
  26839. inline void skip (int numSamples) noexcept { data += 3 * numSamples; }
  26840. inline float getAsFloatLE() const noexcept { return (float) (ByteOrder::littleEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  26841. inline float getAsFloatBE() const noexcept { return (float) (ByteOrder::bigEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  26842. inline void setAsFloatLE (float newValue) noexcept { ByteOrder::littleEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  26843. inline void setAsFloatBE (float newValue) noexcept { ByteOrder::bigEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  26844. inline int32 getAsInt32LE() const noexcept { return (int32) ByteOrder::littleEndian24Bit (data) << 8; }
  26845. inline int32 getAsInt32BE() const noexcept { return (int32) ByteOrder::bigEndian24Bit (data) << 8; }
  26846. inline void setAsInt32LE (int32 newValue) noexcept { ByteOrder::littleEndian24BitToChars (newValue >> 8, data); }
  26847. inline void setAsInt32BE (int32 newValue) noexcept { ByteOrder::bigEndian24BitToChars (newValue >> 8, data); }
  26848. inline void clear() noexcept { data[0] = 0; data[1] = 0; data[2] = 0; }
  26849. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26850. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26851. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26852. inline void copyFromSameType (Int24& source) noexcept { data[0] = source.data[0]; data[1] = source.data[1]; data[2] = source.data[2]; }
  26853. char* data;
  26854. enum { bytesPerSample = 3, maxValue = 0x7fffff, resolution = (1 << 8), isFloat = 0 };
  26855. };
  26856. class Int32
  26857. {
  26858. public:
  26859. inline Int32 (void* data_) noexcept : data (static_cast <uint32*> (data_)) {}
  26860. inline void advance() noexcept { ++data; }
  26861. inline void skip (int numSamples) noexcept { data += numSamples; }
  26862. inline float getAsFloatLE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfBigEndian (*data)); }
  26863. inline float getAsFloatBE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfLittleEndian (*data)); }
  26864. inline void setAsFloatLE (float newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint32) (maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
  26865. inline void setAsFloatBE (float newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint32) (maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
  26866. inline int32 getAsInt32LE() const noexcept { return (int32) ByteOrder::swapIfBigEndian (*data); }
  26867. inline int32 getAsInt32BE() const noexcept { return (int32) ByteOrder::swapIfLittleEndian (*data); }
  26868. inline void setAsInt32LE (int32 newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint32) newValue); }
  26869. inline void setAsInt32BE (int32 newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint32) newValue); }
  26870. inline void clear() noexcept { *data = 0; }
  26871. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26872. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26873. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26874. inline void copyFromSameType (Int32& source) noexcept { *data = *source.data; }
  26875. uint32* data;
  26876. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = 1, isFloat = 0 };
  26877. };
  26878. class Float32
  26879. {
  26880. public:
  26881. inline Float32 (void* data_) noexcept : data (static_cast <float*> (data_)) {}
  26882. inline void advance() noexcept { ++data; }
  26883. inline void skip (int numSamples) noexcept { data += numSamples; }
  26884. #if JUCE_BIG_ENDIAN
  26885. inline float getAsFloatBE() const noexcept { return *data; }
  26886. inline void setAsFloatBE (float newValue) noexcept { *data = newValue; }
  26887. inline float getAsFloatLE() const noexcept { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  26888. inline void setAsFloatLE (float newValue) noexcept { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  26889. #else
  26890. inline float getAsFloatLE() const noexcept { return *data; }
  26891. inline void setAsFloatLE (float newValue) noexcept { *data = newValue; }
  26892. inline float getAsFloatBE() const noexcept { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  26893. inline void setAsFloatBE (float newValue) noexcept { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  26894. #endif
  26895. inline int32 getAsInt32LE() const noexcept { return (int32) roundToInt (jlimit (-1.0, 1.0, (double) getAsFloatLE()) * (double) maxValue); }
  26896. inline int32 getAsInt32BE() const noexcept { return (int32) roundToInt (jlimit (-1.0, 1.0, (double) getAsFloatBE()) * (double) maxValue); }
  26897. inline void setAsInt32LE (int32 newValue) noexcept { setAsFloatLE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  26898. inline void setAsInt32BE (int32 newValue) noexcept { setAsFloatBE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  26899. inline void clear() noexcept { *data = 0; }
  26900. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26901. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsFloatLE (source.getAsFloat()); }
  26902. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsFloatBE (source.getAsFloat()); }
  26903. inline void copyFromSameType (Float32& source) noexcept { *data = *source.data; }
  26904. float* data;
  26905. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = (1 << 8), isFloat = 1 };
  26906. };
  26907. class NonInterleaved
  26908. {
  26909. public:
  26910. inline NonInterleaved() noexcept {}
  26911. inline NonInterleaved (const NonInterleaved&) noexcept {}
  26912. inline NonInterleaved (const int) noexcept {}
  26913. inline void copyFrom (const NonInterleaved&) noexcept {}
  26914. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) noexcept { s.advance(); }
  26915. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) noexcept { s.skip (numSamples); }
  26916. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) noexcept { s.clearMultiple (numSamples); }
  26917. template <class SampleFormatType> inline static int getNumBytesBetweenSamples (const SampleFormatType&) noexcept { return SampleFormatType::bytesPerSample; }
  26918. enum { isInterleavedType = 0, numInterleavedChannels = 1 };
  26919. };
  26920. class Interleaved
  26921. {
  26922. public:
  26923. inline Interleaved() noexcept : numInterleavedChannels (1) {}
  26924. inline Interleaved (const Interleaved& other) noexcept : numInterleavedChannels (other.numInterleavedChannels) {}
  26925. inline Interleaved (const int numInterleavedChannels_) noexcept : numInterleavedChannels (numInterleavedChannels_) {}
  26926. inline void copyFrom (const Interleaved& other) noexcept { numInterleavedChannels = other.numInterleavedChannels; }
  26927. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) noexcept { s.skip (numInterleavedChannels); }
  26928. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) noexcept { s.skip (numInterleavedChannels * numSamples); }
  26929. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) noexcept { while (--numSamples >= 0) { s.clear(); s.skip (numInterleavedChannels); } }
  26930. template <class SampleFormatType> inline int getNumBytesBetweenSamples (const SampleFormatType&) const noexcept { return numInterleavedChannels * SampleFormatType::bytesPerSample; }
  26931. int numInterleavedChannels;
  26932. enum { isInterleavedType = 1 };
  26933. };
  26934. class NonConst
  26935. {
  26936. public:
  26937. typedef void VoidType;
  26938. static inline void* toVoidPtr (VoidType* v) noexcept { return v; }
  26939. enum { isConst = 0 };
  26940. };
  26941. class Const
  26942. {
  26943. public:
  26944. typedef const void VoidType;
  26945. static inline void* toVoidPtr (VoidType* v) noexcept { return const_cast<void*> (v); }
  26946. enum { isConst = 1 };
  26947. };
  26948. #endif
  26949. /**
  26950. A pointer to a block of audio data with a particular encoding.
  26951. This object can be used to read and write from blocks of encoded audio samples. To create one, you specify
  26952. the audio format as a series of template parameters, e.g.
  26953. @code
  26954. // this creates a pointer for reading from a const array of 16-bit little-endian packed samples.
  26955. AudioData::Pointer <AudioData::Int16,
  26956. AudioData::LittleEndian,
  26957. AudioData::NonInterleaved,
  26958. AudioData::Const> pointer (someRawAudioData);
  26959. // These methods read the sample that is being pointed to
  26960. float firstSampleAsFloat = pointer.getAsFloat();
  26961. int32 firstSampleAsInt = pointer.getAsInt32();
  26962. ++pointer; // moves the pointer to the next sample.
  26963. pointer += 3; // skips the next 3 samples.
  26964. @endcode
  26965. The convertSamples() method lets you copy a range of samples from one format to another, automatically
  26966. converting its format.
  26967. @see AudioData::Converter
  26968. */
  26969. template <typename SampleFormat,
  26970. typename Endianness,
  26971. typename InterleavingType,
  26972. typename Constness>
  26973. class Pointer
  26974. {
  26975. public:
  26976. /** Creates a non-interleaved pointer from some raw data in the appropriate format.
  26977. This constructor is only used if you've specified the AudioData::NonInterleaved option -
  26978. for interleaved formats, use the constructor that also takes a number of channels.
  26979. */
  26980. Pointer (typename Constness::VoidType* sourceData) noexcept
  26981. : data (Constness::toVoidPtr (sourceData))
  26982. {
  26983. // If you're using interleaved data, call the other constructor! If you're using non-interleaved data,
  26984. // you should pass NonInterleaved as the template parameter for the interleaving type!
  26985. static_jassert (InterleavingType::isInterleavedType == 0);
  26986. }
  26987. /** Creates a pointer from some raw data in the appropriate format with the specified number of interleaved channels.
  26988. For non-interleaved data, use the other constructor.
  26989. */
  26990. Pointer (typename Constness::VoidType* sourceData, int numInterleavedChannels) noexcept
  26991. : data (Constness::toVoidPtr (sourceData)),
  26992. interleaving (numInterleavedChannels)
  26993. {
  26994. }
  26995. /** Creates a copy of another pointer. */
  26996. Pointer (const Pointer& other) noexcept
  26997. : data (other.data),
  26998. interleaving (other.interleaving)
  26999. {
  27000. }
  27001. Pointer& operator= (const Pointer& other) noexcept
  27002. {
  27003. data = other.data;
  27004. interleaving.copyFrom (other.interleaving);
  27005. return *this;
  27006. }
  27007. /** Returns the value of the first sample as a floating point value.
  27008. The value will be in the range -1.0 to 1.0 for integer formats. For floating point
  27009. formats, the value could be outside that range, although -1 to 1 is the standard range.
  27010. */
  27011. inline float getAsFloat() const noexcept { return Endianness::getAsFloat (data); }
  27012. /** Sets the value of the first sample as a floating point value.
  27013. (This method can only be used if the AudioData::NonConst option was used).
  27014. The value should be in the range -1.0 to 1.0 - for integer formats, values outside that
  27015. range will be clipped. For floating point formats, any value passed in here will be
  27016. written directly, although -1 to 1 is the standard range.
  27017. */
  27018. inline void setAsFloat (float newValue) noexcept
  27019. {
  27020. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27021. Endianness::setAsFloat (data, newValue);
  27022. }
  27023. /** Returns the value of the first sample as a 32-bit integer.
  27024. The value returned will be in the range 0x80000000 to 0x7fffffff, and shorter values will be
  27025. shifted to fill this range (e.g. if you're reading from 24-bit data, the values will be shifted up
  27026. by 8 bits when returned here). If the source data is floating point, values beyond -1.0 to 1.0 will
  27027. be clipped so that -1.0 maps onto -0x7fffffff and 1.0 maps to 0x7fffffff.
  27028. */
  27029. inline int32 getAsInt32() const noexcept { return Endianness::getAsInt32 (data); }
  27030. /** Sets the value of the first sample as a 32-bit integer.
  27031. This will be mapped to the range of the format that is being written - see getAsInt32().
  27032. */
  27033. inline void setAsInt32 (int32 newValue) noexcept
  27034. {
  27035. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27036. Endianness::setAsInt32 (data, newValue);
  27037. }
  27038. /** Moves the pointer along to the next sample. */
  27039. inline Pointer& operator++() noexcept { advance(); return *this; }
  27040. /** Moves the pointer back to the previous sample. */
  27041. inline Pointer& operator--() noexcept { interleaving.advanceDataBy (data, -1); return *this; }
  27042. /** Adds a number of samples to the pointer's position. */
  27043. Pointer& operator+= (int samplesToJump) noexcept { interleaving.advanceDataBy (data, samplesToJump); return *this; }
  27044. /** Writes a stream of samples into this pointer from another pointer.
  27045. This will copy the specified number of samples, converting between formats appropriately.
  27046. */
  27047. void convertSamples (Pointer source, int numSamples) const noexcept
  27048. {
  27049. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27050. Pointer dest (*this);
  27051. while (--numSamples >= 0)
  27052. {
  27053. dest.data.copyFromSameType (source.data);
  27054. dest.advance();
  27055. source.advance();
  27056. }
  27057. }
  27058. /** Writes a stream of samples into this pointer from another pointer.
  27059. This will copy the specified number of samples, converting between formats appropriately.
  27060. */
  27061. template <class OtherPointerType>
  27062. void convertSamples (OtherPointerType source, int numSamples) const noexcept
  27063. {
  27064. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27065. Pointer dest (*this);
  27066. if (source.getRawData() != getRawData() || source.getNumBytesBetweenSamples() >= getNumBytesBetweenSamples())
  27067. {
  27068. while (--numSamples >= 0)
  27069. {
  27070. Endianness::copyFrom (dest.data, source);
  27071. dest.advance();
  27072. ++source;
  27073. }
  27074. }
  27075. else // copy backwards if we're increasing the sample width..
  27076. {
  27077. dest += numSamples;
  27078. source += numSamples;
  27079. while (--numSamples >= 0)
  27080. Endianness::copyFrom ((--dest).data, --source);
  27081. }
  27082. }
  27083. /** Sets a number of samples to zero. */
  27084. void clearSamples (int numSamples) const noexcept
  27085. {
  27086. Pointer dest (*this);
  27087. dest.interleaving.clear (dest.data, numSamples);
  27088. }
  27089. /** Returns true if the pointer is using a floating-point format. */
  27090. static bool isFloatingPoint() noexcept { return (bool) SampleFormat::isFloat; }
  27091. /** Returns true if the format is big-endian. */
  27092. static bool isBigEndian() noexcept { return (bool) Endianness::isBigEndian; }
  27093. /** Returns the number of bytes in each sample (ignoring the number of interleaved channels). */
  27094. static int getBytesPerSample() noexcept { return (int) SampleFormat::bytesPerSample; }
  27095. /** Returns the number of interleaved channels in the format. */
  27096. int getNumInterleavedChannels() const noexcept { return (int) this->numInterleavedChannels; }
  27097. /** Returns the number of bytes between the start address of each sample. */
  27098. int getNumBytesBetweenSamples() const noexcept { return interleaving.getNumBytesBetweenSamples (data); }
  27099. /** Returns the accuracy of this format when represented as a 32-bit integer.
  27100. This is the smallest number above 0 that can be represented in the sample format, converted to
  27101. a 32-bit range. E,g. if the format is 8-bit, its resolution is 0x01000000; if the format is 24-bit,
  27102. its resolution is 0x100.
  27103. */
  27104. static int get32BitResolution() noexcept { return (int) SampleFormat::resolution; }
  27105. /** Returns a pointer to the underlying data. */
  27106. const void* getRawData() const noexcept { return data.data; }
  27107. private:
  27108. SampleFormat data;
  27109. InterleavingType interleaving; // annoyingly, making the interleaving type a superclass to take
  27110. // advantage of EBCO causes an internal compiler error in VC6..
  27111. inline void advance() noexcept { interleaving.advanceData (data); }
  27112. Pointer operator++ (int); // private to force you to use the more efficient pre-increment!
  27113. Pointer operator-- (int);
  27114. };
  27115. /** A base class for objects that are used to convert between two different sample formats.
  27116. The AudioData::ConverterInstance implements this base class and can be templated, so
  27117. you can create an instance that converts between two particular formats, and then
  27118. store this in the abstract base class.
  27119. @see AudioData::ConverterInstance
  27120. */
  27121. class Converter
  27122. {
  27123. public:
  27124. virtual ~Converter() {}
  27125. /** Converts a sequence of samples from the converter's source format into the dest format. */
  27126. virtual void convertSamples (void* destSamples, const void* sourceSamples, int numSamples) const = 0;
  27127. /** Converts a sequence of samples from the converter's source format into the dest format.
  27128. This method takes sub-channel indexes, which can be used with interleaved formats in order to choose a
  27129. particular sub-channel of the data to be used.
  27130. */
  27131. virtual void convertSamples (void* destSamples, int destSubChannel,
  27132. const void* sourceSamples, int sourceSubChannel, int numSamples) const = 0;
  27133. };
  27134. /**
  27135. A class that converts between two templated AudioData::Pointer types, and which
  27136. implements the AudioData::Converter interface.
  27137. This can be used as a concrete instance of the AudioData::Converter abstract class.
  27138. @see AudioData::Converter
  27139. */
  27140. template <class SourceSampleType, class DestSampleType>
  27141. class ConverterInstance : public Converter
  27142. {
  27143. public:
  27144. ConverterInstance (int numSourceChannels = 1, int numDestChannels = 1)
  27145. : sourceChannels (numSourceChannels), destChannels (numDestChannels)
  27146. {}
  27147. ~ConverterInstance() {}
  27148. void convertSamples (void* dest, const void* source, int numSamples) const
  27149. {
  27150. SourceSampleType s (source, sourceChannels);
  27151. DestSampleType d (dest, destChannels);
  27152. d.convertSamples (s, numSamples);
  27153. }
  27154. void convertSamples (void* dest, int destSubChannel,
  27155. const void* source, int sourceSubChannel, int numSamples) const
  27156. {
  27157. jassert (destSubChannel < destChannels && sourceSubChannel < sourceChannels);
  27158. SourceSampleType s (addBytesToPointer (source, sourceSubChannel * SourceSampleType::getBytesPerSample()), sourceChannels);
  27159. DestSampleType d (addBytesToPointer (dest, destSubChannel * DestSampleType::getBytesPerSample()), destChannels);
  27160. d.convertSamples (s, numSamples);
  27161. }
  27162. private:
  27163. JUCE_DECLARE_NON_COPYABLE (ConverterInstance);
  27164. const int sourceChannels, destChannels;
  27165. };
  27166. };
  27167. /**
  27168. A set of routines to convert buffers of 32-bit floating point data to and from
  27169. various integer formats.
  27170. Note that these functions are deprecated - the AudioData class provides a much more
  27171. flexible set of conversion classes now.
  27172. */
  27173. class JUCE_API AudioDataConverters
  27174. {
  27175. public:
  27176. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27177. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27178. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27179. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27180. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27181. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27182. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27183. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27184. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27185. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27186. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27187. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27188. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27189. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27190. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27191. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27192. enum DataFormat
  27193. {
  27194. int16LE,
  27195. int16BE,
  27196. int24LE,
  27197. int24BE,
  27198. int32LE,
  27199. int32BE,
  27200. float32LE,
  27201. float32BE,
  27202. };
  27203. static void convertFloatToFormat (DataFormat destFormat,
  27204. const float* source, void* dest, int numSamples);
  27205. static void convertFormatToFloat (DataFormat sourceFormat,
  27206. const void* source, float* dest, int numSamples);
  27207. static void interleaveSamples (const float** source, float* dest,
  27208. int numSamples, int numChannels);
  27209. static void deinterleaveSamples (const float* source, float** dest,
  27210. int numSamples, int numChannels);
  27211. private:
  27212. AudioDataConverters();
  27213. JUCE_DECLARE_NON_COPYABLE (AudioDataConverters);
  27214. };
  27215. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27216. /*** End of inlined file: juce_AudioDataConverters.h ***/
  27217. class AudioFormat;
  27218. /**
  27219. Reads samples from an audio file stream.
  27220. A subclass that reads a specific type of audio format will be created by
  27221. an AudioFormat object.
  27222. @see AudioFormat, AudioFormatWriter
  27223. */
  27224. class JUCE_API AudioFormatReader
  27225. {
  27226. protected:
  27227. /** Creates an AudioFormatReader object.
  27228. @param sourceStream the stream to read from - this will be deleted
  27229. by this object when it is no longer needed. (Some
  27230. specialised readers might not use this parameter and
  27231. can leave it as 0).
  27232. @param formatName the description that will be returned by the getFormatName()
  27233. method
  27234. */
  27235. AudioFormatReader (InputStream* sourceStream,
  27236. const String& formatName);
  27237. public:
  27238. /** Destructor. */
  27239. virtual ~AudioFormatReader();
  27240. /** Returns a description of what type of format this is.
  27241. E.g. "AIFF"
  27242. */
  27243. const String getFormatName() const noexcept { return formatName; }
  27244. /** Reads samples from the stream.
  27245. @param destSamples an array of buffers into which the sample data for each
  27246. channel will be written.
  27247. If the format is fixed-point, each channel will be written
  27248. as an array of 32-bit signed integers using the full
  27249. range -0x80000000 to 0x7fffffff, regardless of the source's
  27250. bit-depth. If it is a floating-point format, you should cast
  27251. the resulting array to a (float**) to get the values (in the
  27252. range -1.0 to 1.0 or beyond)
  27253. If the format is stereo, then destSamples[0] is the left channel
  27254. data, and destSamples[1] is the right channel.
  27255. The numDestChannels parameter indicates how many pointers this array
  27256. contains, but some of these pointers can be null if you don't want to
  27257. read data for some of the channels
  27258. @param numDestChannels the number of array elements in the destChannels array
  27259. @param startSampleInSource the position in the audio file or stream at which the samples
  27260. should be read, as a number of samples from the start of the
  27261. stream. It's ok for this to be beyond the start or end of the
  27262. available data - any samples that are out-of-range will be returned
  27263. as zeros.
  27264. @param numSamplesToRead the number of samples to read. If this is greater than the number
  27265. of samples that the file or stream contains. the result will be padded
  27266. with zeros
  27267. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  27268. for some of the channels that you pass in, then they should be filled with
  27269. copies of valid source channels.
  27270. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  27271. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  27272. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  27273. was false, then only the first channel would be filled with the file's contents, and
  27274. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  27275. from a stereo file, then the last 3 would all end up with copies of the same data.
  27276. @returns true if the operation succeeded, false if there was an error. Note
  27277. that reading sections of data beyond the extent of the stream isn't an
  27278. error - the reader should just return zeros for these regions
  27279. @see readMaxLevels
  27280. */
  27281. bool read (int* const* destSamples,
  27282. int numDestChannels,
  27283. int64 startSampleInSource,
  27284. int numSamplesToRead,
  27285. bool fillLeftoverChannelsWithCopies);
  27286. /** Finds the highest and lowest sample levels from a section of the audio stream.
  27287. This will read a block of samples from the stream, and measure the
  27288. highest and lowest sample levels from the channels in that section, returning
  27289. these as normalised floating-point levels.
  27290. @param startSample the offset into the audio stream to start reading from. It's
  27291. ok for this to be beyond the start or end of the stream.
  27292. @param numSamples how many samples to read
  27293. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  27294. @param highestLeft on return, this is the highest absolute sample from the left channel
  27295. @param lowestRight on return, this is the lowest absolute sample from the right
  27296. channel (if there is one)
  27297. @param highestRight on return, this is the highest absolute sample from the right
  27298. channel (if there is one)
  27299. @see read
  27300. */
  27301. virtual void readMaxLevels (int64 startSample,
  27302. int64 numSamples,
  27303. float& lowestLeft,
  27304. float& highestLeft,
  27305. float& lowestRight,
  27306. float& highestRight);
  27307. /** Scans the source looking for a sample whose magnitude is in a specified range.
  27308. This will read from the source, either forwards or backwards between two sample
  27309. positions, until it finds a sample whose magnitude lies between two specified levels.
  27310. If it finds a suitable sample, it returns its position; if not, it will return -1.
  27311. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  27312. points when you're searching for a continuous range of samples
  27313. @param startSample the first sample to look at
  27314. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  27315. the search will go backwards
  27316. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  27317. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  27318. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  27319. of this many consecutive samples, all of which lie
  27320. within the target range. When it finds such a sequence,
  27321. it returns the position of the first in-range sample
  27322. it found (i.e. the earliest one if scanning forwards, the
  27323. latest one if scanning backwards)
  27324. */
  27325. int64 searchForLevel (int64 startSample,
  27326. int64 numSamplesToSearch,
  27327. double magnitudeRangeMinimum,
  27328. double magnitudeRangeMaximum,
  27329. int minimumConsecutiveSamples);
  27330. /** The sample-rate of the stream. */
  27331. double sampleRate;
  27332. /** The number of bits per sample, e.g. 16, 24, 32. */
  27333. unsigned int bitsPerSample;
  27334. /** The total number of samples in the audio stream. */
  27335. int64 lengthInSamples;
  27336. /** The total number of channels in the audio stream. */
  27337. unsigned int numChannels;
  27338. /** Indicates whether the data is floating-point or fixed. */
  27339. bool usesFloatingPointData;
  27340. /** A set of metadata values that the reader has pulled out of the stream.
  27341. Exactly what these values are depends on the format, so you can
  27342. check out the format implementation code to see what kind of stuff
  27343. they understand.
  27344. */
  27345. StringPairArray metadataValues;
  27346. /** The input stream, for use by subclasses. */
  27347. InputStream* input;
  27348. /** Subclasses must implement this method to perform the low-level read operation.
  27349. Callers should use read() instead of calling this directly.
  27350. @param destSamples the array of destination buffers to fill. Some of these
  27351. pointers may be null
  27352. @param numDestChannels the number of items in the destSamples array. This
  27353. value is guaranteed not to be greater than the number of
  27354. channels that this reader object contains
  27355. @param startOffsetInDestBuffer the number of samples from the start of the
  27356. dest data at which to begin writing
  27357. @param startSampleInFile the number of samples into the source data at which
  27358. to begin reading. This value is guaranteed to be >= 0.
  27359. @param numSamples the number of samples to read
  27360. */
  27361. virtual bool readSamples (int** destSamples,
  27362. int numDestChannels,
  27363. int startOffsetInDestBuffer,
  27364. int64 startSampleInFile,
  27365. int numSamples) = 0;
  27366. protected:
  27367. /** Used by AudioFormatReader subclasses to copy data to different formats. */
  27368. template <class DestSampleType, class SourceSampleType, class SourceEndianness>
  27369. struct ReadHelper
  27370. {
  27371. typedef AudioData::Pointer <DestSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  27372. typedef AudioData::Pointer <SourceSampleType, SourceEndianness, AudioData::Interleaved, AudioData::Const> SourceType;
  27373. static void read (int** destData, int destOffset, int numDestChannels, const void* sourceData, int numSourceChannels, int numSamples) noexcept
  27374. {
  27375. for (int i = 0; i < numDestChannels; ++i)
  27376. {
  27377. if (destData[i] != nullptr)
  27378. {
  27379. DestType dest (destData[i]);
  27380. dest += destOffset;
  27381. if (i < numSourceChannels)
  27382. dest.convertSamples (SourceType (addBytesToPointer (sourceData, i * SourceType::getBytesPerSample()), numSourceChannels), numSamples);
  27383. else
  27384. dest.clearSamples (numSamples);
  27385. }
  27386. }
  27387. }
  27388. };
  27389. private:
  27390. String formatName;
  27391. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReader);
  27392. };
  27393. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27394. /*** End of inlined file: juce_AudioFormatReader.h ***/
  27395. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  27396. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27397. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27398. /*** Start of inlined file: juce_AudioSource.h ***/
  27399. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  27400. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  27401. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  27402. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27403. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27404. class AudioFormatReader;
  27405. class AudioFormatWriter;
  27406. /**
  27407. A multi-channel buffer of 32-bit floating point audio samples.
  27408. */
  27409. class JUCE_API AudioSampleBuffer
  27410. {
  27411. public:
  27412. /** Creates a buffer with a specified number of channels and samples.
  27413. The contents of the buffer will initially be undefined, so use clear() to
  27414. set all the samples to zero.
  27415. The buffer will allocate its memory internally, and this will be released
  27416. when the buffer is deleted.
  27417. */
  27418. AudioSampleBuffer (int numChannels,
  27419. int numSamples) noexcept;
  27420. /** Creates a buffer using a pre-allocated block of memory.
  27421. Note that if the buffer is resized or its number of channels is changed, it
  27422. will re-allocate memory internally and copy the existing data to this new area,
  27423. so it will then stop directly addressing this memory.
  27424. @param dataToReferTo a pre-allocated array containing pointers to the data
  27425. for each channel that should be used by this buffer. The
  27426. buffer will only refer to this memory, it won't try to delete
  27427. it when the buffer is deleted or resized.
  27428. @param numChannels the number of channels to use - this must correspond to the
  27429. number of elements in the array passed in
  27430. @param numSamples the number of samples to use - this must correspond to the
  27431. size of the arrays passed in
  27432. */
  27433. AudioSampleBuffer (float** dataToReferTo,
  27434. int numChannels,
  27435. int numSamples) noexcept;
  27436. /** Creates a buffer using a pre-allocated block of memory.
  27437. Note that if the buffer is resized or its number of channels is changed, it
  27438. will re-allocate memory internally and copy the existing data to this new area,
  27439. so it will then stop directly addressing this memory.
  27440. @param dataToReferTo a pre-allocated array containing pointers to the data
  27441. for each channel that should be used by this buffer. The
  27442. buffer will only refer to this memory, it won't try to delete
  27443. it when the buffer is deleted or resized.
  27444. @param numChannels the number of channels to use - this must correspond to the
  27445. number of elements in the array passed in
  27446. @param startSample the offset within the arrays at which the data begins
  27447. @param numSamples the number of samples to use - this must correspond to the
  27448. size of the arrays passed in
  27449. */
  27450. AudioSampleBuffer (float** dataToReferTo,
  27451. int numChannels,
  27452. int startSample,
  27453. int numSamples) noexcept;
  27454. /** Copies another buffer.
  27455. This buffer will make its own copy of the other's data, unless the buffer was created
  27456. using an external data buffer, in which case boths buffers will just point to the same
  27457. shared block of data.
  27458. */
  27459. AudioSampleBuffer (const AudioSampleBuffer& other) noexcept;
  27460. /** Copies another buffer onto this one.
  27461. This buffer's size will be changed to that of the other buffer.
  27462. */
  27463. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) noexcept;
  27464. /** Destructor.
  27465. This will free any memory allocated by the buffer.
  27466. */
  27467. virtual ~AudioSampleBuffer() noexcept;
  27468. /** Returns the number of channels of audio data that this buffer contains.
  27469. @see getSampleData
  27470. */
  27471. int getNumChannels() const noexcept { return numChannels; }
  27472. /** Returns the number of samples allocated in each of the buffer's channels.
  27473. @see getSampleData
  27474. */
  27475. int getNumSamples() const noexcept { return size; }
  27476. /** Returns a pointer one of the buffer's channels.
  27477. For speed, this doesn't check whether the channel number is out of range,
  27478. so be careful when using it!
  27479. */
  27480. float* getSampleData (const int channelNumber) const noexcept
  27481. {
  27482. jassert (isPositiveAndBelow (channelNumber, numChannels));
  27483. return channels [channelNumber];
  27484. }
  27485. /** Returns a pointer to a sample in one of the buffer's channels.
  27486. For speed, this doesn't check whether the channel and sample number
  27487. are out-of-range, so be careful when using it!
  27488. */
  27489. float* getSampleData (const int channelNumber,
  27490. const int sampleOffset) const noexcept
  27491. {
  27492. jassert (isPositiveAndBelow (channelNumber, numChannels));
  27493. jassert (isPositiveAndBelow (sampleOffset, size));
  27494. return channels [channelNumber] + sampleOffset;
  27495. }
  27496. /** Returns an array of pointers to the channels in the buffer.
  27497. Don't modify any of the pointers that are returned, and bear in mind that
  27498. these will become invalid if the buffer is resized.
  27499. */
  27500. float** getArrayOfChannels() const noexcept { return channels; }
  27501. /** Changes the buffer's size or number of channels.
  27502. This can expand or contract the buffer's length, and add or remove channels.
  27503. If keepExistingContent is true, it will try to preserve as much of the
  27504. old data as it can in the new buffer.
  27505. If clearExtraSpace is true, then any extra channels or space that is
  27506. allocated will be also be cleared. If false, then this space is left
  27507. uninitialised.
  27508. If avoidReallocating is true, then changing the buffer's size won't reduce the
  27509. amount of memory that is currently allocated (but it will still increase it if
  27510. the new size is bigger than the amount it currently has). If this is false, then
  27511. a new allocation will be done so that the buffer uses takes up the minimum amount
  27512. of memory that it needs.
  27513. */
  27514. void setSize (int newNumChannels,
  27515. int newNumSamples,
  27516. bool keepExistingContent = false,
  27517. bool clearExtraSpace = false,
  27518. bool avoidReallocating = false) noexcept;
  27519. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  27520. There's also a constructor that lets you specify arrays like this, but this
  27521. lets you change the channels dynamically.
  27522. Note that if the buffer is resized or its number of channels is changed, it
  27523. will re-allocate memory internally and copy the existing data to this new area,
  27524. so it will then stop directly addressing this memory.
  27525. @param dataToReferTo a pre-allocated array containing pointers to the data
  27526. for each channel that should be used by this buffer. The
  27527. buffer will only refer to this memory, it won't try to delete
  27528. it when the buffer is deleted or resized.
  27529. @param numChannels the number of channels to use - this must correspond to the
  27530. number of elements in the array passed in
  27531. @param numSamples the number of samples to use - this must correspond to the
  27532. size of the arrays passed in
  27533. */
  27534. void setDataToReferTo (float** dataToReferTo,
  27535. int numChannels,
  27536. int numSamples) noexcept;
  27537. /** Clears all the samples in all channels. */
  27538. void clear() noexcept;
  27539. /** Clears a specified region of all the channels.
  27540. For speed, this doesn't check whether the channel and sample number
  27541. are in-range, so be careful!
  27542. */
  27543. void clear (int startSample,
  27544. int numSamples) noexcept;
  27545. /** Clears a specified region of just one channel.
  27546. For speed, this doesn't check whether the channel and sample number
  27547. are in-range, so be careful!
  27548. */
  27549. void clear (int channel,
  27550. int startSample,
  27551. int numSamples) noexcept;
  27552. /** Applies a gain multiple to a region of one channel.
  27553. For speed, this doesn't check whether the channel and sample number
  27554. are in-range, so be careful!
  27555. */
  27556. void applyGain (int channel,
  27557. int startSample,
  27558. int numSamples,
  27559. float gain) noexcept;
  27560. /** Applies a gain multiple to a region of all the channels.
  27561. For speed, this doesn't check whether the sample numbers
  27562. are in-range, so be careful!
  27563. */
  27564. void applyGain (int startSample,
  27565. int numSamples,
  27566. float gain) noexcept;
  27567. /** Applies a range of gains to a region of a channel.
  27568. The gain that is applied to each sample will vary from
  27569. startGain on the first sample to endGain on the last Sample,
  27570. so it can be used to do basic fades.
  27571. For speed, this doesn't check whether the sample numbers
  27572. are in-range, so be careful!
  27573. */
  27574. void applyGainRamp (int channel,
  27575. int startSample,
  27576. int numSamples,
  27577. float startGain,
  27578. float endGain) noexcept;
  27579. /** Adds samples from another buffer to this one.
  27580. @param destChannel the channel within this buffer to add the samples to
  27581. @param destStartSample the start sample within this buffer's channel
  27582. @param source the source buffer to add from
  27583. @param sourceChannel the channel within the source buffer to read from
  27584. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  27585. @param numSamples the number of samples to process
  27586. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  27587. added to this buffer's samples
  27588. @see copyFrom
  27589. */
  27590. void addFrom (int destChannel,
  27591. int destStartSample,
  27592. const AudioSampleBuffer& source,
  27593. int sourceChannel,
  27594. int sourceStartSample,
  27595. int numSamples,
  27596. float gainToApplyToSource = 1.0f) noexcept;
  27597. /** Adds samples from an array of floats to one of the channels.
  27598. @param destChannel the channel within this buffer to add the samples to
  27599. @param destStartSample the start sample within this buffer's channel
  27600. @param source the source data to use
  27601. @param numSamples the number of samples to process
  27602. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  27603. added to this buffer's samples
  27604. @see copyFrom
  27605. */
  27606. void addFrom (int destChannel,
  27607. int destStartSample,
  27608. const float* source,
  27609. int numSamples,
  27610. float gainToApplyToSource = 1.0f) noexcept;
  27611. /** Adds samples from an array of floats, applying a gain ramp to them.
  27612. @param destChannel the channel within this buffer to add the samples to
  27613. @param destStartSample the start sample within this buffer's channel
  27614. @param source the source data to use
  27615. @param numSamples the number of samples to process
  27616. @param startGain the gain to apply to the first sample (this is multiplied with
  27617. the source samples before they are added to this buffer)
  27618. @param endGain the gain to apply to the final sample. The gain is linearly
  27619. interpolated between the first and last samples.
  27620. */
  27621. void addFromWithRamp (int destChannel,
  27622. int destStartSample,
  27623. const float* source,
  27624. int numSamples,
  27625. float startGain,
  27626. float endGain) noexcept;
  27627. /** Copies samples from another buffer to this one.
  27628. @param destChannel the channel within this buffer to copy the samples to
  27629. @param destStartSample the start sample within this buffer's channel
  27630. @param source the source buffer to read from
  27631. @param sourceChannel the channel within the source buffer to read from
  27632. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  27633. @param numSamples the number of samples to process
  27634. @see addFrom
  27635. */
  27636. void copyFrom (int destChannel,
  27637. int destStartSample,
  27638. const AudioSampleBuffer& source,
  27639. int sourceChannel,
  27640. int sourceStartSample,
  27641. int numSamples) noexcept;
  27642. /** Copies samples from an array of floats into one of the channels.
  27643. @param destChannel the channel within this buffer to copy the samples to
  27644. @param destStartSample the start sample within this buffer's channel
  27645. @param source the source buffer to read from
  27646. @param numSamples the number of samples to process
  27647. @see addFrom
  27648. */
  27649. void copyFrom (int destChannel,
  27650. int destStartSample,
  27651. const float* source,
  27652. int numSamples) noexcept;
  27653. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  27654. @param destChannel the channel within this buffer to copy the samples to
  27655. @param destStartSample the start sample within this buffer's channel
  27656. @param source the source buffer to read from
  27657. @param numSamples the number of samples to process
  27658. @param gain the gain to apply
  27659. @see addFrom
  27660. */
  27661. void copyFrom (int destChannel,
  27662. int destStartSample,
  27663. const float* source,
  27664. int numSamples,
  27665. float gain) noexcept;
  27666. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  27667. @param destChannel the channel within this buffer to copy the samples to
  27668. @param destStartSample the start sample within this buffer's channel
  27669. @param source the source buffer to read from
  27670. @param numSamples the number of samples to process
  27671. @param startGain the gain to apply to the first sample (this is multiplied with
  27672. the source samples before they are copied to this buffer)
  27673. @param endGain the gain to apply to the final sample. The gain is linearly
  27674. interpolated between the first and last samples.
  27675. @see addFrom
  27676. */
  27677. void copyFromWithRamp (int destChannel,
  27678. int destStartSample,
  27679. const float* source,
  27680. int numSamples,
  27681. float startGain,
  27682. float endGain) noexcept;
  27683. /** Finds the highest and lowest sample values in a given range.
  27684. @param channel the channel to read from
  27685. @param startSample the start sample within the channel
  27686. @param numSamples the number of samples to check
  27687. @param minVal on return, the lowest value that was found
  27688. @param maxVal on return, the highest value that was found
  27689. */
  27690. void findMinMax (int channel,
  27691. int startSample,
  27692. int numSamples,
  27693. float& minVal,
  27694. float& maxVal) const noexcept;
  27695. /** Finds the highest absolute sample value within a region of a channel.
  27696. */
  27697. float getMagnitude (int channel,
  27698. int startSample,
  27699. int numSamples) const noexcept;
  27700. /** Finds the highest absolute sample value within a region on all channels.
  27701. */
  27702. float getMagnitude (int startSample,
  27703. int numSamples) const noexcept;
  27704. /** Returns the root mean squared level for a region of a channel.
  27705. */
  27706. float getRMSLevel (int channel,
  27707. int startSample,
  27708. int numSamples) const noexcept;
  27709. /** Fills a section of the buffer using an AudioReader as its source.
  27710. This will convert the reader's fixed- or floating-point data to
  27711. the buffer's floating-point format, and will try to intelligently
  27712. cope with mismatches between the number of channels in the reader
  27713. and the buffer.
  27714. @see writeToAudioWriter
  27715. */
  27716. void readFromAudioReader (AudioFormatReader* reader,
  27717. int startSample,
  27718. int numSamples,
  27719. int64 readerStartSample,
  27720. bool useReaderLeftChan,
  27721. bool useReaderRightChan);
  27722. /** Writes a section of this buffer to an audio writer.
  27723. This saves you having to mess about with channels or floating/fixed
  27724. point conversion.
  27725. @see readFromAudioReader
  27726. */
  27727. void writeToAudioWriter (AudioFormatWriter* writer,
  27728. int startSample,
  27729. int numSamples) const;
  27730. private:
  27731. int numChannels, size;
  27732. size_t allocatedBytes;
  27733. float** channels;
  27734. HeapBlock <char> allocatedData;
  27735. float* preallocatedChannelSpace [32];
  27736. void allocateData();
  27737. void allocateChannels (float** dataToReferTo, int offset);
  27738. JUCE_LEAK_DETECTOR (AudioSampleBuffer);
  27739. };
  27740. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27741. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  27742. /**
  27743. Used by AudioSource::getNextAudioBlock().
  27744. */
  27745. struct JUCE_API AudioSourceChannelInfo
  27746. {
  27747. /** The destination buffer to fill with audio data.
  27748. When the AudioSource::getNextAudioBlock() method is called, the active section
  27749. of this buffer should be filled with whatever output the source produces.
  27750. Only the samples specified by the startSample and numSamples members of this structure
  27751. should be affected by the call.
  27752. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  27753. method can be treated as the input if the source is performing some kind of filter operation,
  27754. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  27755. a handy way of doing this.
  27756. The number of channels in the buffer could be anything, so the AudioSource
  27757. must cope with this in whatever way is appropriate for its function.
  27758. */
  27759. AudioSampleBuffer* buffer;
  27760. /** The first sample in the buffer from which the callback is expected
  27761. to write data. */
  27762. int startSample;
  27763. /** The number of samples in the buffer which the callback is expected to
  27764. fill with data. */
  27765. int numSamples;
  27766. /** Convenient method to clear the buffer if the source is not producing any data. */
  27767. void clearActiveBufferRegion() const
  27768. {
  27769. if (buffer != nullptr)
  27770. buffer->clear (startSample, numSamples);
  27771. }
  27772. };
  27773. /**
  27774. Base class for objects that can produce a continuous stream of audio.
  27775. An AudioSource has two states: 'prepared' and 'unprepared'.
  27776. When a source needs to be played, it is first put into a 'prepared' state by a call to
  27777. prepareToPlay(), and then repeated calls will be made to its getNextAudioBlock() method to
  27778. process the audio data.
  27779. Once playback has finished, the releaseResources() method is called to put the stream
  27780. back into an 'unprepared' state.
  27781. @see AudioFormatReaderSource, ResamplingAudioSource
  27782. */
  27783. class JUCE_API AudioSource
  27784. {
  27785. protected:
  27786. /** Creates an AudioSource. */
  27787. AudioSource() noexcept {}
  27788. public:
  27789. /** Destructor. */
  27790. virtual ~AudioSource() {}
  27791. /** Tells the source to prepare for playing.
  27792. An AudioSource has two states: prepared and unprepared.
  27793. The prepareToPlay() method is guaranteed to be called at least once on an 'unpreprared'
  27794. source to put it into a 'prepared' state before any calls will be made to getNextAudioBlock().
  27795. This callback allows the source to initialise any resources it might need when playing.
  27796. Once playback has finished, the releaseResources() method is called to put the stream
  27797. back into an 'unprepared' state.
  27798. Note that this method could be called more than once in succession without
  27799. a matching call to releaseResources(), so make sure your code is robust and
  27800. can handle that kind of situation.
  27801. @param samplesPerBlockExpected the number of samples that the source
  27802. will be expected to supply each time its
  27803. getNextAudioBlock() method is called. This
  27804. number may vary slightly, because it will be dependent
  27805. on audio hardware callbacks, and these aren't
  27806. guaranteed to always use a constant block size, so
  27807. the source should be able to cope with small variations.
  27808. @param sampleRate the sample rate that the output will be used at - this
  27809. is needed by sources such as tone generators.
  27810. @see releaseResources, getNextAudioBlock
  27811. */
  27812. virtual void prepareToPlay (int samplesPerBlockExpected,
  27813. double sampleRate) = 0;
  27814. /** Allows the source to release anything it no longer needs after playback has stopped.
  27815. This will be called when the source is no longer going to have its getNextAudioBlock()
  27816. method called, so it should release any spare memory, etc. that it might have
  27817. allocated during the prepareToPlay() call.
  27818. Note that there's no guarantee that prepareToPlay() will actually have been called before
  27819. releaseResources(), and it may be called more than once in succession, so make sure your
  27820. code is robust and doesn't make any assumptions about when it will be called.
  27821. @see prepareToPlay, getNextAudioBlock
  27822. */
  27823. virtual void releaseResources() = 0;
  27824. /** Called repeatedly to fetch subsequent blocks of audio data.
  27825. After calling the prepareToPlay() method, this callback will be made each
  27826. time the audio playback hardware (or whatever other destination the audio
  27827. data is going to) needs another block of data.
  27828. It will generally be called on a high-priority system thread, or possibly even
  27829. an interrupt, so be careful not to do too much work here, as that will cause
  27830. audio glitches!
  27831. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  27832. */
  27833. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  27834. };
  27835. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  27836. /*** End of inlined file: juce_AudioSource.h ***/
  27837. class AudioThumbnail;
  27838. /**
  27839. Writes samples to an audio file stream.
  27840. A subclass that writes a specific type of audio format will be created by
  27841. an AudioFormat object.
  27842. After creating one of these with the AudioFormat::createWriterFor() method
  27843. you can call its write() method to store the samples, and then delete it.
  27844. @see AudioFormat, AudioFormatReader
  27845. */
  27846. class JUCE_API AudioFormatWriter
  27847. {
  27848. protected:
  27849. /** Creates an AudioFormatWriter object.
  27850. @param destStream the stream to write to - this will be deleted
  27851. by this object when it is no longer needed
  27852. @param formatName the description that will be returned by the getFormatName()
  27853. method
  27854. @param sampleRate the sample rate to use - the base class just stores
  27855. this value, it doesn't do anything with it
  27856. @param numberOfChannels the number of channels to write - the base class just stores
  27857. this value, it doesn't do anything with it
  27858. @param bitsPerSample the bit depth of the stream - the base class just stores
  27859. this value, it doesn't do anything with it
  27860. */
  27861. AudioFormatWriter (OutputStream* destStream,
  27862. const String& formatName,
  27863. double sampleRate,
  27864. unsigned int numberOfChannels,
  27865. unsigned int bitsPerSample);
  27866. public:
  27867. /** Destructor. */
  27868. virtual ~AudioFormatWriter();
  27869. /** Returns a description of what type of format this is.
  27870. E.g. "AIFF file"
  27871. */
  27872. const String getFormatName() const noexcept { return formatName; }
  27873. /** Writes a set of samples to the audio stream.
  27874. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  27875. can use AudioSampleBuffer::writeToAudioWriter().
  27876. @param samplesToWrite an array of arrays containing the sample data for
  27877. each channel to write. This is a zero-terminated
  27878. array of arrays, and can contain a different number
  27879. of channels than the actual stream uses, and the
  27880. writer should do its best to cope with this.
  27881. If the format is fixed-point, each channel will be formatted
  27882. as an array of signed integers using the full 32-bit
  27883. range -0x80000000 to 0x7fffffff, regardless of the source's
  27884. bit-depth. If it is a floating-point format, you should treat
  27885. the arrays as arrays of floats, and just cast it to an (int**)
  27886. to pass it into the method.
  27887. @param numSamples the number of samples to write
  27888. */
  27889. virtual bool write (const int** samplesToWrite,
  27890. int numSamples) = 0;
  27891. /** Reads a section of samples from an AudioFormatReader, and writes these to
  27892. the output.
  27893. This will take care of any floating-point conversion that's required to convert
  27894. between the two formats. It won't deal with sample-rate conversion, though.
  27895. If numSamplesToRead < 0, it will write the entire length of the reader.
  27896. @returns false if it can't read or write properly during the operation
  27897. */
  27898. bool writeFromAudioReader (AudioFormatReader& reader,
  27899. int64 startSample,
  27900. int64 numSamplesToRead);
  27901. /** Reads some samples from an AudioSource, and writes these to the output.
  27902. The source must already have been initialised with the AudioSource::prepareToPlay() method
  27903. @param source the source to read from
  27904. @param numSamplesToRead total number of samples to read and write
  27905. @param samplesPerBlock the maximum number of samples to fetch from the source
  27906. @returns false if it can't read or write properly during the operation
  27907. */
  27908. bool writeFromAudioSource (AudioSource& source,
  27909. int numSamplesToRead,
  27910. int samplesPerBlock = 2048);
  27911. /** Writes some samples from an AudioSampleBuffer.
  27912. */
  27913. bool writeFromAudioSampleBuffer (const AudioSampleBuffer& source,
  27914. int startSample, int numSamples);
  27915. /** Returns the sample rate being used. */
  27916. double getSampleRate() const noexcept { return sampleRate; }
  27917. /** Returns the number of channels being written. */
  27918. int getNumChannels() const noexcept { return numChannels; }
  27919. /** Returns the bit-depth of the data being written. */
  27920. int getBitsPerSample() const noexcept { return bitsPerSample; }
  27921. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  27922. bool isFloatingPoint() const noexcept { return usesFloatingPointData; }
  27923. /**
  27924. Provides a FIFO for an AudioFormatWriter, allowing you to push incoming
  27925. data into a buffer which will be flushed to disk by a background thread.
  27926. */
  27927. class ThreadedWriter
  27928. {
  27929. public:
  27930. /** Creates a ThreadedWriter for a given writer and a thread.
  27931. The writer object which is passed in here will be owned and deleted by
  27932. the ThreadedWriter when it is no longer needed.
  27933. To stop the writer and flush the buffer to disk, simply delete this object.
  27934. */
  27935. ThreadedWriter (AudioFormatWriter* writer,
  27936. TimeSliceThread& backgroundThread,
  27937. int numSamplesToBuffer);
  27938. /** Destructor. */
  27939. ~ThreadedWriter();
  27940. /** Pushes some incoming audio data into the FIFO.
  27941. If there's enough free space in the buffer, this will add the data to it,
  27942. If the FIFO is too full to accept this many samples, the method will return
  27943. false - then you could either wait until the background thread has had time to
  27944. consume some of the buffered data and try again, or you can give up
  27945. and lost this block.
  27946. The data must be an array containing the same number of channels as the
  27947. AudioFormatWriter object is using. None of these channels can be null.
  27948. */
  27949. bool write (const float** data, int numSamples);
  27950. /** Allows you to specify a thumbnail that this writer should update with the
  27951. incoming data.
  27952. The thumbnail will be cleared and will the writer will begin adding data to
  27953. it as it arrives. Pass a null pointer to stop the writer updating any thumbnails.
  27954. */
  27955. void setThumbnailToUpdate (AudioThumbnail* thumbnailToUpdate);
  27956. /** @internal */
  27957. class Buffer; // (only public for VC6 compatibility)
  27958. private:
  27959. friend class ScopedPointer<Buffer>;
  27960. ScopedPointer<Buffer> buffer;
  27961. };
  27962. protected:
  27963. /** The sample rate of the stream. */
  27964. double sampleRate;
  27965. /** The number of channels being written to the stream. */
  27966. unsigned int numChannels;
  27967. /** The bit depth of the file. */
  27968. unsigned int bitsPerSample;
  27969. /** True if it's a floating-point format, false if it's fixed-point. */
  27970. bool usesFloatingPointData;
  27971. /** The output stream for Use by subclasses. */
  27972. OutputStream* output;
  27973. /** Used by AudioFormatWriter subclasses to copy data to different formats. */
  27974. template <class DestSampleType, class SourceSampleType, class DestEndianness>
  27975. struct WriteHelper
  27976. {
  27977. typedef AudioData::Pointer <DestSampleType, DestEndianness, AudioData::Interleaved, AudioData::NonConst> DestType;
  27978. typedef AudioData::Pointer <SourceSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  27979. static void write (void* destData, int numDestChannels, const int** source,
  27980. int numSamples, const int sourceOffset = 0) noexcept
  27981. {
  27982. for (int i = 0; i < numDestChannels; ++i)
  27983. {
  27984. const DestType dest (addBytesToPointer (destData, i * DestType::getBytesPerSample()), numDestChannels);
  27985. if (*source != nullptr)
  27986. {
  27987. dest.convertSamples (SourceType (*source + sourceOffset), numSamples);
  27988. ++source;
  27989. }
  27990. else
  27991. {
  27992. dest.clearSamples (numSamples);
  27993. }
  27994. }
  27995. }
  27996. };
  27997. private:
  27998. String formatName;
  27999. friend class ThreadedWriter;
  28000. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatWriter);
  28001. };
  28002. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28003. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  28004. /**
  28005. Subclasses of AudioFormat are used to read and write different audio
  28006. file formats.
  28007. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  28008. */
  28009. class JUCE_API AudioFormat
  28010. {
  28011. public:
  28012. /** Destructor. */
  28013. virtual ~AudioFormat();
  28014. /** Returns the name of this format.
  28015. e.g. "WAV file" or "AIFF file"
  28016. */
  28017. const String& getFormatName() const;
  28018. /** Returns all the file extensions that might apply to a file of this format.
  28019. The first item will be the one that's preferred when creating a new file.
  28020. So for a wav file this might just return ".wav"; for an AIFF file it might
  28021. return two items, ".aif" and ".aiff"
  28022. */
  28023. const StringArray& getFileExtensions() const;
  28024. /** Returns true if this the given file can be read by this format.
  28025. Subclasses shouldn't do too much work here, just check the extension or
  28026. file type. The base class implementation just checks the file's extension
  28027. against one of the ones that was registered in the constructor.
  28028. */
  28029. virtual bool canHandleFile (const File& fileToTest);
  28030. /** Returns a set of sample rates that the format can read and write. */
  28031. virtual const Array <int> getPossibleSampleRates() = 0;
  28032. /** Returns a set of bit depths that the format can read and write. */
  28033. virtual const Array <int> getPossibleBitDepths() = 0;
  28034. /** Returns true if the format can do 2-channel audio. */
  28035. virtual bool canDoStereo() = 0;
  28036. /** Returns true if the format can do 1-channel audio. */
  28037. virtual bool canDoMono() = 0;
  28038. /** Returns true if the format uses compressed data. */
  28039. virtual bool isCompressed();
  28040. /** Returns a list of different qualities that can be used when writing.
  28041. Non-compressed formats will just return an empty array, but for something
  28042. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  28043. When calling createWriterFor(), an index from this array is passed in to
  28044. tell the format which option is required.
  28045. */
  28046. virtual const StringArray getQualityOptions();
  28047. /** Tries to create an object that can read from a stream containing audio
  28048. data in this format.
  28049. The reader object that is returned can be used to read from the stream, and
  28050. should then be deleted by the caller.
  28051. @param sourceStream the stream to read from - the AudioFormatReader object
  28052. that is returned will delete this stream when it no longer
  28053. needs it.
  28054. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  28055. should delete the stream object that was passed-in. (If a valid
  28056. reader is returned, it will always be in charge of deleting the
  28057. stream, so this parameter is ignored)
  28058. @see AudioFormatReader
  28059. */
  28060. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28061. bool deleteStreamIfOpeningFails) = 0;
  28062. /** Tries to create an object that can write to a stream with this audio format.
  28063. The writer object that is returned can be used to write to the stream, and
  28064. should then be deleted by the caller.
  28065. If the stream can't be created for some reason (e.g. the parameters passed in
  28066. here aren't suitable), this will return 0.
  28067. @param streamToWriteTo the stream that the data will go to - this will be
  28068. deleted by the AudioFormatWriter object when it's no longer
  28069. needed. If no AudioFormatWriter can be created by this method,
  28070. the stream will NOT be deleted, so that the caller can re-use it
  28071. to try to open a different format, etc
  28072. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  28073. returned by getPossibleSampleRates()
  28074. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  28075. the choice will depend on the results of canDoMono() and
  28076. canDoStereo()
  28077. @param bitsPerSample the bits per sample to use - this must be one of the values
  28078. returned by getPossibleBitDepths()
  28079. @param metadataValues a set of metadata values that the writer should try to write
  28080. to the stream. Exactly what these are depends on the format,
  28081. and the subclass doesn't actually have to do anything with
  28082. them if it doesn't want to. Have a look at the specific format
  28083. implementation classes to see possible values that can be
  28084. used
  28085. @param qualityOptionIndex the index of one of compression qualities returned by the
  28086. getQualityOptions() method. If there aren't any quality options
  28087. for this format, just pass 0 in this parameter, as it'll be
  28088. ignored
  28089. @see AudioFormatWriter
  28090. */
  28091. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28092. double sampleRateToUse,
  28093. unsigned int numberOfChannels,
  28094. int bitsPerSample,
  28095. const StringPairArray& metadataValues,
  28096. int qualityOptionIndex) = 0;
  28097. protected:
  28098. /** Creates an AudioFormat object.
  28099. @param formatName this sets the value that will be returned by getFormatName()
  28100. @param fileExtensions a zero-terminated list of file extensions - this is what will
  28101. be returned by getFileExtension()
  28102. */
  28103. AudioFormat (const String& formatName,
  28104. const StringArray& fileExtensions);
  28105. private:
  28106. String formatName;
  28107. StringArray fileExtensions;
  28108. };
  28109. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  28110. /*** End of inlined file: juce_AudioFormat.h ***/
  28111. /**
  28112. Reads and Writes AIFF format audio files.
  28113. @see AudioFormat
  28114. */
  28115. class JUCE_API AiffAudioFormat : public AudioFormat
  28116. {
  28117. public:
  28118. /** Creates an format object. */
  28119. AiffAudioFormat();
  28120. /** Destructor. */
  28121. ~AiffAudioFormat();
  28122. const Array <int> getPossibleSampleRates();
  28123. const Array <int> getPossibleBitDepths();
  28124. bool canDoStereo();
  28125. bool canDoMono();
  28126. #if JUCE_MAC
  28127. bool canHandleFile (const File& fileToTest);
  28128. #endif
  28129. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28130. bool deleteStreamIfOpeningFails);
  28131. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28132. double sampleRateToUse,
  28133. unsigned int numberOfChannels,
  28134. int bitsPerSample,
  28135. const StringPairArray& metadataValues,
  28136. int qualityOptionIndex);
  28137. private:
  28138. JUCE_LEAK_DETECTOR (AiffAudioFormat);
  28139. };
  28140. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  28141. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  28142. #endif
  28143. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28144. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  28145. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28146. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28147. #if JUCE_USE_CDBURNER || DOXYGEN
  28148. /**
  28149. */
  28150. class AudioCDBurner : public ChangeBroadcaster
  28151. {
  28152. public:
  28153. /** Returns a list of available optical drives.
  28154. Use openDevice() to open one of the items from this list.
  28155. */
  28156. static const StringArray findAvailableDevices();
  28157. /** Tries to open one of the optical drives.
  28158. The deviceIndex is an index into the array returned by findAvailableDevices().
  28159. */
  28160. static AudioCDBurner* openDevice (const int deviceIndex);
  28161. /** Destructor. */
  28162. ~AudioCDBurner();
  28163. enum DiskState
  28164. {
  28165. unknown, /**< An error condition, if the device isn't responding. */
  28166. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  28167. may seem to be permanently open. */
  28168. noDisc, /**< The drive has no disk in it. */
  28169. writableDiskPresent, /**< The drive contains a writeable disk. */
  28170. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  28171. };
  28172. /** Returns the current status of the device.
  28173. To get informed when the drive's status changes, attach a ChangeListener to
  28174. the AudioCDBurner.
  28175. */
  28176. DiskState getDiskState() const;
  28177. /** Returns true if there's a writable disk in the drive. */
  28178. bool isDiskPresent() const;
  28179. /** Sends an eject signal to the drive.
  28180. The eject will happen asynchronously, so you can use getDiskState() and
  28181. waitUntilStateChange() to monitor its progress.
  28182. */
  28183. bool openTray();
  28184. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  28185. @returns the device's new state
  28186. */
  28187. DiskState waitUntilStateChange (int timeOutMilliseconds);
  28188. /** Returns the set of possible write speeds that the device can handle.
  28189. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  28190. Note that if there's no media present in the drive, this value may be unavailable!
  28191. @see setWriteSpeed, getWriteSpeed
  28192. */
  28193. const Array<int> getAvailableWriteSpeeds() const;
  28194. /** Tries to enable or disable buffer underrun safety on devices that support it.
  28195. @returns true if it's now enabled. If the device doesn't support it, this
  28196. will always return false.
  28197. */
  28198. bool setBufferUnderrunProtection (bool shouldBeEnabled);
  28199. /** Returns the number of free blocks on the disk.
  28200. There are 75 blocks per second, at 44100Hz.
  28201. */
  28202. int getNumAvailableAudioBlocks() const;
  28203. /** Adds a track to be written.
  28204. The source passed-in here will be kept by this object, and it will
  28205. be used and deleted at some point in the future, either during the
  28206. burn() method or when this AudioCDBurner object is deleted. Your caller
  28207. method shouldn't keep a reference to it or use it again after passing
  28208. it in here.
  28209. */
  28210. bool addAudioTrack (AudioSource* source, int numSamples);
  28211. /** Receives progress callbacks during a cd-burn operation.
  28212. @see AudioCDBurner::burn()
  28213. */
  28214. class BurnProgressListener
  28215. {
  28216. public:
  28217. BurnProgressListener() noexcept {}
  28218. virtual ~BurnProgressListener() {}
  28219. /** Called at intervals to report on the progress of the AudioCDBurner.
  28220. To cancel the burn, return true from this method.
  28221. */
  28222. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  28223. };
  28224. /** Runs the burn process.
  28225. This method will block until the operation is complete.
  28226. @param listener the object to receive callbacks about progress
  28227. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  28228. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  28229. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  28230. 0 or less to mean the fastest speed.
  28231. */
  28232. const String burn (BurnProgressListener* listener,
  28233. bool ejectDiscAfterwards,
  28234. bool performFakeBurnForTesting,
  28235. int writeSpeed);
  28236. /** If a burn operation is currently in progress, this tells it to stop
  28237. as soon as possible.
  28238. It's also possible to stop the burn process by returning true from
  28239. BurnProgressListener::audioCDBurnProgress()
  28240. */
  28241. void abortBurn();
  28242. private:
  28243. AudioCDBurner (const int deviceIndex);
  28244. class Pimpl;
  28245. friend class ScopedPointer<Pimpl>;
  28246. ScopedPointer<Pimpl> pimpl;
  28247. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDBurner);
  28248. };
  28249. #endif
  28250. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28251. /*** End of inlined file: juce_AudioCDBurner.h ***/
  28252. #endif
  28253. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28254. /*** Start of inlined file: juce_AudioCDReader.h ***/
  28255. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28256. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  28257. #if JUCE_USE_CDREADER || DOXYGEN
  28258. #if JUCE_MAC
  28259. #endif
  28260. /**
  28261. A type of AudioFormatReader that reads from an audio CD.
  28262. One of these can be used to read a CD as if it's one big audio stream. Use the
  28263. getPositionOfTrackStart() method to find where the individual tracks are
  28264. within the stream.
  28265. @see AudioFormatReader
  28266. */
  28267. class JUCE_API AudioCDReader : public AudioFormatReader
  28268. {
  28269. public:
  28270. /** Returns a list of names of Audio CDs currently available for reading.
  28271. If there's a CD drive but no CD in it, this might return an empty list, or
  28272. possibly a device that can be opened but which has no tracks, depending
  28273. on the platform.
  28274. @see createReaderForCD
  28275. */
  28276. static const StringArray getAvailableCDNames();
  28277. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  28278. @param index the index of one of the available CDs - use getAvailableCDNames()
  28279. to find out how many there are.
  28280. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  28281. caller will be responsible for deleting the object returned.
  28282. */
  28283. static AudioCDReader* createReaderForCD (const int index);
  28284. /** Destructor. */
  28285. ~AudioCDReader();
  28286. /** Implementation of the AudioFormatReader method. */
  28287. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28288. int64 startSampleInFile, int numSamples);
  28289. /** Checks whether the CD has been removed from the drive.
  28290. */
  28291. bool isCDStillPresent() const;
  28292. /** Returns the total number of tracks (audio + data).
  28293. */
  28294. int getNumTracks() const;
  28295. /** Finds the sample offset of the start of a track.
  28296. @param trackNum the track number, where trackNum = 0 is the first track
  28297. and trackNum = getNumTracks() means the end of the CD.
  28298. */
  28299. int getPositionOfTrackStart (int trackNum) const;
  28300. /** Returns true if a given track is an audio track.
  28301. @param trackNum the track number, where 0 is the first track.
  28302. */
  28303. bool isTrackAudio (int trackNum) const;
  28304. /** Returns an array of sample offsets for the start of each track, followed by
  28305. the sample position of the end of the CD.
  28306. */
  28307. const Array<int>& getTrackOffsets() const;
  28308. /** Refreshes the object's table of contents.
  28309. If the disc has been ejected and a different one put in since this
  28310. object was created, this will cause it to update its idea of how many tracks
  28311. there are, etc.
  28312. */
  28313. void refreshTrackLengths();
  28314. /** Enables scanning for indexes within tracks.
  28315. @see getLastIndex
  28316. */
  28317. void enableIndexScanning (bool enabled);
  28318. /** Returns the index number found during the last read() call.
  28319. Index scanning is turned off by default - turn it on with enableIndexScanning().
  28320. Then when the read() method is called, if it comes across an index within that
  28321. block, the index number is stored and returned by this method.
  28322. Some devices might not support indexes, of course.
  28323. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  28324. @see enableIndexScanning
  28325. */
  28326. int getLastIndex() const;
  28327. /** Scans a track to find the position of any indexes within it.
  28328. @param trackNumber the track to look in, where 0 is the first track on the disc
  28329. @returns an array of sample positions of any index points found (not including
  28330. the index that marks the start of the track)
  28331. */
  28332. const Array <int> findIndexesInTrack (const int trackNumber);
  28333. /** Returns the CDDB id number for the CD.
  28334. It's not a great way of identifying a disc, but it's traditional.
  28335. */
  28336. int getCDDBId();
  28337. /** Tries to eject the disk.
  28338. Of course this might not be possible, if some other process is using it.
  28339. */
  28340. void ejectDisk();
  28341. enum
  28342. {
  28343. framesPerSecond = 75,
  28344. samplesPerFrame = 44100 / framesPerSecond
  28345. };
  28346. private:
  28347. Array<int> trackStartSamples;
  28348. #if JUCE_MAC
  28349. File volumeDir;
  28350. Array<File> tracks;
  28351. int currentReaderTrack;
  28352. ScopedPointer <AudioFormatReader> reader;
  28353. AudioCDReader (const File& volume);
  28354. #elif JUCE_WINDOWS
  28355. bool audioTracks [100];
  28356. void* handle;
  28357. bool indexingEnabled;
  28358. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  28359. MemoryBlock buffer;
  28360. AudioCDReader (void* handle);
  28361. int getIndexAt (int samplePos);
  28362. #elif JUCE_LINUX
  28363. AudioCDReader();
  28364. #endif
  28365. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDReader);
  28366. };
  28367. #endif
  28368. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  28369. /*** End of inlined file: juce_AudioCDReader.h ***/
  28370. #endif
  28371. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  28372. #endif
  28373. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28374. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  28375. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28376. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28377. /**
  28378. A class for keeping a list of available audio formats, and for deciding which
  28379. one to use to open a given file.
  28380. You can either use this class as a singleton object, or create instances of it
  28381. yourself. Once created, use its registerFormat() method to tell it which
  28382. formats it should use.
  28383. @see AudioFormat
  28384. */
  28385. class JUCE_API AudioFormatManager
  28386. {
  28387. public:
  28388. /** Creates an empty format manager.
  28389. Before it'll be any use, you'll need to call registerFormat() with all the
  28390. formats you want it to be able to recognise.
  28391. */
  28392. AudioFormatManager();
  28393. /** Destructor. */
  28394. ~AudioFormatManager();
  28395. /** Adds a format to the manager's list of available file types.
  28396. The object passed-in will be deleted by this object, so don't keep a pointer
  28397. to it!
  28398. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  28399. return this one when called.
  28400. */
  28401. void registerFormat (AudioFormat* newFormat,
  28402. bool makeThisTheDefaultFormat);
  28403. /** Handy method to make it easy to register the formats that come with Juce.
  28404. Currently, this will add WAV and AIFF to the list.
  28405. */
  28406. void registerBasicFormats();
  28407. /** Clears the list of known formats. */
  28408. void clearFormats();
  28409. /** Returns the number of currently registered file formats. */
  28410. int getNumKnownFormats() const;
  28411. /** Returns one of the registered file formats. */
  28412. AudioFormat* getKnownFormat (int index) const;
  28413. /** Looks for which of the known formats is listed as being for a given file
  28414. extension.
  28415. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  28416. */
  28417. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  28418. /** Returns the format which has been set as the default one.
  28419. You can set a format as being the default when it is registered. It's useful
  28420. when you want to write to a file, because the best format may change between
  28421. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  28422. If none has been set as the default, this method will just return the first
  28423. one in the list.
  28424. */
  28425. AudioFormat* getDefaultFormat() const;
  28426. /** Returns a set of wildcards for file-matching that contains the extensions for
  28427. all known formats.
  28428. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  28429. */
  28430. const String getWildcardForAllFormats() const;
  28431. /** Searches through the known formats to try to create a suitable reader for
  28432. this file.
  28433. If none of the registered formats can open the file, it'll return 0. If it
  28434. returns a reader, it's the caller's responsibility to delete the reader.
  28435. */
  28436. AudioFormatReader* createReaderFor (const File& audioFile);
  28437. /** Searches through the known formats to try to create a suitable reader for
  28438. this stream.
  28439. The stream object that is passed-in will be deleted by this method or by the
  28440. reader that is returned, so the caller should not keep any references to it.
  28441. The stream that is passed-in must be capable of being repositioned so
  28442. that all the formats can have a go at opening it.
  28443. If none of the registered formats can open the stream, it'll return 0. If it
  28444. returns a reader, it's the caller's responsibility to delete the reader.
  28445. */
  28446. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  28447. private:
  28448. OwnedArray<AudioFormat> knownFormats;
  28449. int defaultFormatIndex;
  28450. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatManager);
  28451. };
  28452. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28453. /*** End of inlined file: juce_AudioFormatManager.h ***/
  28454. #endif
  28455. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  28456. #endif
  28457. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28458. #endif
  28459. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28460. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  28461. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28462. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28463. /**
  28464. This class is used to wrap an AudioFormatReader and only read from a
  28465. subsection of the file.
  28466. So if you have a reader which can read a 1000 sample file, you could wrap it
  28467. in one of these to only access, e.g. samples 100 to 200, and any samples
  28468. outside that will come back as 0. Accessing sample 0 from this reader will
  28469. actually read the first sample from the other's subsection, which might
  28470. be at a non-zero position.
  28471. @see AudioFormatReader
  28472. */
  28473. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  28474. {
  28475. public:
  28476. /** Creates a AudioSubsectionReader for a given data source.
  28477. @param sourceReader the source reader from which we'll be taking data
  28478. @param subsectionStartSample the sample within the source reader which will be
  28479. mapped onto sample 0 for this reader.
  28480. @param subsectionLength the number of samples from the source that will
  28481. make up the subsection. If this reader is asked for
  28482. any samples beyond this region, it will return zero.
  28483. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  28484. this object is deleted.
  28485. */
  28486. AudioSubsectionReader (AudioFormatReader* sourceReader,
  28487. int64 subsectionStartSample,
  28488. int64 subsectionLength,
  28489. bool deleteSourceWhenDeleted);
  28490. /** Destructor. */
  28491. ~AudioSubsectionReader();
  28492. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28493. int64 startSampleInFile, int numSamples);
  28494. void readMaxLevels (int64 startSample,
  28495. int64 numSamples,
  28496. float& lowestLeft,
  28497. float& highestLeft,
  28498. float& lowestRight,
  28499. float& highestRight);
  28500. private:
  28501. AudioFormatReader* const source;
  28502. int64 startSample, length;
  28503. const bool deleteSourceWhenDeleted;
  28504. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSubsectionReader);
  28505. };
  28506. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28507. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  28508. #endif
  28509. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28510. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  28511. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28512. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28513. class AudioThumbnailCache;
  28514. /**
  28515. Makes it easy to quickly draw scaled views of the waveform shape of an
  28516. audio file.
  28517. To use this class, just create an AudioThumbNail class for the file you want
  28518. to draw, call setSource to tell it which file or resource to use, then call
  28519. drawChannel() to draw it.
  28520. The class will asynchronously scan the wavefile to create its scaled-down view,
  28521. so you should make your UI repaint itself as this data comes in. To do this, the
  28522. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  28523. listeners should repaint themselves.
  28524. The thumbnail stores an internal low-res version of the wave data, and this can
  28525. be loaded and saved to avoid having to scan the file again.
  28526. @see AudioThumbnailCache
  28527. */
  28528. class JUCE_API AudioThumbnail : public ChangeBroadcaster
  28529. {
  28530. public:
  28531. /** Creates an audio thumbnail.
  28532. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  28533. of the audio data, this is the scale at which it should be done. (This
  28534. number is the number of original samples that will be averaged for each
  28535. low-res sample)
  28536. @param formatManagerToUse the audio format manager that is used to open the file
  28537. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  28538. thread and storage that is used to by the thumbnail, and the cache
  28539. object can be shared between multiple thumbnails
  28540. */
  28541. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  28542. AudioFormatManager& formatManagerToUse,
  28543. AudioThumbnailCache& cacheToUse);
  28544. /** Destructor. */
  28545. ~AudioThumbnail();
  28546. /** Clears and resets the thumbnail. */
  28547. void clear();
  28548. /** Specifies the file or stream that contains the audio file.
  28549. For a file, just call
  28550. @code
  28551. setSource (new FileInputSource (file))
  28552. @endcode
  28553. You can pass a zero in here to clear the thumbnail.
  28554. The source that is passed in will be deleted by this object when it is no longer needed.
  28555. @returns true if the source could be opened as a valid audio file, false if this failed for
  28556. some reason.
  28557. */
  28558. bool setSource (InputSource* newSource);
  28559. /** Gives the thumbnail an AudioFormatReader to use directly.
  28560. This will start parsing the audio in a background thread (unless the hash code
  28561. can be looked-up successfully in the thumbnail cache). Note that the reader
  28562. object will be held by the thumbnail and deleted later when no longer needed.
  28563. The thumbnail will actually keep hold of this reader until you clear the thumbnail
  28564. or change the input source, so the file will be held open for all this time. If
  28565. you don't want the thumbnail to keep a file handle open continuously, you
  28566. should use the setSource() method instead, which will only open the file when
  28567. it needs to.
  28568. */
  28569. void setReader (AudioFormatReader* newReader, int64 hashCode);
  28570. /** Resets the thumbnail, ready for adding data with the specified format.
  28571. If you're going to generate a thumbnail yourself, call this before using addBlock()
  28572. to add the data.
  28573. */
  28574. void reset (int numChannels, double sampleRate, int64 totalSamplesInSource = 0);
  28575. /** Adds a block of level data to the thumbnail.
  28576. Call reset() before using this, to tell the thumbnail about the data format.
  28577. */
  28578. void addBlock (int64 sampleNumberInSource, const AudioSampleBuffer& newData,
  28579. int startOffsetInBuffer, int numSamples);
  28580. /** Reloads the low res thumbnail data from an input stream.
  28581. This is not an audio file stream! It takes a stream of thumbnail data that would
  28582. previously have been created by the saveTo() method.
  28583. @see saveTo
  28584. */
  28585. void loadFrom (InputStream& input);
  28586. /** Saves the low res thumbnail data to an output stream.
  28587. The data that is written can later be reloaded using loadFrom().
  28588. @see loadFrom
  28589. */
  28590. void saveTo (OutputStream& output) const;
  28591. /** Returns the number of channels in the file. */
  28592. int getNumChannels() const noexcept;
  28593. /** Returns the length of the audio file, in seconds. */
  28594. double getTotalLength() const noexcept;
  28595. /** Draws the waveform for a channel.
  28596. The waveform will be drawn within the specified rectangle, where startTime
  28597. and endTime specify the times within the audio file that should be positioned
  28598. at the left and right edges of the rectangle.
  28599. The waveform will be scaled vertically so that a full-volume sample will fill
  28600. the rectangle vertically, but you can also specify an extra vertical scale factor
  28601. with the verticalZoomFactor parameter.
  28602. */
  28603. void drawChannel (Graphics& g,
  28604. const Rectangle<int>& area,
  28605. double startTimeSeconds,
  28606. double endTimeSeconds,
  28607. int channelNum,
  28608. float verticalZoomFactor);
  28609. /** Draws the waveforms for all channels in the thumbnail.
  28610. This will call drawChannel() to render each of the thumbnail's channels, stacked
  28611. above each other within the specified area.
  28612. @see drawChannel
  28613. */
  28614. void drawChannels (Graphics& g,
  28615. const Rectangle<int>& area,
  28616. double startTimeSeconds,
  28617. double endTimeSeconds,
  28618. float verticalZoomFactor);
  28619. /** Returns true if the low res preview is fully generated. */
  28620. bool isFullyLoaded() const noexcept;
  28621. /** Returns the number of samples that have been set in the thumbnail. */
  28622. int64 getNumSamplesFinished() const noexcept;
  28623. /** Returns the highest level in the thumbnail.
  28624. Note that because the thumb only stores low-resolution data, this isn't
  28625. an accurate representation of the highest value, it's only a rough approximation.
  28626. */
  28627. float getApproximatePeak() const;
  28628. /** Reads the approximate min and max levels from a section of the thumbnail.
  28629. The lowest and highest samples are returned in minValue and maxValue, but obviously
  28630. because the thumb only stores low-resolution data, these numbers will only be a rough
  28631. approximation of the true values.
  28632. */
  28633. void getApproximateMinMax (double startTime, double endTime, int channelIndex,
  28634. float& minValue, float& maxValue) const noexcept;
  28635. /** Returns the hash code that was set by setSource() or setReader(). */
  28636. int64 getHashCode() const;
  28637. #ifndef DOXYGEN
  28638. class LevelDataSource; // (this is only public to avoid a VC6 bug)
  28639. #endif
  28640. private:
  28641. AudioFormatManager& formatManagerToUse;
  28642. AudioThumbnailCache& cache;
  28643. struct MinMaxValue;
  28644. class ThumbData;
  28645. class CachedWindow;
  28646. friend class LevelDataSource;
  28647. friend class ScopedPointer<LevelDataSource>;
  28648. friend class ThumbData;
  28649. friend class OwnedArray<ThumbData>;
  28650. friend class CachedWindow;
  28651. friend class ScopedPointer<CachedWindow>;
  28652. ScopedPointer<LevelDataSource> source;
  28653. ScopedPointer<CachedWindow> window;
  28654. OwnedArray<ThumbData> channels;
  28655. int32 samplesPerThumbSample;
  28656. int64 totalSamples, numSamplesFinished;
  28657. int32 numChannels;
  28658. double sampleRate;
  28659. CriticalSection lock;
  28660. bool setDataSource (LevelDataSource* newSource);
  28661. void setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues);
  28662. void createChannels (int length);
  28663. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnail);
  28664. };
  28665. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28666. /*** End of inlined file: juce_AudioThumbnail.h ***/
  28667. #endif
  28668. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28669. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  28670. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28671. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28672. struct ThumbnailCacheEntry;
  28673. /**
  28674. An instance of this class is used to manage multiple AudioThumbnail objects.
  28675. The cache runs a single background thread that is shared by all the thumbnails
  28676. that need it, and it maintains a set of low-res previews in memory, to avoid
  28677. having to re-scan audio files too often.
  28678. @see AudioThumbnail
  28679. */
  28680. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  28681. {
  28682. public:
  28683. /** Creates a cache object.
  28684. The maxNumThumbsToStore parameter lets you specify how many previews should
  28685. be kept in memory at once.
  28686. */
  28687. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  28688. /** Destructor. */
  28689. ~AudioThumbnailCache();
  28690. /** Clears out any stored thumbnails.
  28691. */
  28692. void clear();
  28693. /** Reloads the specified thumb if this cache contains the appropriate stored
  28694. data.
  28695. This is called automatically by the AudioThumbnail class, so you shouldn't
  28696. normally need to call it directly.
  28697. */
  28698. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  28699. /** Stores the cachable data from the specified thumb in this cache.
  28700. This is called automatically by the AudioThumbnail class, so you shouldn't
  28701. normally need to call it directly.
  28702. */
  28703. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  28704. private:
  28705. OwnedArray <ThumbnailCacheEntry> thumbs;
  28706. int maxNumThumbsToStore;
  28707. ThumbnailCacheEntry* findThumbFor (int64 hash) const;
  28708. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnailCache);
  28709. };
  28710. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28711. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  28712. #endif
  28713. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28714. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  28715. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28716. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28717. #if JUCE_USE_FLAC || defined (DOXYGEN)
  28718. /**
  28719. Reads and writes the lossless-compression FLAC audio format.
  28720. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  28721. and make sure your include search path and library search path are set up to find
  28722. the FLAC header files and static libraries.
  28723. @see AudioFormat
  28724. */
  28725. class JUCE_API FlacAudioFormat : public AudioFormat
  28726. {
  28727. public:
  28728. FlacAudioFormat();
  28729. ~FlacAudioFormat();
  28730. const Array <int> getPossibleSampleRates();
  28731. const Array <int> getPossibleBitDepths();
  28732. bool canDoStereo();
  28733. bool canDoMono();
  28734. bool isCompressed();
  28735. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28736. bool deleteStreamIfOpeningFails);
  28737. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28738. double sampleRateToUse,
  28739. unsigned int numberOfChannels,
  28740. int bitsPerSample,
  28741. const StringPairArray& metadataValues,
  28742. int qualityOptionIndex);
  28743. private:
  28744. JUCE_LEAK_DETECTOR (FlacAudioFormat);
  28745. };
  28746. #endif
  28747. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28748. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  28749. #endif
  28750. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28751. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  28752. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28753. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28754. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  28755. /**
  28756. Reads and writes the Ogg-Vorbis audio format.
  28757. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  28758. and make sure your include search path and library search path are set up to find
  28759. the Vorbis and Ogg header files and static libraries.
  28760. @see AudioFormat,
  28761. */
  28762. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  28763. {
  28764. public:
  28765. OggVorbisAudioFormat();
  28766. ~OggVorbisAudioFormat();
  28767. const Array <int> getPossibleSampleRates();
  28768. const Array <int> getPossibleBitDepths();
  28769. bool canDoStereo();
  28770. bool canDoMono();
  28771. bool isCompressed();
  28772. const StringArray getQualityOptions();
  28773. /** Tries to estimate the quality level of an ogg file based on its size.
  28774. If it can't read the file for some reason, this will just return 1 (medium quality),
  28775. otherwise it will return the approximate quality setting that would have been used
  28776. to create the file.
  28777. @see getQualityOptions
  28778. */
  28779. int estimateOggFileQuality (const File& source);
  28780. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28781. bool deleteStreamIfOpeningFails);
  28782. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28783. double sampleRateToUse,
  28784. unsigned int numberOfChannels,
  28785. int bitsPerSample,
  28786. const StringPairArray& metadataValues,
  28787. int qualityOptionIndex);
  28788. private:
  28789. JUCE_LEAK_DETECTOR (OggVorbisAudioFormat);
  28790. };
  28791. #endif
  28792. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28793. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  28794. #endif
  28795. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28796. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  28797. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28798. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28799. #if JUCE_QUICKTIME
  28800. /**
  28801. Uses QuickTime to read the audio track a movie or media file.
  28802. As well as QuickTime movies, this should also manage to open other audio
  28803. files that quicktime can understand, like mp3, m4a, etc.
  28804. @see AudioFormat
  28805. */
  28806. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  28807. {
  28808. public:
  28809. /** Creates a format object. */
  28810. QuickTimeAudioFormat();
  28811. /** Destructor. */
  28812. ~QuickTimeAudioFormat();
  28813. const Array <int> getPossibleSampleRates();
  28814. const Array <int> getPossibleBitDepths();
  28815. bool canDoStereo();
  28816. bool canDoMono();
  28817. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28818. bool deleteStreamIfOpeningFails);
  28819. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28820. double sampleRateToUse,
  28821. unsigned int numberOfChannels,
  28822. int bitsPerSample,
  28823. const StringPairArray& metadataValues,
  28824. int qualityOptionIndex);
  28825. private:
  28826. JUCE_LEAK_DETECTOR (QuickTimeAudioFormat);
  28827. };
  28828. #endif
  28829. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28830. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  28831. #endif
  28832. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28833. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  28834. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28835. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28836. /**
  28837. Reads and Writes WAV format audio files.
  28838. @see AudioFormat
  28839. */
  28840. class JUCE_API WavAudioFormat : public AudioFormat
  28841. {
  28842. public:
  28843. /** Creates a format object. */
  28844. WavAudioFormat();
  28845. /** Destructor. */
  28846. ~WavAudioFormat();
  28847. /** Metadata property name used by wav readers and writers for adding
  28848. a BWAV chunk to the file.
  28849. @see AudioFormatReader::metadataValues, createWriterFor
  28850. */
  28851. static const char* const bwavDescription;
  28852. /** Metadata property name used by wav readers and writers for adding
  28853. a BWAV chunk to the file.
  28854. @see AudioFormatReader::metadataValues, createWriterFor
  28855. */
  28856. static const char* const bwavOriginator;
  28857. /** Metadata property name used by wav readers and writers for adding
  28858. a BWAV chunk to the file.
  28859. @see AudioFormatReader::metadataValues, createWriterFor
  28860. */
  28861. static const char* const bwavOriginatorRef;
  28862. /** Metadata property name used by wav readers and writers for adding
  28863. a BWAV chunk to the file.
  28864. Date format is: yyyy-mm-dd
  28865. @see AudioFormatReader::metadataValues, createWriterFor
  28866. */
  28867. static const char* const bwavOriginationDate;
  28868. /** Metadata property name used by wav readers and writers for adding
  28869. a BWAV chunk to the file.
  28870. Time format is: hh-mm-ss
  28871. @see AudioFormatReader::metadataValues, createWriterFor
  28872. */
  28873. static const char* const bwavOriginationTime;
  28874. /** Metadata property name used by wav readers and writers for adding
  28875. a BWAV chunk to the file.
  28876. This is the number of samples from the start of an edit that the
  28877. file is supposed to begin at. Seems like an obvious mistake to
  28878. only allow a file to occur in an edit once, but that's the way
  28879. it is..
  28880. @see AudioFormatReader::metadataValues, createWriterFor
  28881. */
  28882. static const char* const bwavTimeReference;
  28883. /** Metadata property name used by wav readers and writers for adding
  28884. a BWAV chunk to the file.
  28885. This is a
  28886. @see AudioFormatReader::metadataValues, createWriterFor
  28887. */
  28888. static const char* const bwavCodingHistory;
  28889. /** Utility function to fill out the appropriate metadata for a BWAV file.
  28890. This just makes it easier than using the property names directly, and it
  28891. fills out the time and date in the right format.
  28892. */
  28893. static const StringPairArray createBWAVMetadata (const String& description,
  28894. const String& originator,
  28895. const String& originatorRef,
  28896. const Time& dateAndTime,
  28897. const int64 timeReferenceSamples,
  28898. const String& codingHistory);
  28899. const Array <int> getPossibleSampleRates();
  28900. const Array <int> getPossibleBitDepths();
  28901. bool canDoStereo();
  28902. bool canDoMono();
  28903. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28904. bool deleteStreamIfOpeningFails);
  28905. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28906. double sampleRateToUse,
  28907. unsigned int numberOfChannels,
  28908. int bitsPerSample,
  28909. const StringPairArray& metadataValues,
  28910. int qualityOptionIndex);
  28911. /** Utility function to replace the metadata in a wav file with a new set of values.
  28912. If possible, this cheats by overwriting just the metadata region of the file, rather
  28913. than by copying the whole file again.
  28914. */
  28915. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  28916. private:
  28917. JUCE_LEAK_DETECTOR (WavAudioFormat);
  28918. };
  28919. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28920. /*** End of inlined file: juce_WavAudioFormat.h ***/
  28921. #endif
  28922. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28923. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  28924. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28925. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28926. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  28927. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28928. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28929. /**
  28930. A type of AudioSource which can be repositioned.
  28931. The basic AudioSource just streams continuously with no idea of a current
  28932. time or length, so the PositionableAudioSource is used for a finite stream
  28933. that has a current read position.
  28934. @see AudioSource, AudioTransportSource
  28935. */
  28936. class JUCE_API PositionableAudioSource : public AudioSource
  28937. {
  28938. protected:
  28939. /** Creates the PositionableAudioSource. */
  28940. PositionableAudioSource() noexcept {}
  28941. public:
  28942. /** Destructor */
  28943. ~PositionableAudioSource() {}
  28944. /** Tells the stream to move to a new position.
  28945. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  28946. should return samples from this position.
  28947. Note that this may be called on a different thread to getNextAudioBlock(),
  28948. so the subclass should make sure it's synchronised.
  28949. */
  28950. virtual void setNextReadPosition (int64 newPosition) = 0;
  28951. /** Returns the position from which the next block will be returned.
  28952. @see setNextReadPosition
  28953. */
  28954. virtual int64 getNextReadPosition() const = 0;
  28955. /** Returns the total length of the stream (in samples). */
  28956. virtual int64 getTotalLength() const = 0;
  28957. /** Returns true if this source is actually playing in a loop. */
  28958. virtual bool isLooping() const = 0;
  28959. /** Tells the source whether you'd like it to play in a loop. */
  28960. virtual void setLooping (bool shouldLoop) { (void) shouldLoop; }
  28961. };
  28962. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28963. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  28964. /**
  28965. A type of AudioSource that will read from an AudioFormatReader.
  28966. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  28967. */
  28968. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  28969. {
  28970. public:
  28971. /** Creates an AudioFormatReaderSource for a given reader.
  28972. @param sourceReader the reader to use as the data source
  28973. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  28974. when this object is deleted; if false it will be
  28975. left up to the caller to manage its lifetime
  28976. */
  28977. AudioFormatReaderSource (AudioFormatReader* sourceReader,
  28978. bool deleteReaderWhenThisIsDeleted);
  28979. /** Destructor. */
  28980. ~AudioFormatReaderSource();
  28981. /** Toggles loop-mode.
  28982. If set to true, it will continuously loop the input source. If false,
  28983. it will just emit silence after the source has finished.
  28984. @see isLooping
  28985. */
  28986. void setLooping (bool shouldLoop);
  28987. /** Returns whether loop-mode is turned on or not. */
  28988. bool isLooping() const { return looping; }
  28989. /** Returns the reader that's being used. */
  28990. AudioFormatReader* getAudioFormatReader() const noexcept { return reader; }
  28991. /** Implementation of the AudioSource method. */
  28992. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28993. /** Implementation of the AudioSource method. */
  28994. void releaseResources();
  28995. /** Implementation of the AudioSource method. */
  28996. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28997. /** Implements the PositionableAudioSource method. */
  28998. void setNextReadPosition (int64 newPosition);
  28999. /** Implements the PositionableAudioSource method. */
  29000. int64 getNextReadPosition() const;
  29001. /** Implements the PositionableAudioSource method. */
  29002. int64 getTotalLength() const;
  29003. private:
  29004. AudioFormatReader* reader;
  29005. bool deleteReader;
  29006. int64 volatile nextPlayPos;
  29007. bool volatile looping;
  29008. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  29009. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReaderSource);
  29010. };
  29011. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  29012. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  29013. #endif
  29014. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  29015. #endif
  29016. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29017. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  29018. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29019. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29020. /*** Start of inlined file: juce_AudioIODevice.h ***/
  29021. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  29022. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  29023. class AudioIODevice;
  29024. /**
  29025. One of these is passed to an AudioIODevice object to stream the audio data
  29026. in and out.
  29027. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  29028. method on its own high-priority audio thread, when it needs to send or receive
  29029. the next block of data.
  29030. @see AudioIODevice, AudioDeviceManager
  29031. */
  29032. class JUCE_API AudioIODeviceCallback
  29033. {
  29034. public:
  29035. /** Destructor. */
  29036. virtual ~AudioIODeviceCallback() {}
  29037. /** Processes a block of incoming and outgoing audio data.
  29038. The subclass's implementation should use the incoming audio for whatever
  29039. purposes it needs to, and must fill all the output channels with the next
  29040. block of output data before returning.
  29041. The channel data is arranged with the same array indices as the channel name
  29042. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  29043. that aren't specified in AudioIODevice::open() will have a null pointer for their
  29044. associated channel, so remember to check for this.
  29045. @param inputChannelData a set of arrays containing the audio data for each
  29046. incoming channel - this data is valid until the function
  29047. returns. There will be one channel of data for each input
  29048. channel that was enabled when the audio device was opened
  29049. (see AudioIODevice::open())
  29050. @param numInputChannels the number of pointers to channel data in the
  29051. inputChannelData array.
  29052. @param outputChannelData a set of arrays which need to be filled with the data
  29053. that should be sent to each outgoing channel of the device.
  29054. There will be one channel of data for each output channel
  29055. that was enabled when the audio device was opened (see
  29056. AudioIODevice::open())
  29057. The initial contents of the array is undefined, so the
  29058. callback function must fill all the channels with zeros if
  29059. its output is silence. Failing to do this could cause quite
  29060. an unpleasant noise!
  29061. @param numOutputChannels the number of pointers to channel data in the
  29062. outputChannelData array.
  29063. @param numSamples the number of samples in each channel of the input and
  29064. output arrays. The number of samples will depend on the
  29065. audio device's buffer size and will usually remain constant,
  29066. although this isn't guaranteed, so make sure your code can
  29067. cope with reasonable changes in the buffer size from one
  29068. callback to the next.
  29069. */
  29070. virtual void audioDeviceIOCallback (const float** inputChannelData,
  29071. int numInputChannels,
  29072. float** outputChannelData,
  29073. int numOutputChannels,
  29074. int numSamples) = 0;
  29075. /** Called to indicate that the device is about to start calling back.
  29076. This will be called just before the audio callbacks begin, either when this
  29077. callback has just been added to an audio device, or after the device has been
  29078. restarted because of a sample-rate or block-size change.
  29079. You can use this opportunity to find out the sample rate and block size
  29080. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  29081. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  29082. @param device the audio IO device that will be used to drive the callback.
  29083. Note that if you're going to store this this pointer, it is
  29084. only valid until the next time that audioDeviceStopped is called.
  29085. */
  29086. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  29087. /** Called to indicate that the device has stopped.
  29088. */
  29089. virtual void audioDeviceStopped() = 0;
  29090. };
  29091. /**
  29092. Base class for an audio device with synchronised input and output channels.
  29093. Subclasses of this are used to implement different protocols such as DirectSound,
  29094. ASIO, CoreAudio, etc.
  29095. To create one of these, you'll need to use the AudioIODeviceType class - see the
  29096. documentation for that class for more info.
  29097. For an easier way of managing audio devices and their settings, have a look at the
  29098. AudioDeviceManager class.
  29099. @see AudioIODeviceType, AudioDeviceManager
  29100. */
  29101. class JUCE_API AudioIODevice
  29102. {
  29103. public:
  29104. /** Destructor. */
  29105. virtual ~AudioIODevice();
  29106. /** Returns the device's name, (as set in the constructor). */
  29107. const String& getName() const noexcept { return name; }
  29108. /** Returns the type of the device.
  29109. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  29110. */
  29111. const String& getTypeName() const noexcept { return typeName; }
  29112. /** Returns the names of all the available output channels on this device.
  29113. To find out which of these are currently in use, call getActiveOutputChannels().
  29114. */
  29115. virtual const StringArray getOutputChannelNames() = 0;
  29116. /** Returns the names of all the available input channels on this device.
  29117. To find out which of these are currently in use, call getActiveInputChannels().
  29118. */
  29119. virtual const StringArray getInputChannelNames() = 0;
  29120. /** Returns the number of sample-rates this device supports.
  29121. To find out which rates are available on this device, use this method to
  29122. find out how many there are, and getSampleRate() to get the rates.
  29123. @see getSampleRate
  29124. */
  29125. virtual int getNumSampleRates() = 0;
  29126. /** Returns one of the sample-rates this device supports.
  29127. To find out which rates are available on this device, use getNumSampleRates() to
  29128. find out how many there are, and getSampleRate() to get the individual rates.
  29129. The sample rate is set by the open() method.
  29130. (Note that for DirectSound some rates might not work, depending on combinations
  29131. of i/o channels that are being opened).
  29132. @see getNumSampleRates
  29133. */
  29134. virtual double getSampleRate (int index) = 0;
  29135. /** Returns the number of sizes of buffer that are available.
  29136. @see getBufferSizeSamples, getDefaultBufferSize
  29137. */
  29138. virtual int getNumBufferSizesAvailable() = 0;
  29139. /** Returns one of the possible buffer-sizes.
  29140. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  29141. @returns a number of samples
  29142. @see getNumBufferSizesAvailable, getDefaultBufferSize
  29143. */
  29144. virtual int getBufferSizeSamples (int index) = 0;
  29145. /** Returns the default buffer-size to use.
  29146. @returns a number of samples
  29147. @see getNumBufferSizesAvailable, getBufferSizeSamples
  29148. */
  29149. virtual int getDefaultBufferSize() = 0;
  29150. /** Tries to open the device ready to play.
  29151. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  29152. input channel should be enabled
  29153. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  29154. output channel should be enabled
  29155. @param sampleRate the sample rate to try to use - to find out which rates are
  29156. available, see getNumSampleRates() and getSampleRate()
  29157. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  29158. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  29159. @returns an error description if there's a problem, or an empty string if it succeeds in
  29160. opening the device
  29161. @see close
  29162. */
  29163. virtual const String open (const BigInteger& inputChannels,
  29164. const BigInteger& outputChannels,
  29165. double sampleRate,
  29166. int bufferSizeSamples) = 0;
  29167. /** Closes and releases the device if it's open. */
  29168. virtual void close() = 0;
  29169. /** Returns true if the device is still open.
  29170. A device might spontaneously close itself if something goes wrong, so this checks if
  29171. it's still open.
  29172. */
  29173. virtual bool isOpen() = 0;
  29174. /** Starts the device actually playing.
  29175. This must be called after the device has been opened.
  29176. @param callback the callback to use for streaming the data.
  29177. @see AudioIODeviceCallback, open
  29178. */
  29179. virtual void start (AudioIODeviceCallback* callback) = 0;
  29180. /** Stops the device playing.
  29181. Once a device has been started, this will stop it. Any pending calls to the
  29182. callback class will be flushed before this method returns.
  29183. */
  29184. virtual void stop() = 0;
  29185. /** Returns true if the device is still calling back.
  29186. The device might mysteriously stop, so this checks whether it's
  29187. still playing.
  29188. */
  29189. virtual bool isPlaying() = 0;
  29190. /** Returns the last error that happened if anything went wrong. */
  29191. virtual const String getLastError() = 0;
  29192. /** Returns the buffer size that the device is currently using.
  29193. If the device isn't actually open, this value doesn't really mean much.
  29194. */
  29195. virtual int getCurrentBufferSizeSamples() = 0;
  29196. /** Returns the sample rate that the device is currently using.
  29197. If the device isn't actually open, this value doesn't really mean much.
  29198. */
  29199. virtual double getCurrentSampleRate() = 0;
  29200. /** Returns the device's current physical bit-depth.
  29201. If the device isn't actually open, this value doesn't really mean much.
  29202. */
  29203. virtual int getCurrentBitDepth() = 0;
  29204. /** Returns a mask showing which of the available output channels are currently
  29205. enabled.
  29206. @see getOutputChannelNames
  29207. */
  29208. virtual const BigInteger getActiveOutputChannels() const = 0;
  29209. /** Returns a mask showing which of the available input channels are currently
  29210. enabled.
  29211. @see getInputChannelNames
  29212. */
  29213. virtual const BigInteger getActiveInputChannels() const = 0;
  29214. /** Returns the device's output latency.
  29215. This is the delay in samples between a callback getting a block of data, and
  29216. that data actually getting played.
  29217. */
  29218. virtual int getOutputLatencyInSamples() = 0;
  29219. /** Returns the device's input latency.
  29220. This is the delay in samples between some audio actually arriving at the soundcard,
  29221. and the callback getting passed this block of data.
  29222. */
  29223. virtual int getInputLatencyInSamples() = 0;
  29224. /** True if this device can show a pop-up control panel for editing its settings.
  29225. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  29226. to display it.
  29227. */
  29228. virtual bool hasControlPanel() const;
  29229. /** Shows a device-specific control panel if there is one.
  29230. This should only be called for devices which return true from hasControlPanel().
  29231. */
  29232. virtual bool showControlPanel();
  29233. protected:
  29234. /** Creates a device, setting its name and type member variables. */
  29235. AudioIODevice (const String& deviceName,
  29236. const String& typeName);
  29237. /** @internal */
  29238. String name, typeName;
  29239. };
  29240. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  29241. /*** End of inlined file: juce_AudioIODevice.h ***/
  29242. /**
  29243. Wrapper class to continuously stream audio from an audio source to an
  29244. AudioIODevice.
  29245. This object acts as an AudioIODeviceCallback, so can be attached to an
  29246. output device, and will stream audio from an AudioSource.
  29247. */
  29248. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  29249. {
  29250. public:
  29251. /** Creates an empty AudioSourcePlayer. */
  29252. AudioSourcePlayer();
  29253. /** Destructor.
  29254. Make sure this object isn't still being used by an AudioIODevice before
  29255. deleting it!
  29256. */
  29257. virtual ~AudioSourcePlayer();
  29258. /** Changes the current audio source to play from.
  29259. If the source passed in is already being used, this method will do nothing.
  29260. If the source is not null, its prepareToPlay() method will be called
  29261. before it starts being used for playback.
  29262. If there's another source currently playing, its releaseResources() method
  29263. will be called after it has been swapped for the new one.
  29264. @param newSource the new source to use - this will NOT be deleted
  29265. by this object when no longer needed, so it's the
  29266. caller's responsibility to manage it.
  29267. */
  29268. void setSource (AudioSource* newSource);
  29269. /** Returns the source that's playing.
  29270. May return 0 if there's no source.
  29271. */
  29272. AudioSource* getCurrentSource() const noexcept { return source; }
  29273. /** Sets a gain to apply to the audio data.
  29274. @see getGain
  29275. */
  29276. void setGain (float newGain) noexcept;
  29277. /** Returns the current gain.
  29278. @see setGain
  29279. */
  29280. float getGain() const noexcept { return gain; }
  29281. /** Implementation of the AudioIODeviceCallback method. */
  29282. void audioDeviceIOCallback (const float** inputChannelData,
  29283. int totalNumInputChannels,
  29284. float** outputChannelData,
  29285. int totalNumOutputChannels,
  29286. int numSamples);
  29287. /** Implementation of the AudioIODeviceCallback method. */
  29288. void audioDeviceAboutToStart (AudioIODevice* device);
  29289. /** Implementation of the AudioIODeviceCallback method. */
  29290. void audioDeviceStopped();
  29291. private:
  29292. CriticalSection readLock;
  29293. AudioSource* source;
  29294. double sampleRate;
  29295. int bufferSize;
  29296. float* channels [128];
  29297. float* outputChans [128];
  29298. const float* inputChans [128];
  29299. AudioSampleBuffer tempBuffer;
  29300. float lastGain, gain;
  29301. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSourcePlayer);
  29302. };
  29303. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29304. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  29305. #endif
  29306. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29307. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  29308. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29309. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29310. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  29311. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29312. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29313. /**
  29314. An AudioSource which takes another source as input, and buffers it using a thread.
  29315. Create this as a wrapper around another thread, and it will read-ahead with
  29316. a background thread to smooth out playback. You can either create one of these
  29317. directly, or use it indirectly using an AudioTransportSource.
  29318. @see PositionableAudioSource, AudioTransportSource
  29319. */
  29320. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  29321. {
  29322. public:
  29323. /** Creates a BufferingAudioSource.
  29324. @param source the input source to read from
  29325. @param deleteSourceWhenDeleted if true, then the input source object will
  29326. be deleted when this object is deleted
  29327. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  29328. */
  29329. BufferingAudioSource (PositionableAudioSource* source,
  29330. bool deleteSourceWhenDeleted,
  29331. int numberOfSamplesToBuffer);
  29332. /** Destructor.
  29333. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  29334. flag was set in the constructor.
  29335. */
  29336. ~BufferingAudioSource();
  29337. /** Implementation of the AudioSource method. */
  29338. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29339. /** Implementation of the AudioSource method. */
  29340. void releaseResources();
  29341. /** Implementation of the AudioSource method. */
  29342. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29343. /** Implements the PositionableAudioSource method. */
  29344. void setNextReadPosition (int64 newPosition);
  29345. /** Implements the PositionableAudioSource method. */
  29346. int64 getNextReadPosition() const;
  29347. /** Implements the PositionableAudioSource method. */
  29348. int64 getTotalLength() const { return source->getTotalLength(); }
  29349. /** Implements the PositionableAudioSource method. */
  29350. bool isLooping() const { return source->isLooping(); }
  29351. private:
  29352. PositionableAudioSource* source;
  29353. bool deleteSourceWhenDeleted;
  29354. int numberOfSamplesToBuffer;
  29355. AudioSampleBuffer buffer;
  29356. CriticalSection bufferStartPosLock;
  29357. int64 volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  29358. bool wasSourceLooping;
  29359. double volatile sampleRate;
  29360. friend class SharedBufferingAudioSourceThread;
  29361. bool readNextBufferChunk();
  29362. void readBufferSection (int64 start, int length, int bufferOffset);
  29363. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferingAudioSource);
  29364. };
  29365. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29366. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  29367. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  29368. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29369. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29370. /**
  29371. A type of AudioSource that takes an input source and changes its sample rate.
  29372. @see AudioSource
  29373. */
  29374. class JUCE_API ResamplingAudioSource : public AudioSource
  29375. {
  29376. public:
  29377. /** Creates a ResamplingAudioSource for a given input source.
  29378. @param inputSource the input source to read from
  29379. @param deleteInputWhenDeleted if true, the input source will be deleted when
  29380. this object is deleted
  29381. @param numChannels the number of channels to process
  29382. */
  29383. ResamplingAudioSource (AudioSource* inputSource,
  29384. bool deleteInputWhenDeleted,
  29385. int numChannels = 2);
  29386. /** Destructor. */
  29387. ~ResamplingAudioSource();
  29388. /** Changes the resampling ratio.
  29389. (This value can be changed at any time, even while the source is running).
  29390. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  29391. values will speed it up; lower values will slow it
  29392. down. The ratio must be greater than 0
  29393. */
  29394. void setResamplingRatio (double samplesInPerOutputSample);
  29395. /** Returns the current resampling ratio.
  29396. This is the value that was set by setResamplingRatio().
  29397. */
  29398. double getResamplingRatio() const noexcept { return ratio; }
  29399. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29400. void releaseResources();
  29401. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29402. private:
  29403. AudioSource* const input;
  29404. const bool deleteInputWhenDeleted;
  29405. double ratio, lastRatio;
  29406. AudioSampleBuffer buffer;
  29407. int bufferPos, sampsInBuffer;
  29408. double subSampleOffset;
  29409. double coefficients[6];
  29410. SpinLock ratioLock;
  29411. const int numChannels;
  29412. HeapBlock<float*> destBuffers, srcBuffers;
  29413. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  29414. void createLowPass (double proportionalRate);
  29415. struct FilterState
  29416. {
  29417. double x1, x2, y1, y2;
  29418. };
  29419. HeapBlock<FilterState> filterStates;
  29420. void resetFilters();
  29421. void applyFilter (float* samples, int num, FilterState& fs);
  29422. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResamplingAudioSource);
  29423. };
  29424. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29425. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  29426. /**
  29427. An AudioSource that takes a PositionableAudioSource and allows it to be
  29428. played, stopped, started, etc.
  29429. This can also be told use a buffer and background thread to read ahead, and
  29430. if can correct for different sample-rates.
  29431. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  29432. to control playback of an audio file.
  29433. @see AudioSource, AudioSourcePlayer
  29434. */
  29435. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  29436. public ChangeBroadcaster
  29437. {
  29438. public:
  29439. /** Creates an AudioTransportSource.
  29440. After creating one of these, use the setSource() method to select an input source.
  29441. */
  29442. AudioTransportSource();
  29443. /** Destructor. */
  29444. ~AudioTransportSource();
  29445. /** Sets the reader that is being used as the input source.
  29446. This will stop playback, reset the position to 0 and change to the new reader.
  29447. The source passed in will not be deleted by this object, so must be managed by
  29448. the caller.
  29449. @param newSource the new input source to use. This may be zero
  29450. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  29451. is zero, no reading ahead will be done; if it's
  29452. greater than zero, a BufferingAudioSource will be used
  29453. to do the reading-ahead
  29454. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  29455. rate of the source, and playback will be sample-rate
  29456. adjusted to maintain playback at the correct pitch. If
  29457. this is 0, no sample-rate adjustment will be performed
  29458. @param maxNumChannels the maximum number of channels that may need to be played
  29459. */
  29460. void setSource (PositionableAudioSource* newSource,
  29461. int readAheadBufferSize = 0,
  29462. double sourceSampleRateToCorrectFor = 0.0,
  29463. int maxNumChannels = 2);
  29464. /** Changes the current playback position in the source stream.
  29465. The next time the getNextAudioBlock() method is called, this
  29466. is the time from which it'll read data.
  29467. @see getPosition
  29468. */
  29469. void setPosition (double newPosition);
  29470. /** Returns the position that the next data block will be read from
  29471. This is a time in seconds.
  29472. */
  29473. double getCurrentPosition() const;
  29474. /** Returns the stream's length in seconds. */
  29475. double getLengthInSeconds() const;
  29476. /** Returns true if the player has stopped because its input stream ran out of data.
  29477. */
  29478. bool hasStreamFinished() const noexcept { return inputStreamEOF; }
  29479. /** Starts playing (if a source has been selected).
  29480. If it starts playing, this will send a message to any ChangeListeners
  29481. that are registered with this object.
  29482. */
  29483. void start();
  29484. /** Stops playing.
  29485. If it's actually playing, this will send a message to any ChangeListeners
  29486. that are registered with this object.
  29487. */
  29488. void stop();
  29489. /** Returns true if it's currently playing. */
  29490. bool isPlaying() const noexcept { return playing; }
  29491. /** Changes the gain to apply to the output.
  29492. @param newGain a factor by which to multiply the outgoing samples,
  29493. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  29494. */
  29495. void setGain (float newGain) noexcept;
  29496. /** Returns the current gain setting.
  29497. @see setGain
  29498. */
  29499. float getGain() const noexcept { return gain; }
  29500. /** Implementation of the AudioSource method. */
  29501. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29502. /** Implementation of the AudioSource method. */
  29503. void releaseResources();
  29504. /** Implementation of the AudioSource method. */
  29505. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29506. /** Implements the PositionableAudioSource method. */
  29507. void setNextReadPosition (int64 newPosition);
  29508. /** Implements the PositionableAudioSource method. */
  29509. int64 getNextReadPosition() const;
  29510. /** Implements the PositionableAudioSource method. */
  29511. int64 getTotalLength() const;
  29512. /** Implements the PositionableAudioSource method. */
  29513. bool isLooping() const;
  29514. private:
  29515. PositionableAudioSource* source;
  29516. ResamplingAudioSource* resamplerSource;
  29517. BufferingAudioSource* bufferingSource;
  29518. PositionableAudioSource* positionableSource;
  29519. AudioSource* masterSource;
  29520. CriticalSection callbackLock;
  29521. float volatile gain, lastGain;
  29522. bool volatile playing, stopped;
  29523. double sampleRate, sourceSampleRate;
  29524. int blockSize, readAheadBufferSize;
  29525. bool isPrepared, inputStreamEOF;
  29526. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioTransportSource);
  29527. };
  29528. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29529. /*** End of inlined file: juce_AudioTransportSource.h ***/
  29530. #endif
  29531. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29532. #endif
  29533. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29534. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  29535. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29536. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29537. /**
  29538. An AudioSource that takes the audio from another source, and re-maps its
  29539. input and output channels to a different arrangement.
  29540. You can use this to increase or decrease the number of channels that an
  29541. audio source uses, or to re-order those channels.
  29542. Call the reset() method before using it to set up a default mapping, and then
  29543. the setInputChannelMapping() and setOutputChannelMapping() methods to
  29544. create an appropriate mapping, otherwise no channels will be connected and
  29545. it'll produce silence.
  29546. @see AudioSource
  29547. */
  29548. class ChannelRemappingAudioSource : public AudioSource
  29549. {
  29550. public:
  29551. /** Creates a remapping source that will pass on audio from the given input.
  29552. @param source the input source to use. Make sure that this doesn't
  29553. get deleted before the ChannelRemappingAudioSource object
  29554. @param deleteSourceWhenDeleted if true, the input source will be deleted
  29555. when this object is deleted, if false, the caller is
  29556. responsible for its deletion
  29557. */
  29558. ChannelRemappingAudioSource (AudioSource* source,
  29559. bool deleteSourceWhenDeleted);
  29560. /** Destructor. */
  29561. ~ChannelRemappingAudioSource();
  29562. /** Specifies a number of channels that this audio source must produce from its
  29563. getNextAudioBlock() callback.
  29564. */
  29565. void setNumberOfChannelsToProduce (int requiredNumberOfChannels);
  29566. /** Clears any mapped channels.
  29567. After this, no channels are mapped, so this object will produce silence. Create
  29568. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  29569. */
  29570. void clearAllMappings();
  29571. /** Creates an input channel mapping.
  29572. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  29573. data will be sent to destChannelIndex of our input source.
  29574. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  29575. source specified when this object was created).
  29576. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  29577. during our getNextAudioBlock() callback
  29578. */
  29579. void setInputChannelMapping (int destChannelIndex,
  29580. int sourceChannelIndex);
  29581. /** Creates an output channel mapping.
  29582. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  29583. our input audio source will be copied to channel destChannelIndex of the final buffer.
  29584. @param sourceChannelIndex the index of an output channel coming from our input audio source
  29585. (i.e. the source specified when this object was created).
  29586. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  29587. during our getNextAudioBlock() callback
  29588. */
  29589. void setOutputChannelMapping (int sourceChannelIndex,
  29590. int destChannelIndex);
  29591. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  29592. our input audio source.
  29593. */
  29594. int getRemappedInputChannel (int inputChannelIndex) const;
  29595. /** Returns the output channel to which channel outputChannelIndex of our input audio
  29596. source will be sent to.
  29597. */
  29598. int getRemappedOutputChannel (int outputChannelIndex) const;
  29599. /** Returns an XML object to encapsulate the state of the mappings.
  29600. @see restoreFromXml
  29601. */
  29602. XmlElement* createXml() const;
  29603. /** Restores the mappings from an XML object created by createXML().
  29604. @see createXml
  29605. */
  29606. void restoreFromXml (const XmlElement& e);
  29607. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29608. void releaseResources();
  29609. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29610. private:
  29611. int requiredNumberOfChannels;
  29612. Array <int> remappedInputs, remappedOutputs;
  29613. AudioSource* const source;
  29614. const bool deleteSourceWhenDeleted;
  29615. AudioSampleBuffer buffer;
  29616. AudioSourceChannelInfo remappedInfo;
  29617. CriticalSection lock;
  29618. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelRemappingAudioSource);
  29619. };
  29620. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29621. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  29622. #endif
  29623. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29624. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  29625. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29626. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29627. /*** Start of inlined file: juce_IIRFilter.h ***/
  29628. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  29629. #define __JUCE_IIRFILTER_JUCEHEADER__
  29630. /**
  29631. An IIR filter that can perform low, high, or band-pass filtering on an
  29632. audio signal.
  29633. @see IIRFilterAudioSource
  29634. */
  29635. class JUCE_API IIRFilter
  29636. {
  29637. public:
  29638. /** Creates a filter.
  29639. Initially the filter is inactive, so will have no effect on samples that
  29640. you process with it. Use the appropriate method to turn it into the type
  29641. of filter needed.
  29642. */
  29643. IIRFilter();
  29644. /** Creates a copy of another filter. */
  29645. IIRFilter (const IIRFilter& other);
  29646. /** Destructor. */
  29647. ~IIRFilter();
  29648. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  29649. Note that this clears the processing state, but the type of filter and
  29650. its coefficients aren't changed. To put a filter into an inactive state, use
  29651. the makeInactive() method.
  29652. */
  29653. void reset() noexcept;
  29654. /** Performs the filter operation on the given set of samples.
  29655. */
  29656. void processSamples (float* samples,
  29657. int numSamples) noexcept;
  29658. /** Processes a single sample, without any locking or checking.
  29659. Use this if you need fast processing of a single value, but be aware that
  29660. this isn't thread-safe in the way that processSamples() is.
  29661. */
  29662. float processSingleSampleRaw (float sample) noexcept;
  29663. /** Sets the filter up to act as a low-pass filter.
  29664. */
  29665. void makeLowPass (double sampleRate,
  29666. double frequency) noexcept;
  29667. /** Sets the filter up to act as a high-pass filter.
  29668. */
  29669. void makeHighPass (double sampleRate,
  29670. double frequency) noexcept;
  29671. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  29672. The gain is a scale factor that the low frequencies are multiplied by, so values
  29673. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  29674. attenuate them.
  29675. */
  29676. void makeLowShelf (double sampleRate,
  29677. double cutOffFrequency,
  29678. double Q,
  29679. float gainFactor) noexcept;
  29680. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  29681. The gain is a scale factor that the high frequencies are multiplied by, so values
  29682. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  29683. attenuate them.
  29684. */
  29685. void makeHighShelf (double sampleRate,
  29686. double cutOffFrequency,
  29687. double Q,
  29688. float gainFactor) noexcept;
  29689. /** Sets the filter up to act as a band pass filter centred around a
  29690. frequency, with a variable Q and gain.
  29691. The gain is a scale factor that the centre frequencies are multiplied by, so
  29692. values greater than 1.0 will boost the centre frequencies, values less than
  29693. 1.0 will attenuate them.
  29694. */
  29695. void makeBandPass (double sampleRate,
  29696. double centreFrequency,
  29697. double Q,
  29698. float gainFactor) noexcept;
  29699. /** Clears the filter's coefficients so that it becomes inactive.
  29700. */
  29701. void makeInactive() noexcept;
  29702. /** Makes this filter duplicate the set-up of another one.
  29703. */
  29704. void copyCoefficientsFrom (const IIRFilter& other) noexcept;
  29705. protected:
  29706. CriticalSection processLock;
  29707. void setCoefficients (double c1, double c2, double c3,
  29708. double c4, double c5, double c6) noexcept;
  29709. bool active;
  29710. float coefficients[6];
  29711. float x1, x2, y1, y2;
  29712. // (use the copyCoefficientsFrom() method instead of this operator)
  29713. IIRFilter& operator= (const IIRFilter&);
  29714. JUCE_LEAK_DETECTOR (IIRFilter);
  29715. };
  29716. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  29717. /*** End of inlined file: juce_IIRFilter.h ***/
  29718. /**
  29719. An AudioSource that performs an IIR filter on another source.
  29720. */
  29721. class JUCE_API IIRFilterAudioSource : public AudioSource
  29722. {
  29723. public:
  29724. /** Creates a IIRFilterAudioSource for a given input source.
  29725. @param inputSource the input source to read from
  29726. @param deleteInputWhenDeleted if true, the input source will be deleted when
  29727. this object is deleted
  29728. */
  29729. IIRFilterAudioSource (AudioSource* inputSource,
  29730. bool deleteInputWhenDeleted);
  29731. /** Destructor. */
  29732. ~IIRFilterAudioSource();
  29733. /** Changes the filter to use the same parameters as the one being passed in.
  29734. */
  29735. void setFilterParameters (const IIRFilter& newSettings);
  29736. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29737. void releaseResources();
  29738. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29739. private:
  29740. AudioSource* const input;
  29741. const bool deleteInputWhenDeleted;
  29742. OwnedArray <IIRFilter> iirFilters;
  29743. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IIRFilterAudioSource);
  29744. };
  29745. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29746. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  29747. #endif
  29748. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29749. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  29750. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29751. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29752. /**
  29753. An AudioSource that mixes together the output of a set of other AudioSources.
  29754. Input sources can be added and removed while the mixer is running as long as their
  29755. prepareToPlay() and releaseResources() methods are called before and after adding
  29756. them to the mixer.
  29757. */
  29758. class JUCE_API MixerAudioSource : public AudioSource
  29759. {
  29760. public:
  29761. /** Creates a MixerAudioSource.
  29762. */
  29763. MixerAudioSource();
  29764. /** Destructor. */
  29765. ~MixerAudioSource();
  29766. /** Adds an input source to the mixer.
  29767. If the mixer is running you'll need to make sure that the input source
  29768. is ready to play by calling its prepareToPlay() method before adding it.
  29769. If the mixer is stopped, then its input sources will be automatically
  29770. prepared when the mixer's prepareToPlay() method is called.
  29771. @param newInput the source to add to the mixer
  29772. @param deleteWhenRemoved if true, then this source will be deleted when
  29773. the mixer is deleted or when removeAllInputs() is
  29774. called (unless the source is previously removed
  29775. with the removeInputSource method)
  29776. */
  29777. void addInputSource (AudioSource* newInput, bool deleteWhenRemoved);
  29778. /** Removes an input source.
  29779. If the mixer is running, this will remove the source but not call its
  29780. releaseResources() method, so the caller might want to do this manually.
  29781. @param input the source to remove
  29782. @param deleteSource whether to delete this source after it's been removed
  29783. */
  29784. void removeInputSource (AudioSource* input, bool deleteSource);
  29785. /** Removes all the input sources.
  29786. If the mixer is running, this will remove the sources but not call their
  29787. releaseResources() method, so the caller might want to do this manually.
  29788. Any sources which were added with the deleteWhenRemoved flag set will be
  29789. deleted by this method.
  29790. */
  29791. void removeAllInputs();
  29792. /** Implementation of the AudioSource method.
  29793. This will call prepareToPlay() on all its input sources.
  29794. */
  29795. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29796. /** Implementation of the AudioSource method.
  29797. This will call releaseResources() on all its input sources.
  29798. */
  29799. void releaseResources();
  29800. /** Implementation of the AudioSource method. */
  29801. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29802. private:
  29803. Array <AudioSource*> inputs;
  29804. BigInteger inputsToDelete;
  29805. CriticalSection lock;
  29806. AudioSampleBuffer tempBuffer;
  29807. double currentSampleRate;
  29808. int bufferSizeExpected;
  29809. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MixerAudioSource);
  29810. };
  29811. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29812. /*** End of inlined file: juce_MixerAudioSource.h ***/
  29813. #endif
  29814. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29815. #endif
  29816. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29817. #endif
  29818. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29819. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  29820. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29821. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29822. /**
  29823. A simple AudioSource that generates a sine wave.
  29824. */
  29825. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  29826. {
  29827. public:
  29828. /** Creates a ToneGeneratorAudioSource. */
  29829. ToneGeneratorAudioSource();
  29830. /** Destructor. */
  29831. ~ToneGeneratorAudioSource();
  29832. /** Sets the signal's amplitude. */
  29833. void setAmplitude (float newAmplitude);
  29834. /** Sets the signal's frequency. */
  29835. void setFrequency (double newFrequencyHz);
  29836. /** Implementation of the AudioSource method. */
  29837. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29838. /** Implementation of the AudioSource method. */
  29839. void releaseResources();
  29840. /** Implementation of the AudioSource method. */
  29841. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29842. private:
  29843. double frequency, sampleRate;
  29844. double currentPhase, phasePerSample;
  29845. float amplitude;
  29846. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToneGeneratorAudioSource);
  29847. };
  29848. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29849. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  29850. #endif
  29851. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29852. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  29853. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29854. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29855. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  29856. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29857. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29858. class AudioDeviceManager;
  29859. class Component;
  29860. /**
  29861. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  29862. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  29863. method. Each of the objects returned can then be used to list the available
  29864. devices of that type. E.g.
  29865. @code
  29866. OwnedArray <AudioIODeviceType> types;
  29867. myAudioDeviceManager.createAudioDeviceTypes (types);
  29868. for (int i = 0; i < types.size(); ++i)
  29869. {
  29870. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  29871. types[i]->scanForDevices(); // This must be called before getting the list of devices
  29872. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  29873. for (int j = 0; j < deviceNames.size(); ++j)
  29874. {
  29875. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  29876. ...
  29877. }
  29878. }
  29879. @endcode
  29880. For an easier way of managing audio devices and their settings, have a look at the
  29881. AudioDeviceManager class.
  29882. @see AudioIODevice, AudioDeviceManager
  29883. */
  29884. class JUCE_API AudioIODeviceType
  29885. {
  29886. public:
  29887. /** Returns the name of this type of driver that this object manages.
  29888. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  29889. */
  29890. const String& getTypeName() const noexcept { return typeName; }
  29891. /** Refreshes the object's cached list of known devices.
  29892. This must be called at least once before calling getDeviceNames() or any of
  29893. the other device creation methods.
  29894. */
  29895. virtual void scanForDevices() = 0;
  29896. /** Returns the list of available devices of this type.
  29897. The scanForDevices() method must have been called to create this list.
  29898. @param wantInputNames only really used by DirectSound where devices are split up
  29899. into inputs and outputs, this indicates whether to use
  29900. the input or output name to refer to a pair of devices.
  29901. */
  29902. virtual const StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  29903. /** Returns the name of the default device.
  29904. This will be one of the names from the getDeviceNames() list.
  29905. @param forInput if true, this means that a default input device should be
  29906. returned; if false, it should return the default output
  29907. */
  29908. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  29909. /** Returns the index of a given device in the list of device names.
  29910. If asInput is true, it shows the index in the inputs list, otherwise it
  29911. looks for it in the outputs list.
  29912. */
  29913. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  29914. /** Returns true if two different devices can be used for the input and output.
  29915. */
  29916. virtual bool hasSeparateInputsAndOutputs() const = 0;
  29917. /** Creates one of the devices of this type.
  29918. The deviceName must be one of the strings returned by getDeviceNames(), and
  29919. scanForDevices() must have been called before this method is used.
  29920. */
  29921. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  29922. const String& inputDeviceName) = 0;
  29923. struct DeviceSetupDetails
  29924. {
  29925. AudioDeviceManager* manager;
  29926. int minNumInputChannels, maxNumInputChannels;
  29927. int minNumOutputChannels, maxNumOutputChannels;
  29928. bool useStereoPairs;
  29929. };
  29930. /** Destructor. */
  29931. virtual ~AudioIODeviceType();
  29932. /** Creates a CoreAudio device type if it's available on this platform, or returns null. */
  29933. static AudioIODeviceType* createAudioIODeviceType_CoreAudio();
  29934. /** Creates an iOS device type if it's available on this platform, or returns null. */
  29935. static AudioIODeviceType* createAudioIODeviceType_iOSAudio();
  29936. /** Creates a WASAPI device type if it's available on this platform, or returns null. */
  29937. static AudioIODeviceType* createAudioIODeviceType_WASAPI();
  29938. /** Creates a DirectSound device type if it's available on this platform, or returns null. */
  29939. static AudioIODeviceType* createAudioIODeviceType_DirectSound();
  29940. /** Creates an ASIO device type if it's available on this platform, or returns null. */
  29941. static AudioIODeviceType* createAudioIODeviceType_ASIO();
  29942. /** Creates an ALSA device type if it's available on this platform, or returns null. */
  29943. static AudioIODeviceType* createAudioIODeviceType_ALSA();
  29944. /** Creates a JACK device type if it's available on this platform, or returns null. */
  29945. static AudioIODeviceType* createAudioIODeviceType_JACK();
  29946. /** Creates an Android device type if it's available on this platform, or returns null. */
  29947. static AudioIODeviceType* createAudioIODeviceType_Android();
  29948. protected:
  29949. explicit AudioIODeviceType (const String& typeName);
  29950. private:
  29951. String typeName;
  29952. JUCE_DECLARE_NON_COPYABLE (AudioIODeviceType);
  29953. };
  29954. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29955. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  29956. /*** Start of inlined file: juce_MidiInput.h ***/
  29957. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  29958. #define __JUCE_MIDIINPUT_JUCEHEADER__
  29959. /*** Start of inlined file: juce_MidiMessage.h ***/
  29960. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  29961. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  29962. /**
  29963. Encapsulates a MIDI message.
  29964. @see MidiMessageSequence, MidiOutput, MidiInput
  29965. */
  29966. class JUCE_API MidiMessage
  29967. {
  29968. public:
  29969. /** Creates a 3-byte short midi message.
  29970. @param byte1 message byte 1
  29971. @param byte2 message byte 2
  29972. @param byte3 message byte 3
  29973. @param timeStamp the time to give the midi message - this value doesn't
  29974. use any particular units, so will be application-specific
  29975. */
  29976. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) noexcept;
  29977. /** Creates a 2-byte short midi message.
  29978. @param byte1 message byte 1
  29979. @param byte2 message byte 2
  29980. @param timeStamp the time to give the midi message - this value doesn't
  29981. use any particular units, so will be application-specific
  29982. */
  29983. MidiMessage (int byte1, int byte2, double timeStamp = 0) noexcept;
  29984. /** Creates a 1-byte short midi message.
  29985. @param byte1 message byte 1
  29986. @param timeStamp the time to give the midi message - this value doesn't
  29987. use any particular units, so will be application-specific
  29988. */
  29989. MidiMessage (int byte1, double timeStamp = 0) noexcept;
  29990. /** Creates a midi message from a block of data. */
  29991. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  29992. /** Reads the next midi message from some data.
  29993. This will read as many bytes from a data stream as it needs to make a
  29994. complete message, and will return the number of bytes it used. This lets
  29995. you read a sequence of midi messages from a file or stream.
  29996. @param data the data to read from
  29997. @param maxBytesToUse the maximum number of bytes it's allowed to read
  29998. @param numBytesUsed returns the number of bytes that were actually needed
  29999. @param lastStatusByte in a sequence of midi messages, the initial byte
  30000. can be dropped from a message if it's the same as the
  30001. first byte of the previous message, so this lets you
  30002. supply the byte to use if the first byte of the message
  30003. has in fact been dropped.
  30004. @param timeStamp the time to give the midi message - this value doesn't
  30005. use any particular units, so will be application-specific
  30006. */
  30007. MidiMessage (const void* data, int maxBytesToUse,
  30008. int& numBytesUsed, uint8 lastStatusByte,
  30009. double timeStamp = 0);
  30010. /** Creates an active-sense message.
  30011. Since the MidiMessage has to contain a valid message, this default constructor
  30012. just initialises it with an empty sysex message.
  30013. */
  30014. MidiMessage() noexcept;
  30015. /** Creates a copy of another midi message. */
  30016. MidiMessage (const MidiMessage& other);
  30017. /** Creates a copy of another midi message, with a different timestamp. */
  30018. MidiMessage (const MidiMessage& other, double newTimeStamp);
  30019. /** Destructor. */
  30020. ~MidiMessage();
  30021. /** Copies this message from another one. */
  30022. MidiMessage& operator= (const MidiMessage& other);
  30023. /** Returns a pointer to the raw midi data.
  30024. @see getRawDataSize
  30025. */
  30026. uint8* getRawData() const noexcept { return data; }
  30027. /** Returns the number of bytes of data in the message.
  30028. @see getRawData
  30029. */
  30030. int getRawDataSize() const noexcept { return size; }
  30031. /** Returns the timestamp associated with this message.
  30032. The exact meaning of this time and its units will vary, as messages are used in
  30033. a variety of different contexts.
  30034. If you're getting the message from a midi file, this could be a time in seconds, or
  30035. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  30036. If the message is being used in a MidiBuffer, it might indicate the number of
  30037. audio samples from the start of the buffer.
  30038. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  30039. for details of the way that it initialises this value.
  30040. @see setTimeStamp, addToTimeStamp
  30041. */
  30042. double getTimeStamp() const noexcept { return timeStamp; }
  30043. /** Changes the message's associated timestamp.
  30044. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  30045. @see addToTimeStamp, getTimeStamp
  30046. */
  30047. void setTimeStamp (double newTimestamp) noexcept { timeStamp = newTimestamp; }
  30048. /** Adds a value to the message's timestamp.
  30049. The units for the timestamp will be application-specific.
  30050. */
  30051. void addToTimeStamp (double delta) noexcept { timeStamp += delta; }
  30052. /** Returns the midi channel associated with the message.
  30053. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  30054. if it's a sysex)
  30055. @see isForChannel, setChannel
  30056. */
  30057. int getChannel() const noexcept;
  30058. /** Returns true if the message applies to the given midi channel.
  30059. @param channelNumber the channel number to look for, in the range 1 to 16
  30060. @see getChannel, setChannel
  30061. */
  30062. bool isForChannel (int channelNumber) const noexcept;
  30063. /** Changes the message's midi channel.
  30064. This won't do anything for non-channel messages like sysexes.
  30065. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  30066. */
  30067. void setChannel (int newChannelNumber) noexcept;
  30068. /** Returns true if this is a system-exclusive message.
  30069. */
  30070. bool isSysEx() const noexcept;
  30071. /** Returns a pointer to the sysex data inside the message.
  30072. If this event isn't a sysex event, it'll return 0.
  30073. @see getSysExDataSize
  30074. */
  30075. const uint8* getSysExData() const noexcept;
  30076. /** Returns the size of the sysex data.
  30077. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  30078. @see getSysExData
  30079. */
  30080. int getSysExDataSize() const noexcept;
  30081. /** Returns true if this message is a 'key-down' event.
  30082. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  30083. velocity 0, it will still be considered to be a note-on and the
  30084. method will return true. If returnTrueForVelocity0 is false, then
  30085. if this is a note-on event with velocity 0, it'll be regarded as
  30086. a note-off, and the method will return false
  30087. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  30088. */
  30089. bool isNoteOn (bool returnTrueForVelocity0 = false) const noexcept;
  30090. /** Creates a key-down message (using a floating-point velocity).
  30091. @param channel the midi channel, in the range 1 to 16
  30092. @param noteNumber the key number, 0 to 127
  30093. @param velocity in the range 0 to 1.0
  30094. @see isNoteOn
  30095. */
  30096. static const MidiMessage noteOn (int channel, int noteNumber, float velocity) noexcept;
  30097. /** Creates a key-down message (using an integer velocity).
  30098. @param channel the midi channel, in the range 1 to 16
  30099. @param noteNumber the key number, 0 to 127
  30100. @param velocity in the range 0 to 127
  30101. @see isNoteOn
  30102. */
  30103. static const MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) noexcept;
  30104. /** Returns true if this message is a 'key-up' event.
  30105. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  30106. for a note-on event with a velocity of 0.
  30107. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  30108. */
  30109. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const noexcept;
  30110. /** Creates a key-up message.
  30111. @param channel the midi channel, in the range 1 to 16
  30112. @param noteNumber the key number, 0 to 127
  30113. @param velocity in the range 0 to 127
  30114. @see isNoteOff
  30115. */
  30116. static const MidiMessage noteOff (int channel, int noteNumber, uint8 velocity = 0) noexcept;
  30117. /** Returns true if this message is a 'key-down' or 'key-up' event.
  30118. @see isNoteOn, isNoteOff
  30119. */
  30120. bool isNoteOnOrOff() const noexcept;
  30121. /** Returns the midi note number for note-on and note-off messages.
  30122. If the message isn't a note-on or off, the value returned will be
  30123. meaningless.
  30124. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  30125. */
  30126. int getNoteNumber() const noexcept;
  30127. /** Changes the midi note number of a note-on or note-off message.
  30128. If the message isn't a note on or off, this will do nothing.
  30129. */
  30130. void setNoteNumber (int newNoteNumber) noexcept;
  30131. /** Returns the velocity of a note-on or note-off message.
  30132. The value returned will be in the range 0 to 127.
  30133. If the message isn't a note-on or off event, it will return 0.
  30134. @see getFloatVelocity
  30135. */
  30136. uint8 getVelocity() const noexcept;
  30137. /** Returns the velocity of a note-on or note-off message.
  30138. The value returned will be in the range 0 to 1.0
  30139. If the message isn't a note-on or off event, it will return 0.
  30140. @see getVelocity, setVelocity
  30141. */
  30142. float getFloatVelocity() const noexcept;
  30143. /** Changes the velocity of a note-on or note-off message.
  30144. If the message isn't a note on or off, this will do nothing.
  30145. @param newVelocity the new velocity, in the range 0 to 1.0
  30146. @see getFloatVelocity, multiplyVelocity
  30147. */
  30148. void setVelocity (float newVelocity) noexcept;
  30149. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  30150. If the message isn't a note on or off, this will do nothing.
  30151. @param scaleFactor the value by which to multiply the velocity
  30152. @see setVelocity
  30153. */
  30154. void multiplyVelocity (float scaleFactor) noexcept;
  30155. /** Returns true if the message is a program (patch) change message.
  30156. @see getProgramChangeNumber, getGMInstrumentName
  30157. */
  30158. bool isProgramChange() const noexcept;
  30159. /** Returns the new program number of a program change message.
  30160. If the message isn't a program change, the value returned will be
  30161. nonsense.
  30162. @see isProgramChange, getGMInstrumentName
  30163. */
  30164. int getProgramChangeNumber() const noexcept;
  30165. /** Creates a program-change message.
  30166. @param channel the midi channel, in the range 1 to 16
  30167. @param programNumber the midi program number, 0 to 127
  30168. @see isProgramChange, getGMInstrumentName
  30169. */
  30170. static const MidiMessage programChange (int channel, int programNumber) noexcept;
  30171. /** Returns true if the message is a pitch-wheel move.
  30172. @see getPitchWheelValue, pitchWheel
  30173. */
  30174. bool isPitchWheel() const noexcept;
  30175. /** Returns the pitch wheel position from a pitch-wheel move message.
  30176. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  30177. If called for messages which aren't pitch wheel events, the number returned will be
  30178. nonsense.
  30179. @see isPitchWheel
  30180. */
  30181. int getPitchWheelValue() const noexcept;
  30182. /** Creates a pitch-wheel move message.
  30183. @param channel the midi channel, in the range 1 to 16
  30184. @param position the wheel position, in the range 0 to 16383
  30185. @see isPitchWheel
  30186. */
  30187. static const MidiMessage pitchWheel (int channel, int position) noexcept;
  30188. /** Returns true if the message is an aftertouch event.
  30189. For aftertouch events, use the getNoteNumber() method to find out the key
  30190. that it applies to, and getAftertouchValue() to find out the amount. Use
  30191. getChannel() to find out the channel.
  30192. @see getAftertouchValue, getNoteNumber
  30193. */
  30194. bool isAftertouch() const noexcept;
  30195. /** Returns the amount of aftertouch from an aftertouch messages.
  30196. The value returned is in the range 0 to 127, and will be nonsense for messages
  30197. other than aftertouch messages.
  30198. @see isAftertouch
  30199. */
  30200. int getAfterTouchValue() const noexcept;
  30201. /** Creates an aftertouch message.
  30202. @param channel the midi channel, in the range 1 to 16
  30203. @param noteNumber the key number, 0 to 127
  30204. @param aftertouchAmount the amount of aftertouch, 0 to 127
  30205. @see isAftertouch
  30206. */
  30207. static const MidiMessage aftertouchChange (int channel,
  30208. int noteNumber,
  30209. int aftertouchAmount) noexcept;
  30210. /** Returns true if the message is a channel-pressure change event.
  30211. This is like aftertouch, but common to the whole channel rather than a specific
  30212. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  30213. to find out the channel.
  30214. @see channelPressureChange
  30215. */
  30216. bool isChannelPressure() const noexcept;
  30217. /** Returns the pressure from a channel pressure change message.
  30218. @returns the pressure, in the range 0 to 127
  30219. @see isChannelPressure, channelPressureChange
  30220. */
  30221. int getChannelPressureValue() const noexcept;
  30222. /** Creates a channel-pressure change event.
  30223. @param channel the midi channel: 1 to 16
  30224. @param pressure the pressure, 0 to 127
  30225. @see isChannelPressure
  30226. */
  30227. static const MidiMessage channelPressureChange (int channel, int pressure) noexcept;
  30228. /** Returns true if this is a midi controller message.
  30229. @see getControllerNumber, getControllerValue, controllerEvent
  30230. */
  30231. bool isController() const noexcept;
  30232. /** Returns the controller number of a controller message.
  30233. The name of the controller can be looked up using the getControllerName() method.
  30234. Note that the value returned is invalid for messages that aren't controller changes.
  30235. @see isController, getControllerName, getControllerValue
  30236. */
  30237. int getControllerNumber() const noexcept;
  30238. /** Returns the controller value from a controller message.
  30239. A value 0 to 127 is returned to indicate the new controller position.
  30240. Note that the value returned is invalid for messages that aren't controller changes.
  30241. @see isController, getControllerNumber
  30242. */
  30243. int getControllerValue() const noexcept;
  30244. /** Creates a controller message.
  30245. @param channel the midi channel, in the range 1 to 16
  30246. @param controllerType the type of controller
  30247. @param value the controller value
  30248. @see isController
  30249. */
  30250. static const MidiMessage controllerEvent (int channel,
  30251. int controllerType,
  30252. int value) noexcept;
  30253. /** Checks whether this message is an all-notes-off message.
  30254. @see allNotesOff
  30255. */
  30256. bool isAllNotesOff() const noexcept;
  30257. /** Checks whether this message is an all-sound-off message.
  30258. @see allSoundOff
  30259. */
  30260. bool isAllSoundOff() const noexcept;
  30261. /** Creates an all-notes-off message.
  30262. @param channel the midi channel, in the range 1 to 16
  30263. @see isAllNotesOff
  30264. */
  30265. static const MidiMessage allNotesOff (int channel) noexcept;
  30266. /** Creates an all-sound-off message.
  30267. @param channel the midi channel, in the range 1 to 16
  30268. @see isAllSoundOff
  30269. */
  30270. static const MidiMessage allSoundOff (int channel) noexcept;
  30271. /** Creates an all-controllers-off message.
  30272. @param channel the midi channel, in the range 1 to 16
  30273. */
  30274. static const MidiMessage allControllersOff (int channel) noexcept;
  30275. /** Returns true if this event is a meta-event.
  30276. Meta-events are things like tempo changes, track names, etc.
  30277. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  30278. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  30279. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  30280. */
  30281. bool isMetaEvent() const noexcept;
  30282. /** Returns a meta-event's type number.
  30283. If the message isn't a meta-event, this will return -1.
  30284. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  30285. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  30286. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  30287. */
  30288. int getMetaEventType() const noexcept;
  30289. /** Returns a pointer to the data in a meta-event.
  30290. @see isMetaEvent, getMetaEventLength
  30291. */
  30292. const uint8* getMetaEventData() const noexcept;
  30293. /** Returns the length of the data for a meta-event.
  30294. @see isMetaEvent, getMetaEventData
  30295. */
  30296. int getMetaEventLength() const noexcept;
  30297. /** Returns true if this is a 'track' meta-event. */
  30298. bool isTrackMetaEvent() const noexcept;
  30299. /** Returns true if this is an 'end-of-track' meta-event. */
  30300. bool isEndOfTrackMetaEvent() const noexcept;
  30301. /** Creates an end-of-track meta-event.
  30302. @see isEndOfTrackMetaEvent
  30303. */
  30304. static const MidiMessage endOfTrack() noexcept;
  30305. /** Returns true if this is an 'track name' meta-event.
  30306. You can use the getTextFromTextMetaEvent() method to get the track's name.
  30307. */
  30308. bool isTrackNameEvent() const noexcept;
  30309. /** Returns true if this is a 'text' meta-event.
  30310. @see getTextFromTextMetaEvent
  30311. */
  30312. bool isTextMetaEvent() const noexcept;
  30313. /** Returns the text from a text meta-event.
  30314. @see isTextMetaEvent
  30315. */
  30316. const String getTextFromTextMetaEvent() const;
  30317. /** Returns true if this is a 'tempo' meta-event.
  30318. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  30319. */
  30320. bool isTempoMetaEvent() const noexcept;
  30321. /** Returns the tick length from a tempo meta-event.
  30322. @param timeFormat the 16-bit time format value from the midi file's header.
  30323. @returns the tick length (in seconds).
  30324. @see isTempoMetaEvent
  30325. */
  30326. double getTempoMetaEventTickLength (short timeFormat) const noexcept;
  30327. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  30328. @see isTempoMetaEvent, getTempoMetaEventTickLength
  30329. */
  30330. double getTempoSecondsPerQuarterNote() const noexcept;
  30331. /** Creates a tempo meta-event.
  30332. @see isTempoMetaEvent
  30333. */
  30334. static const MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) noexcept;
  30335. /** Returns true if this is a 'time-signature' meta-event.
  30336. @see getTimeSignatureInfo
  30337. */
  30338. bool isTimeSignatureMetaEvent() const noexcept;
  30339. /** Returns the time-signature values from a time-signature meta-event.
  30340. @see isTimeSignatureMetaEvent
  30341. */
  30342. void getTimeSignatureInfo (int& numerator, int& denominator) const noexcept;
  30343. /** Creates a time-signature meta-event.
  30344. @see isTimeSignatureMetaEvent
  30345. */
  30346. static const MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  30347. /** Returns true if this is a 'key-signature' meta-event.
  30348. @see getKeySignatureNumberOfSharpsOrFlats
  30349. */
  30350. bool isKeySignatureMetaEvent() const noexcept;
  30351. /** Returns the key from a key-signature meta-event.
  30352. @see isKeySignatureMetaEvent
  30353. */
  30354. int getKeySignatureNumberOfSharpsOrFlats() const noexcept;
  30355. /** Returns true if this is a 'channel' meta-event.
  30356. A channel meta-event specifies the midi channel that should be used
  30357. for subsequent meta-events.
  30358. @see getMidiChannelMetaEventChannel
  30359. */
  30360. bool isMidiChannelMetaEvent() const noexcept;
  30361. /** Returns the channel number from a channel meta-event.
  30362. @returns the channel, in the range 1 to 16.
  30363. @see isMidiChannelMetaEvent
  30364. */
  30365. int getMidiChannelMetaEventChannel() const noexcept;
  30366. /** Creates a midi channel meta-event.
  30367. @param channel the midi channel, in the range 1 to 16
  30368. @see isMidiChannelMetaEvent
  30369. */
  30370. static const MidiMessage midiChannelMetaEvent (int channel) noexcept;
  30371. /** Returns true if this is an active-sense message. */
  30372. bool isActiveSense() const noexcept;
  30373. /** Returns true if this is a midi start event.
  30374. @see midiStart
  30375. */
  30376. bool isMidiStart() const noexcept;
  30377. /** Creates a midi start event. */
  30378. static const MidiMessage midiStart() noexcept;
  30379. /** Returns true if this is a midi continue event.
  30380. @see midiContinue
  30381. */
  30382. bool isMidiContinue() const noexcept;
  30383. /** Creates a midi continue event. */
  30384. static const MidiMessage midiContinue() noexcept;
  30385. /** Returns true if this is a midi stop event.
  30386. @see midiStop
  30387. */
  30388. bool isMidiStop() const noexcept;
  30389. /** Creates a midi stop event. */
  30390. static const MidiMessage midiStop() noexcept;
  30391. /** Returns true if this is a midi clock event.
  30392. @see midiClock, songPositionPointer
  30393. */
  30394. bool isMidiClock() const noexcept;
  30395. /** Creates a midi clock event. */
  30396. static const MidiMessage midiClock() noexcept;
  30397. /** Returns true if this is a song-position-pointer message.
  30398. @see getSongPositionPointerMidiBeat, songPositionPointer
  30399. */
  30400. bool isSongPositionPointer() const noexcept;
  30401. /** Returns the midi beat-number of a song-position-pointer message.
  30402. @see isSongPositionPointer, songPositionPointer
  30403. */
  30404. int getSongPositionPointerMidiBeat() const noexcept;
  30405. /** Creates a song-position-pointer message.
  30406. The position is a number of midi beats from the start of the song, where 1 midi
  30407. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  30408. are 4 midi beats in a quarter-note.
  30409. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  30410. */
  30411. static const MidiMessage songPositionPointer (int positionInMidiBeats) noexcept;
  30412. /** Returns true if this is a quarter-frame midi timecode message.
  30413. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  30414. */
  30415. bool isQuarterFrame() const noexcept;
  30416. /** Returns the sequence number of a quarter-frame midi timecode message.
  30417. This will be a value between 0 and 7.
  30418. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  30419. */
  30420. int getQuarterFrameSequenceNumber() const noexcept;
  30421. /** Returns the value from a quarter-frame message.
  30422. This will be the lower nybble of the message's data-byte, a value
  30423. between 0 and 15
  30424. */
  30425. int getQuarterFrameValue() const noexcept;
  30426. /** Creates a quarter-frame MTC message.
  30427. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  30428. @param value a value 0 to 15 for the lower nybble of the message's data byte
  30429. */
  30430. static const MidiMessage quarterFrame (int sequenceNumber, int value) noexcept;
  30431. /** SMPTE timecode types.
  30432. Used by the getFullFrameParameters() and fullFrame() methods.
  30433. */
  30434. enum SmpteTimecodeType
  30435. {
  30436. fps24 = 0,
  30437. fps25 = 1,
  30438. fps30drop = 2,
  30439. fps30 = 3
  30440. };
  30441. /** Returns true if this is a full-frame midi timecode message.
  30442. */
  30443. bool isFullFrame() const noexcept;
  30444. /** Extracts the timecode information from a full-frame midi timecode message.
  30445. You should only call this on messages where you've used isFullFrame() to
  30446. check that they're the right kind.
  30447. */
  30448. void getFullFrameParameters (int& hours,
  30449. int& minutes,
  30450. int& seconds,
  30451. int& frames,
  30452. SmpteTimecodeType& timecodeType) const noexcept;
  30453. /** Creates a full-frame MTC message.
  30454. */
  30455. static const MidiMessage fullFrame (int hours,
  30456. int minutes,
  30457. int seconds,
  30458. int frames,
  30459. SmpteTimecodeType timecodeType);
  30460. /** Types of MMC command.
  30461. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  30462. */
  30463. enum MidiMachineControlCommand
  30464. {
  30465. mmc_stop = 1,
  30466. mmc_play = 2,
  30467. mmc_deferredplay = 3,
  30468. mmc_fastforward = 4,
  30469. mmc_rewind = 5,
  30470. mmc_recordStart = 6,
  30471. mmc_recordStop = 7,
  30472. mmc_pause = 9
  30473. };
  30474. /** Checks whether this is an MMC message.
  30475. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  30476. */
  30477. bool isMidiMachineControlMessage() const noexcept;
  30478. /** For an MMC message, this returns its type.
  30479. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  30480. calling this method.
  30481. */
  30482. MidiMachineControlCommand getMidiMachineControlCommand() const noexcept;
  30483. /** Creates an MMC message.
  30484. */
  30485. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  30486. /** Checks whether this is an MMC "goto" message.
  30487. If it is, the parameters passed-in are set to the time that the message contains.
  30488. @see midiMachineControlGoto
  30489. */
  30490. bool isMidiMachineControlGoto (int& hours,
  30491. int& minutes,
  30492. int& seconds,
  30493. int& frames) const noexcept;
  30494. /** Creates an MMC "goto" message.
  30495. This messages tells the device to go to a specific frame.
  30496. @see isMidiMachineControlGoto
  30497. */
  30498. static const MidiMessage midiMachineControlGoto (int hours,
  30499. int minutes,
  30500. int seconds,
  30501. int frames);
  30502. /** Creates a master-volume change message.
  30503. @param volume the volume, 0 to 1.0
  30504. */
  30505. static const MidiMessage masterVolume (float volume);
  30506. /** Creates a system-exclusive message.
  30507. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  30508. */
  30509. static const MidiMessage createSysExMessage (const uint8* sysexData,
  30510. int dataSize);
  30511. /** Reads a midi variable-length integer.
  30512. @param data the data to read the number from
  30513. @param numBytesUsed on return, this will be set to the number of bytes that were read
  30514. */
  30515. static int readVariableLengthVal (const uint8* data,
  30516. int& numBytesUsed) noexcept;
  30517. /** Based on the first byte of a short midi message, this uses a lookup table
  30518. to return the message length (either 1, 2, or 3 bytes).
  30519. The value passed in must be 0x80 or higher.
  30520. */
  30521. static int getMessageLengthFromFirstByte (const uint8 firstByte) noexcept;
  30522. /** Returns the name of a midi note number.
  30523. E.g "C", "D#", etc.
  30524. @param noteNumber the midi note number, 0 to 127
  30525. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  30526. they'll be flattened, e.g. "Db"
  30527. @param includeOctaveNumber if true, the octave number will be appended to the string,
  30528. e.g. "C#4"
  30529. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  30530. number that will be used for middle C's octave
  30531. @see getMidiNoteInHertz
  30532. */
  30533. static const String getMidiNoteName (int noteNumber,
  30534. bool useSharps,
  30535. bool includeOctaveNumber,
  30536. int octaveNumForMiddleC);
  30537. /** Returns the frequency of a midi note number.
  30538. The frequencyOfA parameter is an optional frequency for 'A', normally 440-444Hz for concert pitch.
  30539. @see getMidiNoteName
  30540. */
  30541. static const double getMidiNoteInHertz (int noteNumber, const double frequencyOfA = 440.0) noexcept;
  30542. /** Returns the standard name of a GM instrument.
  30543. @param midiInstrumentNumber the program number 0 to 127
  30544. @see getProgramChangeNumber
  30545. */
  30546. static const String getGMInstrumentName (int midiInstrumentNumber);
  30547. /** Returns the name of a bank of GM instruments.
  30548. @param midiBankNumber the bank, 0 to 15
  30549. */
  30550. static const String getGMInstrumentBankName (int midiBankNumber);
  30551. /** Returns the standard name of a channel 10 percussion sound.
  30552. @param midiNoteNumber the key number, 35 to 81
  30553. */
  30554. static const String getRhythmInstrumentName (int midiNoteNumber);
  30555. /** Returns the name of a controller type number.
  30556. @see getControllerNumber
  30557. */
  30558. static const String getControllerName (int controllerNumber);
  30559. private:
  30560. double timeStamp;
  30561. uint8* data;
  30562. int size;
  30563. #ifndef DOXYGEN
  30564. union
  30565. {
  30566. uint8 asBytes[4];
  30567. uint32 asInt32;
  30568. } preallocatedData;
  30569. #endif
  30570. };
  30571. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  30572. /*** End of inlined file: juce_MidiMessage.h ***/
  30573. class MidiInput;
  30574. /**
  30575. Receives incoming messages from a physical MIDI input device.
  30576. This class is overridden to handle incoming midi messages. See the MidiInput
  30577. class for more details.
  30578. @see MidiInput
  30579. */
  30580. class JUCE_API MidiInputCallback
  30581. {
  30582. public:
  30583. /** Destructor. */
  30584. virtual ~MidiInputCallback() {}
  30585. /** Receives an incoming message.
  30586. A MidiInput object will call this method when a midi event arrives. It'll be
  30587. called on a high-priority system thread, so avoid doing anything time-consuming
  30588. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  30589. for queueing incoming messages for use later.
  30590. @param source the MidiInput object that generated the message
  30591. @param message the incoming message. The message's timestamp is set to a value
  30592. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  30593. time when the message arrived.
  30594. */
  30595. virtual void handleIncomingMidiMessage (MidiInput* source,
  30596. const MidiMessage& message) = 0;
  30597. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  30598. If a long sysex message is broken up into multiple packets, this callback is made
  30599. for each packet that arrives until the message is finished, at which point
  30600. the normal handleIncomingMidiMessage() callback will be made with the entire
  30601. message.
  30602. The message passed in will contain the start of a sysex, but won't be finished
  30603. with the terminating 0xf7 byte.
  30604. */
  30605. virtual void handlePartialSysexMessage (MidiInput* source,
  30606. const uint8* messageData,
  30607. const int numBytesSoFar,
  30608. const double timestamp)
  30609. {
  30610. // (this bit is just to avoid compiler warnings about unused variables)
  30611. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  30612. }
  30613. };
  30614. /**
  30615. Represents a midi input device.
  30616. To create one of these, use the static getDevices() method to find out what inputs are
  30617. available, and then use the openDevice() method to try to open one.
  30618. @see MidiOutput
  30619. */
  30620. class JUCE_API MidiInput
  30621. {
  30622. public:
  30623. /** Returns a list of the available midi input devices.
  30624. You can open one of the devices by passing its index into the
  30625. openDevice() method.
  30626. @see getDefaultDeviceIndex, openDevice
  30627. */
  30628. static const StringArray getDevices();
  30629. /** Returns the index of the default midi input device to use.
  30630. This refers to the index in the list returned by getDevices().
  30631. */
  30632. static int getDefaultDeviceIndex();
  30633. /** Tries to open one of the midi input devices.
  30634. This will return a MidiInput object if it manages to open it. You can then
  30635. call start() and stop() on this device, and delete it when no longer needed.
  30636. If the device can't be opened, this will return a null pointer.
  30637. @param deviceIndex the index of a device from the list returned by getDevices()
  30638. @param callback the object that will receive the midi messages from this device.
  30639. @see MidiInputCallback, getDevices
  30640. */
  30641. static MidiInput* openDevice (int deviceIndex,
  30642. MidiInputCallback* callback);
  30643. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  30644. /** This will try to create a new midi input device (Not available on Windows).
  30645. This will attempt to create a new midi input device with the specified name,
  30646. for other apps to connect to.
  30647. Returns 0 if a device can't be created.
  30648. @param deviceName the name to use for the new device
  30649. @param callback the object that will receive the midi messages from this device.
  30650. */
  30651. static MidiInput* createNewDevice (const String& deviceName,
  30652. MidiInputCallback* callback);
  30653. #endif
  30654. /** Destructor. */
  30655. virtual ~MidiInput();
  30656. /** Returns the name of this device.
  30657. */
  30658. virtual const String getName() const noexcept { return name; }
  30659. /** Allows you to set a custom name for the device, in case you don't like the name
  30660. it was given when created.
  30661. */
  30662. virtual void setName (const String& newName) noexcept { name = newName; }
  30663. /** Starts the device running.
  30664. After calling this, the device will start sending midi messages to the
  30665. MidiInputCallback object that was specified when the openDevice() method
  30666. was called.
  30667. @see stop
  30668. */
  30669. virtual void start();
  30670. /** Stops the device running.
  30671. @see start
  30672. */
  30673. virtual void stop();
  30674. protected:
  30675. String name;
  30676. void* internal;
  30677. explicit MidiInput (const String& name);
  30678. private:
  30679. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInput);
  30680. };
  30681. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  30682. /*** End of inlined file: juce_MidiInput.h ***/
  30683. /*** Start of inlined file: juce_MidiOutput.h ***/
  30684. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  30685. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  30686. /*** Start of inlined file: juce_MidiBuffer.h ***/
  30687. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  30688. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  30689. /**
  30690. Holds a sequence of time-stamped midi events.
  30691. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  30692. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  30693. @see MidiMessage
  30694. */
  30695. class JUCE_API MidiBuffer
  30696. {
  30697. public:
  30698. /** Creates an empty MidiBuffer. */
  30699. MidiBuffer() noexcept;
  30700. /** Creates a MidiBuffer containing a single midi message. */
  30701. explicit MidiBuffer (const MidiMessage& message) noexcept;
  30702. /** Creates a copy of another MidiBuffer. */
  30703. MidiBuffer (const MidiBuffer& other) noexcept;
  30704. /** Makes a copy of another MidiBuffer. */
  30705. MidiBuffer& operator= (const MidiBuffer& other) noexcept;
  30706. /** Destructor */
  30707. ~MidiBuffer();
  30708. /** Removes all events from the buffer. */
  30709. void clear() noexcept;
  30710. /** Removes all events between two times from the buffer.
  30711. All events for which (start <= event position < start + numSamples) will
  30712. be removed.
  30713. */
  30714. void clear (int start, int numSamples);
  30715. /** Returns true if the buffer is empty.
  30716. To actually retrieve the events, use a MidiBuffer::Iterator object
  30717. */
  30718. bool isEmpty() const noexcept;
  30719. /** Counts the number of events in the buffer.
  30720. This is actually quite a slow operation, as it has to iterate through all
  30721. the events, so you might prefer to call isEmpty() if that's all you need
  30722. to know.
  30723. */
  30724. int getNumEvents() const noexcept;
  30725. /** Adds an event to the buffer.
  30726. The sample number will be used to determine the position of the event in
  30727. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  30728. ignored.
  30729. If an event is added whose sample position is the same as one or more events
  30730. already in the buffer, the new event will be placed after the existing ones.
  30731. To retrieve events, use a MidiBuffer::Iterator object
  30732. */
  30733. void addEvent (const MidiMessage& midiMessage, int sampleNumber);
  30734. /** Adds an event to the buffer from raw midi data.
  30735. The sample number will be used to determine the position of the event in
  30736. the buffer, which is always kept sorted.
  30737. If an event is added whose sample position is the same as one or more events
  30738. already in the buffer, the new event will be placed after the existing ones.
  30739. The event data will be inspected to calculate the number of bytes in length that
  30740. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  30741. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  30742. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  30743. add an event at all.
  30744. To retrieve events, use a MidiBuffer::Iterator object
  30745. */
  30746. void addEvent (const void* rawMidiData,
  30747. int maxBytesOfMidiData,
  30748. int sampleNumber);
  30749. /** Adds some events from another buffer to this one.
  30750. @param otherBuffer the buffer containing the events you want to add
  30751. @param startSample the lowest sample number in the source buffer for which
  30752. events should be added. Any source events whose timestamp is
  30753. less than this will be ignored
  30754. @param numSamples the valid range of samples from the source buffer for which
  30755. events should be added - i.e. events in the source buffer whose
  30756. timestamp is greater than or equal to (startSample + numSamples)
  30757. will be ignored. If this value is less than 0, all events after
  30758. startSample will be taken.
  30759. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  30760. that are added to this buffer
  30761. */
  30762. void addEvents (const MidiBuffer& otherBuffer,
  30763. int startSample,
  30764. int numSamples,
  30765. int sampleDeltaToAdd);
  30766. /** Returns the sample number of the first event in the buffer.
  30767. If the buffer's empty, this will just return 0.
  30768. */
  30769. int getFirstEventTime() const noexcept;
  30770. /** Returns the sample number of the last event in the buffer.
  30771. If the buffer's empty, this will just return 0.
  30772. */
  30773. int getLastEventTime() const noexcept;
  30774. /** Exchanges the contents of this buffer with another one.
  30775. This is a quick operation, because no memory allocating or copying is done, it
  30776. just swaps the internal state of the two buffers.
  30777. */
  30778. void swapWith (MidiBuffer& other) noexcept;
  30779. /** Preallocates some memory for the buffer to use.
  30780. This helps to avoid needing to reallocate space when the buffer has messages
  30781. added to it.
  30782. */
  30783. void ensureSize (size_t minimumNumBytes);
  30784. /**
  30785. Used to iterate through the events in a MidiBuffer.
  30786. Note that altering the buffer while an iterator is using it isn't a
  30787. safe operation.
  30788. @see MidiBuffer
  30789. */
  30790. class JUCE_API Iterator
  30791. {
  30792. public:
  30793. /** Creates an Iterator for this MidiBuffer. */
  30794. Iterator (const MidiBuffer& buffer) noexcept;
  30795. /** Destructor. */
  30796. ~Iterator() noexcept;
  30797. /** Repositions the iterator so that the next event retrieved will be the first
  30798. one whose sample position is at greater than or equal to the given position.
  30799. */
  30800. void setNextSamplePosition (int samplePosition) noexcept;
  30801. /** Retrieves a copy of the next event from the buffer.
  30802. @param result on return, this will be the message (the MidiMessage's timestamp
  30803. is not set)
  30804. @param samplePosition on return, this will be the position of the event
  30805. @returns true if an event was found, or false if the iterator has reached
  30806. the end of the buffer
  30807. */
  30808. bool getNextEvent (MidiMessage& result,
  30809. int& samplePosition) noexcept;
  30810. /** Retrieves the next event from the buffer.
  30811. @param midiData on return, this pointer will be set to a block of data containing
  30812. the midi message. Note that to make it fast, this is a pointer
  30813. directly into the MidiBuffer's internal data, so is only valid
  30814. temporarily until the MidiBuffer is altered.
  30815. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  30816. midi message
  30817. @param samplePosition on return, this will be the position of the event
  30818. @returns true if an event was found, or false if the iterator has reached
  30819. the end of the buffer
  30820. */
  30821. bool getNextEvent (const uint8* &midiData,
  30822. int& numBytesOfMidiData,
  30823. int& samplePosition) noexcept;
  30824. private:
  30825. const MidiBuffer& buffer;
  30826. const uint8* data;
  30827. JUCE_DECLARE_NON_COPYABLE (Iterator);
  30828. };
  30829. private:
  30830. friend class MidiBuffer::Iterator;
  30831. MemoryBlock data;
  30832. int bytesUsed;
  30833. uint8* getData() const noexcept;
  30834. uint8* findEventAfter (uint8* d, int samplePosition) const noexcept;
  30835. static int getEventTime (const void* d) noexcept;
  30836. static uint16 getEventDataSize (const void* d) noexcept;
  30837. static uint16 getEventTotalSize (const void* d) noexcept;
  30838. JUCE_LEAK_DETECTOR (MidiBuffer);
  30839. };
  30840. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  30841. /*** End of inlined file: juce_MidiBuffer.h ***/
  30842. /**
  30843. Controls a physical MIDI output device.
  30844. To create one of these, use the static getDevices() method to get a list of the
  30845. available output devices, then use the openDevice() method to try to open one.
  30846. @see MidiInput
  30847. */
  30848. class JUCE_API MidiOutput : private Thread
  30849. {
  30850. public:
  30851. /** Returns a list of the available midi output devices.
  30852. You can open one of the devices by passing its index into the
  30853. openDevice() method.
  30854. @see getDefaultDeviceIndex, openDevice
  30855. */
  30856. static const StringArray getDevices();
  30857. /** Returns the index of the default midi output device to use.
  30858. This refers to the index in the list returned by getDevices().
  30859. */
  30860. static int getDefaultDeviceIndex();
  30861. /** Tries to open one of the midi output devices.
  30862. This will return a MidiOutput object if it manages to open it. You can then
  30863. send messages to this device, and delete it when no longer needed.
  30864. If the device can't be opened, this will return a null pointer.
  30865. @param deviceIndex the index of a device from the list returned by getDevices()
  30866. @see getDevices
  30867. */
  30868. static MidiOutput* openDevice (int deviceIndex);
  30869. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  30870. /** This will try to create a new midi output device (Not available on Windows).
  30871. This will attempt to create a new midi output device that other apps can connect
  30872. to and use as their midi input.
  30873. Returns 0 if a device can't be created.
  30874. @param deviceName the name to use for the new device
  30875. */
  30876. static MidiOutput* createNewDevice (const String& deviceName);
  30877. #endif
  30878. /** Destructor. */
  30879. virtual ~MidiOutput();
  30880. /** Makes this device output a midi message.
  30881. @see MidiMessage
  30882. */
  30883. virtual void sendMessageNow (const MidiMessage& message);
  30884. /** Sends a midi reset to the device. */
  30885. virtual void reset();
  30886. /** Returns the current volume setting for this device. */
  30887. virtual bool getVolume (float& leftVol,
  30888. float& rightVol);
  30889. /** Changes the overall volume for this device. */
  30890. virtual void setVolume (float leftVol,
  30891. float rightVol);
  30892. /** This lets you supply a block of messages that will be sent out at some point
  30893. in the future.
  30894. The MidiOutput class has an internal thread that can send out timestamped
  30895. messages - this appends a set of messages to its internal buffer, ready for
  30896. sending.
  30897. This will only work if you've already started the thread with startBackgroundThread().
  30898. A time is supplied, at which the block of messages should be sent. This time uses
  30899. the same time base as Time::getMillisecondCounter(), and must be in the future.
  30900. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  30901. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  30902. samplesPerSecondForBuffer value is needed to convert this sample position to a
  30903. real time.
  30904. */
  30905. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  30906. double millisecondCounterToStartAt,
  30907. double samplesPerSecondForBuffer);
  30908. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  30909. */
  30910. virtual void clearAllPendingMessages();
  30911. /** Starts up a background thread so that the device can send blocks of data.
  30912. Call this to get the device ready, before using sendBlockOfMessages().
  30913. */
  30914. virtual void startBackgroundThread();
  30915. /** Stops the background thread, and clears any pending midi events.
  30916. @see startBackgroundThread
  30917. */
  30918. virtual void stopBackgroundThread();
  30919. protected:
  30920. void* internal;
  30921. struct PendingMessage
  30922. {
  30923. PendingMessage (const void* data, int len, double timeStamp);
  30924. MidiMessage message;
  30925. PendingMessage* next;
  30926. };
  30927. CriticalSection lock;
  30928. PendingMessage* firstMessage;
  30929. MidiOutput();
  30930. void run();
  30931. private:
  30932. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutput);
  30933. };
  30934. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  30935. /*** End of inlined file: juce_MidiOutput.h ***/
  30936. /*** Start of inlined file: juce_ComboBox.h ***/
  30937. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  30938. #define __JUCE_COMBOBOX_JUCEHEADER__
  30939. /*** Start of inlined file: juce_Label.h ***/
  30940. #ifndef __JUCE_LABEL_JUCEHEADER__
  30941. #define __JUCE_LABEL_JUCEHEADER__
  30942. /*** Start of inlined file: juce_TextEditor.h ***/
  30943. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  30944. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  30945. /*** Start of inlined file: juce_Viewport.h ***/
  30946. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  30947. #define __JUCE_VIEWPORT_JUCEHEADER__
  30948. /*** Start of inlined file: juce_ScrollBar.h ***/
  30949. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  30950. #define __JUCE_SCROLLBAR_JUCEHEADER__
  30951. /*** Start of inlined file: juce_Button.h ***/
  30952. #ifndef __JUCE_BUTTON_JUCEHEADER__
  30953. #define __JUCE_BUTTON_JUCEHEADER__
  30954. /*** Start of inlined file: juce_TooltipWindow.h ***/
  30955. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  30956. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  30957. /*** Start of inlined file: juce_TooltipClient.h ***/
  30958. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30959. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30960. /**
  30961. Components that want to use pop-up tooltips should implement this interface.
  30962. A TooltipWindow will wait for the mouse to hover over a component that
  30963. implements the TooltipClient interface, and when it finds one, it will display
  30964. the tooltip returned by its getTooltip() method.
  30965. @see TooltipWindow, SettableTooltipClient
  30966. */
  30967. class JUCE_API TooltipClient
  30968. {
  30969. public:
  30970. /** Destructor. */
  30971. virtual ~TooltipClient() {}
  30972. /** Returns the string that this object wants to show as its tooltip. */
  30973. virtual const String getTooltip() = 0;
  30974. };
  30975. /**
  30976. An implementation of TooltipClient that stores the tooltip string and a method
  30977. for changing it.
  30978. This makes it easy to add a tooltip to a custom component, by simply adding this
  30979. as a base class and calling setTooltip().
  30980. Many of the Juce widgets already use this as a base class to implement their
  30981. tooltips.
  30982. @see TooltipClient, TooltipWindow
  30983. */
  30984. class JUCE_API SettableTooltipClient : public TooltipClient
  30985. {
  30986. public:
  30987. /** Destructor. */
  30988. virtual ~SettableTooltipClient() {}
  30989. /** Assigns a new tooltip to this object. */
  30990. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  30991. /** Returns the tooltip assigned to this object. */
  30992. virtual const String getTooltip() { return tooltipString; }
  30993. protected:
  30994. SettableTooltipClient() {}
  30995. private:
  30996. String tooltipString;
  30997. };
  30998. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30999. /*** End of inlined file: juce_TooltipClient.h ***/
  31000. /**
  31001. A window that displays a pop-up tooltip when the mouse hovers over another component.
  31002. To enable tooltips in your app, just create a single instance of a TooltipWindow
  31003. object.
  31004. The TooltipWindow object will then stay invisible, waiting until the mouse
  31005. hovers for the specified length of time - it will then see if it's currently
  31006. over a component which implements the TooltipClient interface, and if so,
  31007. it will make itself visible to show the tooltip in the appropriate place.
  31008. @see TooltipClient, SettableTooltipClient
  31009. */
  31010. class JUCE_API TooltipWindow : public Component,
  31011. private Timer
  31012. {
  31013. public:
  31014. /** Creates a tooltip window.
  31015. Make sure your app only creates one instance of this class, otherwise you'll
  31016. get multiple overlaid tooltips appearing. The window will initially be invisible
  31017. and will make itself visible when it needs to display a tip.
  31018. To change the style of tooltips, see the LookAndFeel class for its tooltip
  31019. methods.
  31020. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  31021. otherwise the tooltip will be added to the given parent
  31022. component.
  31023. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  31024. before a tooltip will be shown
  31025. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  31026. */
  31027. explicit TooltipWindow (Component* parentComponent = nullptr,
  31028. int millisecondsBeforeTipAppears = 700);
  31029. /** Destructor. */
  31030. ~TooltipWindow();
  31031. /** Changes the time before the tip appears.
  31032. This lets you change the value that was set in the constructor.
  31033. */
  31034. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) noexcept;
  31035. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  31036. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31037. methods.
  31038. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31039. */
  31040. enum ColourIds
  31041. {
  31042. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  31043. textColourId = 0x1001c00, /**< The colour to use for the text. */
  31044. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  31045. };
  31046. private:
  31047. int millisecondsBeforeTipAppears;
  31048. Point<int> lastMousePos;
  31049. int mouseClicks;
  31050. unsigned int lastCompChangeTime, lastHideTime;
  31051. Component* lastComponentUnderMouse;
  31052. bool changedCompsSinceShown;
  31053. String tipShowing, lastTipUnderMouse;
  31054. void paint (Graphics& g);
  31055. void mouseEnter (const MouseEvent& e);
  31056. void timerCallback();
  31057. static const String getTipFor (Component* c);
  31058. void showFor (const String& tip);
  31059. void hide();
  31060. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TooltipWindow);
  31061. };
  31062. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  31063. /*** End of inlined file: juce_TooltipWindow.h ***/
  31064. #if JUCE_VC6
  31065. #define Listener ButtonListener
  31066. #endif
  31067. /**
  31068. A base class for buttons.
  31069. This contains all the logic for button behaviours such as enabling/disabling,
  31070. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  31071. and radio groups, etc.
  31072. @see TextButton, DrawableButton, ToggleButton
  31073. */
  31074. class JUCE_API Button : public Component,
  31075. public SettableTooltipClient,
  31076. public ApplicationCommandManagerListener,
  31077. public ValueListener,
  31078. private KeyListener
  31079. {
  31080. protected:
  31081. /** Creates a button.
  31082. @param buttonName the text to put in the button (the component's name is also
  31083. initially set to this string, but these can be changed later
  31084. using the setName() and setButtonText() methods)
  31085. */
  31086. explicit Button (const String& buttonName);
  31087. public:
  31088. /** Destructor. */
  31089. virtual ~Button();
  31090. /** Changes the button's text.
  31091. @see getButtonText
  31092. */
  31093. void setButtonText (const String& newText);
  31094. /** Returns the text displayed in the button.
  31095. @see setButtonText
  31096. */
  31097. const String getButtonText() const { return text; }
  31098. /** Returns true if the button is currently being held down by the mouse.
  31099. @see isOver
  31100. */
  31101. bool isDown() const noexcept;
  31102. /** Returns true if the mouse is currently over the button.
  31103. This will be also be true if the mouse is being held down.
  31104. @see isDown
  31105. */
  31106. bool isOver() const noexcept;
  31107. /** A button has an on/off state associated with it, and this changes that.
  31108. By default buttons are 'off' and for simple buttons that you click to perform
  31109. an action you won't change this. Toggle buttons, however will want to
  31110. change their state when turned on or off.
  31111. @param shouldBeOn whether to set the button's toggle state to be on or
  31112. off. If it's a member of a button group, this will
  31113. always try to turn it on, and to turn off any other
  31114. buttons in the group
  31115. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  31116. the button will be repainted but no notification will
  31117. be sent
  31118. @see getToggleState, setRadioGroupId
  31119. */
  31120. void setToggleState (bool shouldBeOn,
  31121. bool sendChangeNotification);
  31122. /** Returns true if the button in 'on'.
  31123. By default buttons are 'off' and for simple buttons that you click to perform
  31124. an action you won't change this. Toggle buttons, however will want to
  31125. change their state when turned on or off.
  31126. @see setToggleState
  31127. */
  31128. bool getToggleState() const noexcept { return isOn.getValue(); }
  31129. /** Returns the Value object that represents the botton's toggle state.
  31130. You can use this Value object to connect the button's state to external values or setters,
  31131. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  31132. your own Value object.
  31133. @see getToggleState, Value
  31134. */
  31135. Value& getToggleStateValue() { return isOn; }
  31136. /** This tells the button to automatically flip the toggle state when
  31137. the button is clicked.
  31138. If set to true, then before the clicked() callback occurs, the toggle-state
  31139. of the button is flipped.
  31140. */
  31141. void setClickingTogglesState (bool shouldToggle) noexcept;
  31142. /** Returns true if this button is set to be an automatic toggle-button.
  31143. This returns the last value that was passed to setClickingTogglesState().
  31144. */
  31145. bool getClickingTogglesState() const noexcept;
  31146. /** Enables the button to act as a member of a mutually-exclusive group
  31147. of 'radio buttons'.
  31148. If the group ID is set to a non-zero number, then this button will
  31149. act as part of a group of buttons with the same ID, only one of
  31150. which can be 'on' at the same time. Note that when it's part of
  31151. a group, clicking a toggle-button that's 'on' won't turn it off.
  31152. To find other buttons with the same ID, this button will search through
  31153. its sibling components for ToggleButtons, so all the buttons for a
  31154. particular group must be placed inside the same parent component.
  31155. Set the group ID back to zero if you want it to act as a normal toggle
  31156. button again.
  31157. @see getRadioGroupId
  31158. */
  31159. void setRadioGroupId (int newGroupId);
  31160. /** Returns the ID of the group to which this button belongs.
  31161. (See setRadioGroupId() for an explanation of this).
  31162. */
  31163. int getRadioGroupId() const noexcept { return radioGroupId; }
  31164. /**
  31165. Used to receive callbacks when a button is clicked.
  31166. @see Button::addListener, Button::removeListener
  31167. */
  31168. class JUCE_API Listener
  31169. {
  31170. public:
  31171. /** Destructor. */
  31172. virtual ~Listener() {}
  31173. /** Called when the button is clicked. */
  31174. virtual void buttonClicked (Button* button) = 0;
  31175. /** Called when the button's state changes. */
  31176. virtual void buttonStateChanged (Button*) {}
  31177. };
  31178. /** Registers a listener to receive events when this button's state changes.
  31179. If the listener is already registered, this will not register it again.
  31180. @see removeListener
  31181. */
  31182. void addListener (Listener* newListener);
  31183. /** Removes a previously-registered button listener
  31184. @see addListener
  31185. */
  31186. void removeListener (Listener* listener);
  31187. /** Causes the button to act as if it's been clicked.
  31188. This will asynchronously make the button draw itself going down and up, and
  31189. will then call back the clicked() method as if mouse was clicked on it.
  31190. @see clicked
  31191. */
  31192. virtual void triggerClick();
  31193. /** Sets a command ID for this button to automatically invoke when it's clicked.
  31194. When the button is pressed, it will use the given manager to trigger the
  31195. command ID.
  31196. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  31197. before this button is. To disable the command triggering, call this method and
  31198. pass 0 for the parameters.
  31199. If generateTooltip is true, then the button's tooltip will be automatically
  31200. generated based on the name of this command and its current shortcut key.
  31201. @see addShortcut, getCommandID
  31202. */
  31203. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  31204. int commandID,
  31205. bool generateTooltip);
  31206. /** Returns the command ID that was set by setCommandToTrigger().
  31207. */
  31208. int getCommandID() const noexcept { return commandID; }
  31209. /** Assigns a shortcut key to trigger the button.
  31210. The button registers itself with its top-level parent component for keypresses.
  31211. Note that a different way of linking buttons to keypresses is by using the
  31212. setCommandToTrigger() method to invoke a command.
  31213. @see clearShortcuts
  31214. */
  31215. void addShortcut (const KeyPress& key);
  31216. /** Removes all key shortcuts that had been set for this button.
  31217. @see addShortcut
  31218. */
  31219. void clearShortcuts();
  31220. /** Returns true if the given keypress is a shortcut for this button.
  31221. @see addShortcut
  31222. */
  31223. bool isRegisteredForShortcut (const KeyPress& key) const;
  31224. /** Sets an auto-repeat speed for the button when it is held down.
  31225. (Auto-repeat is disabled by default).
  31226. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  31227. triggering the next click. If this is zero, auto-repeat
  31228. is disabled
  31229. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  31230. triggered
  31231. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  31232. get faster, the longer the button is held down, up to the
  31233. minimum interval specified here
  31234. */
  31235. void setRepeatSpeed (int initialDelayInMillisecs,
  31236. int repeatDelayInMillisecs,
  31237. int minimumDelayInMillisecs = -1) noexcept;
  31238. /** Sets whether the button click should happen when the mouse is pressed or released.
  31239. By default the button is only considered to have been clicked when the mouse is
  31240. released, but setting this to true will make it call the clicked() method as soon
  31241. as the button is pressed.
  31242. This is useful if the button is being used to show a pop-up menu, as it allows
  31243. the click to be used as a drag onto the menu.
  31244. */
  31245. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) noexcept;
  31246. /** Returns the number of milliseconds since the last time the button
  31247. went into the 'down' state.
  31248. */
  31249. uint32 getMillisecondsSinceButtonDown() const noexcept;
  31250. /** Sets the tooltip for this button.
  31251. @see TooltipClient, TooltipWindow
  31252. */
  31253. void setTooltip (const String& newTooltip);
  31254. // (implementation of the TooltipClient method)
  31255. const String getTooltip();
  31256. /** A combination of these flags are used by setConnectedEdges().
  31257. */
  31258. enum ConnectedEdgeFlags
  31259. {
  31260. ConnectedOnLeft = 1,
  31261. ConnectedOnRight = 2,
  31262. ConnectedOnTop = 4,
  31263. ConnectedOnBottom = 8
  31264. };
  31265. /** Hints about which edges of the button might be connected to adjoining buttons.
  31266. The value passed in is a bitwise combination of any of the values in the
  31267. ConnectedEdgeFlags enum.
  31268. E.g. if you are placing two buttons adjacent to each other, you could use this to
  31269. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  31270. without rounded corners on the edges that connect. It's only a hint, so the
  31271. LookAndFeel can choose to ignore it if it's not relevent for this type of
  31272. button.
  31273. */
  31274. void setConnectedEdges (int connectedEdgeFlags);
  31275. /** Returns the set of flags passed into setConnectedEdges(). */
  31276. int getConnectedEdgeFlags() const noexcept { return connectedEdgeFlags; }
  31277. /** Indicates whether the button adjoins another one on its left edge.
  31278. @see setConnectedEdges
  31279. */
  31280. bool isConnectedOnLeft() const noexcept { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  31281. /** Indicates whether the button adjoins another one on its right edge.
  31282. @see setConnectedEdges
  31283. */
  31284. bool isConnectedOnRight() const noexcept { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  31285. /** Indicates whether the button adjoins another one on its top edge.
  31286. @see setConnectedEdges
  31287. */
  31288. bool isConnectedOnTop() const noexcept { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  31289. /** Indicates whether the button adjoins another one on its bottom edge.
  31290. @see setConnectedEdges
  31291. */
  31292. bool isConnectedOnBottom() const noexcept { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  31293. /** Used by setState(). */
  31294. enum ButtonState
  31295. {
  31296. buttonNormal,
  31297. buttonOver,
  31298. buttonDown
  31299. };
  31300. /** Can be used to force the button into a particular state.
  31301. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  31302. from happening.
  31303. The state that you set here will only last until it is automatically changed when the mouse
  31304. enters or exits the button, or the mouse-button is pressed or released.
  31305. */
  31306. void setState (const ButtonState newState);
  31307. // These are deprecated - please use addListener() and removeListener() instead!
  31308. JUCE_DEPRECATED (void addButtonListener (Listener*));
  31309. JUCE_DEPRECATED (void removeButtonListener (Listener*));
  31310. protected:
  31311. /** This method is called when the button has been clicked.
  31312. Subclasses can override this to perform whatever they actions they need
  31313. to do.
  31314. Alternatively, a ButtonListener can be added to the button, and these listeners
  31315. will be called when the click occurs.
  31316. @see triggerClick
  31317. */
  31318. virtual void clicked();
  31319. /** This method is called when the button has been clicked.
  31320. By default it just calls clicked(), but you might want to override it to handle
  31321. things like clicking when a modifier key is pressed, etc.
  31322. @see ModifierKeys
  31323. */
  31324. virtual void clicked (const ModifierKeys& modifiers);
  31325. /** Subclasses should override this to actually paint the button's contents.
  31326. It's better to use this than the paint method, because it gives you information
  31327. about the over/down state of the button.
  31328. @param g the graphics context to use
  31329. @param isMouseOverButton true if the button is either in the 'over' or
  31330. 'down' state
  31331. @param isButtonDown true if the button should be drawn in the 'down' position
  31332. */
  31333. virtual void paintButton (Graphics& g,
  31334. bool isMouseOverButton,
  31335. bool isButtonDown) = 0;
  31336. /** Called when the button's up/down/over state changes.
  31337. Subclasses can override this if they need to do something special when the button
  31338. goes up or down.
  31339. @see isDown, isOver
  31340. */
  31341. virtual void buttonStateChanged();
  31342. /** @internal */
  31343. virtual void internalClickCallback (const ModifierKeys& modifiers);
  31344. /** @internal */
  31345. void handleCommandMessage (int commandId);
  31346. /** @internal */
  31347. void mouseEnter (const MouseEvent& e);
  31348. /** @internal */
  31349. void mouseExit (const MouseEvent& e);
  31350. /** @internal */
  31351. void mouseDown (const MouseEvent& e);
  31352. /** @internal */
  31353. void mouseDrag (const MouseEvent& e);
  31354. /** @internal */
  31355. void mouseUp (const MouseEvent& e);
  31356. /** @internal */
  31357. bool keyPressed (const KeyPress& key);
  31358. /** @internal */
  31359. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  31360. /** @internal */
  31361. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  31362. /** @internal */
  31363. void paint (Graphics& g);
  31364. /** @internal */
  31365. void parentHierarchyChanged();
  31366. /** @internal */
  31367. void visibilityChanged();
  31368. /** @internal */
  31369. void focusGained (FocusChangeType cause);
  31370. /** @internal */
  31371. void focusLost (FocusChangeType cause);
  31372. /** @internal */
  31373. void enablementChanged();
  31374. /** @internal */
  31375. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  31376. /** @internal */
  31377. void applicationCommandListChanged();
  31378. /** @internal */
  31379. void valueChanged (Value& value);
  31380. private:
  31381. Array <KeyPress> shortcuts;
  31382. WeakReference<Component> keySource;
  31383. String text;
  31384. ListenerList <Listener> buttonListeners;
  31385. class RepeatTimer;
  31386. friend class RepeatTimer;
  31387. friend class ScopedPointer <RepeatTimer>;
  31388. ScopedPointer <RepeatTimer> repeatTimer;
  31389. uint32 buttonPressTime, lastRepeatTime;
  31390. ApplicationCommandManager* commandManagerToUse;
  31391. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  31392. int radioGroupId, commandID, connectedEdgeFlags;
  31393. ButtonState buttonState;
  31394. Value isOn;
  31395. bool lastToggleState : 1;
  31396. bool clickTogglesState : 1;
  31397. bool needsToRelease : 1;
  31398. bool needsRepainting : 1;
  31399. bool isKeyDown : 1;
  31400. bool triggerOnMouseDown : 1;
  31401. bool generateTooltip : 1;
  31402. void repeatTimerCallback();
  31403. RepeatTimer& getRepeatTimer();
  31404. ButtonState updateState();
  31405. ButtonState updateState (bool isOver, bool isDown);
  31406. bool isShortcutPressed() const;
  31407. void turnOffOtherButtonsInGroup (bool sendChangeNotification);
  31408. void flashButtonState();
  31409. void sendClickMessage (const ModifierKeys& modifiers);
  31410. void sendStateMessage();
  31411. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Button);
  31412. };
  31413. #ifndef DOXYGEN
  31414. /** This typedef is just for compatibility with old code and VC6 - newer code should use Button::Listener instead. */
  31415. typedef Button::Listener ButtonListener;
  31416. #endif
  31417. #if JUCE_VC6
  31418. #undef Listener
  31419. #endif
  31420. #endif // __JUCE_BUTTON_JUCEHEADER__
  31421. /*** End of inlined file: juce_Button.h ***/
  31422. /**
  31423. A scrollbar component.
  31424. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  31425. sets the range of values it can represent. Then you can use setCurrentRange() to
  31426. change the position and size of the scrollbar's 'thumb'.
  31427. Registering a ScrollBar::Listener with the scrollbar will allow you to find out when
  31428. the user moves it, and you can use the getCurrentRangeStart() to find out where
  31429. they moved it to.
  31430. The scrollbar will adjust its own visibility according to whether its thumb size
  31431. allows it to actually be scrolled.
  31432. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  31433. instead of handling a scrollbar directly.
  31434. @see ScrollBar::Listener
  31435. */
  31436. class JUCE_API ScrollBar : public Component,
  31437. public AsyncUpdater,
  31438. private Timer
  31439. {
  31440. public:
  31441. /** Creates a Scrollbar.
  31442. @param isVertical whether it should be a vertical or horizontal bar
  31443. @param buttonsAreVisible whether to show the up/down or left/right buttons
  31444. */
  31445. ScrollBar (bool isVertical,
  31446. bool buttonsAreVisible = true);
  31447. /** Destructor. */
  31448. ~ScrollBar();
  31449. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  31450. bool isVertical() const noexcept { return vertical; }
  31451. /** Changes the scrollbar's direction.
  31452. You'll also need to resize the bar appropriately - this just changes its internal
  31453. layout.
  31454. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  31455. */
  31456. void setOrientation (bool shouldBeVertical);
  31457. /** Shows or hides the scrollbar's buttons. */
  31458. void setButtonVisibility (bool buttonsAreVisible);
  31459. /** Tells the scrollbar whether to make itself invisible when not needed.
  31460. The default behaviour is for a scrollbar to become invisible when the thumb
  31461. fills the whole of its range (i.e. when it can't be moved). Setting this
  31462. value to false forces the bar to always be visible.
  31463. @see autoHides()
  31464. */
  31465. void setAutoHide (bool shouldHideWhenFullRange);
  31466. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  31467. as its maximum range.
  31468. @see setAutoHide
  31469. */
  31470. bool autoHides() const noexcept;
  31471. /** Sets the minimum and maximum values that the bar will move between.
  31472. The bar's thumb will always be constrained so that the entire thumb lies
  31473. within this range.
  31474. @see setCurrentRange
  31475. */
  31476. void setRangeLimits (const Range<double>& newRangeLimit);
  31477. /** Sets the minimum and maximum values that the bar will move between.
  31478. The bar's thumb will always be constrained so that the entire thumb lies
  31479. within this range.
  31480. @see setCurrentRange
  31481. */
  31482. void setRangeLimits (double minimum, double maximum);
  31483. /** Returns the current limits on the thumb position.
  31484. @see setRangeLimits
  31485. */
  31486. const Range<double> getRangeLimit() const noexcept { return totalRange; }
  31487. /** Returns the lower value that the thumb can be set to.
  31488. This is the value set by setRangeLimits().
  31489. */
  31490. double getMinimumRangeLimit() const noexcept { return totalRange.getStart(); }
  31491. /** Returns the upper value that the thumb can be set to.
  31492. This is the value set by setRangeLimits().
  31493. */
  31494. double getMaximumRangeLimit() const noexcept { return totalRange.getEnd(); }
  31495. /** Changes the position of the scrollbar's 'thumb'.
  31496. If this method call actually changes the scrollbar's position, it will trigger an
  31497. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  31498. are registered.
  31499. @see getCurrentRange. setCurrentRangeStart
  31500. */
  31501. void setCurrentRange (const Range<double>& newRange);
  31502. /** Changes the position of the scrollbar's 'thumb'.
  31503. This sets both the position and size of the thumb - to just set the position without
  31504. changing the size, you can use setCurrentRangeStart().
  31505. If this method call actually changes the scrollbar's position, it will trigger an
  31506. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  31507. are registered.
  31508. @param newStart the top (or left) of the thumb, in the range
  31509. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  31510. value is beyond these limits, it will be clipped.
  31511. @param newSize the size of the thumb, such that
  31512. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  31513. size is beyond these limits, it will be clipped.
  31514. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  31515. */
  31516. void setCurrentRange (double newStart, double newSize);
  31517. /** Moves the bar's thumb position.
  31518. This will move the thumb position without changing the thumb size. Note
  31519. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  31520. If this method call actually changes the scrollbar's position, it will trigger an
  31521. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  31522. are registered.
  31523. @see setCurrentRange
  31524. */
  31525. void setCurrentRangeStart (double newStart);
  31526. /** Returns the current thumb range.
  31527. @see getCurrentRange, setCurrentRange
  31528. */
  31529. const Range<double> getCurrentRange() const noexcept { return visibleRange; }
  31530. /** Returns the position of the top of the thumb.
  31531. @see getCurrentRange, setCurrentRangeStart
  31532. */
  31533. double getCurrentRangeStart() const noexcept { return visibleRange.getStart(); }
  31534. /** Returns the current size of the thumb.
  31535. @see getCurrentRange, setCurrentRange
  31536. */
  31537. double getCurrentRangeSize() const noexcept { return visibleRange.getLength(); }
  31538. /** Sets the amount by which the up and down buttons will move the bar.
  31539. The value here is in terms of the total range, and is added or subtracted
  31540. from the thumb position when the user clicks an up/down (or left/right) button.
  31541. */
  31542. void setSingleStepSize (double newSingleStepSize);
  31543. /** Moves the scrollbar by a number of single-steps.
  31544. This will move the bar by a multiple of its single-step interval (as
  31545. specified using the setSingleStepSize() method).
  31546. A positive value here will move the bar down or to the right, a negative
  31547. value moves it up or to the left.
  31548. */
  31549. void moveScrollbarInSteps (int howManySteps);
  31550. /** Moves the scroll bar up or down in pages.
  31551. This will move the bar by a multiple of its current thumb size, effectively
  31552. doing a page-up or down.
  31553. A positive value here will move the bar down or to the right, a negative
  31554. value moves it up or to the left.
  31555. */
  31556. void moveScrollbarInPages (int howManyPages);
  31557. /** Scrolls to the top (or left).
  31558. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  31559. */
  31560. void scrollToTop();
  31561. /** Scrolls to the bottom (or right).
  31562. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  31563. */
  31564. void scrollToBottom();
  31565. /** Changes the delay before the up and down buttons autorepeat when they are held
  31566. down.
  31567. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  31568. @see Button::setRepeatSpeed
  31569. */
  31570. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  31571. int repeatDelayInMillisecs,
  31572. int minimumDelayInMillisecs = -1);
  31573. /** A set of colour IDs to use to change the colour of various aspects of the component.
  31574. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31575. methods.
  31576. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31577. */
  31578. enum ColourIds
  31579. {
  31580. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  31581. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  31582. 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. */
  31583. };
  31584. /**
  31585. A class for receiving events from a ScrollBar.
  31586. You can register a ScrollBar::Listener with a ScrollBar using the ScrollBar::addListener()
  31587. method, and it will be called when the bar's position changes.
  31588. @see ScrollBar::addListener, ScrollBar::removeListener
  31589. */
  31590. class JUCE_API Listener
  31591. {
  31592. public:
  31593. /** Destructor. */
  31594. virtual ~Listener() {}
  31595. /** Called when a ScrollBar is moved.
  31596. @param scrollBarThatHasMoved the bar that has moved
  31597. @param newRangeStart the new range start of this bar
  31598. */
  31599. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  31600. double newRangeStart) = 0;
  31601. };
  31602. /** Registers a listener that will be called when the scrollbar is moved. */
  31603. void addListener (Listener* listener);
  31604. /** Deregisters a previously-registered listener. */
  31605. void removeListener (Listener* listener);
  31606. /** @internal */
  31607. bool keyPressed (const KeyPress& key);
  31608. /** @internal */
  31609. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31610. /** @internal */
  31611. void lookAndFeelChanged();
  31612. /** @internal */
  31613. void handleAsyncUpdate();
  31614. /** @internal */
  31615. void mouseDown (const MouseEvent& e);
  31616. /** @internal */
  31617. void mouseDrag (const MouseEvent& e);
  31618. /** @internal */
  31619. void mouseUp (const MouseEvent& e);
  31620. /** @internal */
  31621. void paint (Graphics& g);
  31622. /** @internal */
  31623. void resized();
  31624. private:
  31625. Range <double> totalRange, visibleRange;
  31626. double singleStepSize, dragStartRange;
  31627. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  31628. int dragStartMousePos, lastMousePos;
  31629. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  31630. bool vertical, isDraggingThumb, autohides;
  31631. class ScrollbarButton;
  31632. friend class ScopedPointer<ScrollbarButton>;
  31633. ScopedPointer<ScrollbarButton> upButton, downButton;
  31634. ListenerList <Listener> listeners;
  31635. void updateThumbPosition();
  31636. void timerCallback();
  31637. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollBar);
  31638. };
  31639. /** This typedef is just for compatibility with old code - newer code should use the ScrollBar::Listener class directly. */
  31640. typedef ScrollBar::Listener ScrollBarListener;
  31641. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  31642. /*** End of inlined file: juce_ScrollBar.h ***/
  31643. /**
  31644. A Viewport is used to contain a larger child component, and allows the child
  31645. to be automatically scrolled around.
  31646. To use a Viewport, just create one and set the component that goes inside it
  31647. using the setViewedComponent() method. When the child component changes size,
  31648. the Viewport will adjust its scrollbars accordingly.
  31649. A subclass of the viewport can be created which will receive calls to its
  31650. visibleAreaChanged() method when the subcomponent changes position or size.
  31651. */
  31652. class JUCE_API Viewport : public Component,
  31653. private ComponentListener,
  31654. private ScrollBar::Listener
  31655. {
  31656. public:
  31657. /** Creates a Viewport.
  31658. The viewport is initially empty - use the setViewedComponent() method to
  31659. add a child component for it to manage.
  31660. */
  31661. explicit Viewport (const String& componentName = String::empty);
  31662. /** Destructor. */
  31663. ~Viewport();
  31664. /** Sets the component that this viewport will contain and scroll around.
  31665. This will add the given component to this Viewport and position it at (0, 0).
  31666. (Don't add or remove any child components directly using the normal
  31667. Component::addChildComponent() methods).
  31668. @param newViewedComponent the component to add to this viewport, or null to remove
  31669. the current component.
  31670. @param deleteComponentWhenNoLongerNeeded if true, the component will be deleted
  31671. automatically when the viewport is deleted or when a different
  31672. component is added. If false, the caller must manage the lifetime
  31673. of the component
  31674. @see getViewedComponent
  31675. */
  31676. void setViewedComponent (Component* newViewedComponent,
  31677. bool deleteComponentWhenNoLongerNeeded = true);
  31678. /** Returns the component that's currently being used inside the Viewport.
  31679. @see setViewedComponent
  31680. */
  31681. Component* getViewedComponent() const noexcept { return contentComp; }
  31682. /** Changes the position of the viewed component.
  31683. The inner component will be moved so that the pixel at the top left of
  31684. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  31685. within the inner component.
  31686. This will update the scrollbars and might cause a call to visibleAreaChanged().
  31687. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  31688. */
  31689. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  31690. /** Changes the position of the viewed component.
  31691. The inner component will be moved so that the pixel at the top left of
  31692. the viewport will be the pixel at the specified coordinates within the
  31693. inner component.
  31694. This will update the scrollbars and might cause a call to visibleAreaChanged().
  31695. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  31696. */
  31697. void setViewPosition (const Point<int>& newPosition);
  31698. /** Changes the view position as a proportion of the distance it can move.
  31699. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  31700. visible area in the top-left, and (1, 1) would put it as far down and
  31701. to the right as it's possible to go whilst keeping the child component
  31702. on-screen.
  31703. */
  31704. void setViewPositionProportionately (double proportionX, double proportionY);
  31705. /** If the specified position is at the edges of the viewport, this method scrolls
  31706. the viewport to bring that position nearer to the centre.
  31707. Call this if you're dragging an object inside a viewport and want to make it scroll
  31708. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  31709. useful when auto-scrolling.
  31710. @param mouseX the x position, relative to the Viewport's top-left
  31711. @param mouseY the y position, relative to the Viewport's top-left
  31712. @param distanceFromEdge specifies how close to an edge the position needs to be
  31713. before the viewport should scroll in that direction
  31714. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  31715. to scroll by.
  31716. @returns true if the viewport was scrolled
  31717. */
  31718. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  31719. /** Returns the position within the child component of the top-left of its visible area.
  31720. */
  31721. const Point<int> getViewPosition() const noexcept { return lastVisibleArea.getPosition(); }
  31722. /** Returns the position within the child component of the top-left of its visible area.
  31723. @see getViewWidth, setViewPosition
  31724. */
  31725. int getViewPositionX() const noexcept { return lastVisibleArea.getX(); }
  31726. /** Returns the position within the child component of the top-left of its visible area.
  31727. @see getViewHeight, setViewPosition
  31728. */
  31729. int getViewPositionY() const noexcept { return lastVisibleArea.getY(); }
  31730. /** Returns the width of the visible area of the child component.
  31731. This may be less than the width of this Viewport if there's a vertical scrollbar
  31732. or if the child component is itself smaller.
  31733. */
  31734. int getViewWidth() const noexcept { return lastVisibleArea.getWidth(); }
  31735. /** Returns the height of the visible area of the child component.
  31736. This may be less than the height of this Viewport if there's a horizontal scrollbar
  31737. or if the child component is itself smaller.
  31738. */
  31739. int getViewHeight() const noexcept { return lastVisibleArea.getHeight(); }
  31740. /** Returns the width available within this component for the contents.
  31741. This will be the width of the viewport component minus the width of a
  31742. vertical scrollbar (if visible).
  31743. */
  31744. int getMaximumVisibleWidth() const;
  31745. /** Returns the height available within this component for the contents.
  31746. This will be the height of the viewport component minus the space taken up
  31747. by a horizontal scrollbar (if visible).
  31748. */
  31749. int getMaximumVisibleHeight() const;
  31750. /** Callback method that is called when the visible area changes.
  31751. This will be called when the visible area is moved either be scrolling or
  31752. by calls to setViewPosition(), etc.
  31753. */
  31754. virtual void visibleAreaChanged (const Rectangle<int>& newVisibleArea);
  31755. /** Turns scrollbars on or off.
  31756. If set to false, the scrollbars won't ever appear. When true (the default)
  31757. they will appear only when needed.
  31758. */
  31759. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  31760. bool showHorizontalScrollbarIfNeeded);
  31761. /** True if the vertical scrollbar is enabled.
  31762. @see setScrollBarsShown
  31763. */
  31764. bool isVerticalScrollBarShown() const noexcept { return showVScrollbar; }
  31765. /** True if the horizontal scrollbar is enabled.
  31766. @see setScrollBarsShown
  31767. */
  31768. bool isHorizontalScrollBarShown() const noexcept { return showHScrollbar; }
  31769. /** Changes the width of the scrollbars.
  31770. If this isn't specified, the default width from the LookAndFeel class will be used.
  31771. @see LookAndFeel::getDefaultScrollbarWidth
  31772. */
  31773. void setScrollBarThickness (int thickness);
  31774. /** Returns the thickness of the scrollbars.
  31775. @see setScrollBarThickness
  31776. */
  31777. int getScrollBarThickness() const;
  31778. /** Changes the distance that a single-step click on a scrollbar button
  31779. will move the viewport.
  31780. */
  31781. void setSingleStepSizes (int stepX, int stepY);
  31782. /** Shows or hides the buttons on any scrollbars that are used.
  31783. @see ScrollBar::setButtonVisibility
  31784. */
  31785. void setScrollBarButtonVisibility (bool buttonsVisible);
  31786. /** Returns a pointer to the scrollbar component being used.
  31787. Handy if you need to customise the bar somehow.
  31788. */
  31789. ScrollBar* getVerticalScrollBar() noexcept { return &verticalScrollBar; }
  31790. /** Returns a pointer to the scrollbar component being used.
  31791. Handy if you need to customise the bar somehow.
  31792. */
  31793. ScrollBar* getHorizontalScrollBar() noexcept { return &horizontalScrollBar; }
  31794. /** @internal */
  31795. void resized();
  31796. /** @internal */
  31797. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  31798. /** @internal */
  31799. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31800. /** @internal */
  31801. bool keyPressed (const KeyPress& key);
  31802. /** @internal */
  31803. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  31804. /** @internal */
  31805. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31806. private:
  31807. WeakReference<Component> contentComp;
  31808. Rectangle<int> lastVisibleArea;
  31809. int scrollBarThickness;
  31810. int singleStepX, singleStepY;
  31811. bool showHScrollbar, showVScrollbar, deleteContent;
  31812. Component contentHolder;
  31813. ScrollBar verticalScrollBar;
  31814. ScrollBar horizontalScrollBar;
  31815. void updateVisibleArea();
  31816. void deleteContentComp();
  31817. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  31818. // If you get an error here, it's because this method's parameters have changed! See the new definition above..
  31819. virtual int visibleAreaChanged (int, int, int, int) { return 0; }
  31820. #endif
  31821. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Viewport);
  31822. };
  31823. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  31824. /*** End of inlined file: juce_Viewport.h ***/
  31825. /*** Start of inlined file: juce_PopupMenu.h ***/
  31826. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  31827. #define __JUCE_POPUPMENU_JUCEHEADER__
  31828. /** Creates and displays a popup-menu.
  31829. To show a popup-menu, you create one of these, add some items to it, then
  31830. call its show() method, which returns the id of the item the user selects.
  31831. E.g. @code
  31832. void MyWidget::mouseDown (const MouseEvent& e)
  31833. {
  31834. PopupMenu m;
  31835. m.addItem (1, "item 1");
  31836. m.addItem (2, "item 2");
  31837. const int result = m.show();
  31838. if (result == 0)
  31839. {
  31840. // user dismissed the menu without picking anything
  31841. }
  31842. else if (result == 1)
  31843. {
  31844. // user picked item 1
  31845. }
  31846. else if (result == 2)
  31847. {
  31848. // user picked item 2
  31849. }
  31850. }
  31851. @endcode
  31852. Submenus are easy too: @code
  31853. void MyWidget::mouseDown (const MouseEvent& e)
  31854. {
  31855. PopupMenu subMenu;
  31856. subMenu.addItem (1, "item 1");
  31857. subMenu.addItem (2, "item 2");
  31858. PopupMenu mainMenu;
  31859. mainMenu.addItem (3, "item 3");
  31860. mainMenu.addSubMenu ("other choices", subMenu);
  31861. const int result = m.show();
  31862. ...etc
  31863. }
  31864. @endcode
  31865. */
  31866. class JUCE_API PopupMenu
  31867. {
  31868. public:
  31869. /** Creates an empty popup menu. */
  31870. PopupMenu();
  31871. /** Creates a copy of another menu. */
  31872. PopupMenu (const PopupMenu& other);
  31873. /** Destructor. */
  31874. ~PopupMenu();
  31875. /** Copies this menu from another one. */
  31876. PopupMenu& operator= (const PopupMenu& other);
  31877. /** Resets the menu, removing all its items. */
  31878. void clear();
  31879. /** Appends a new text item for this menu to show.
  31880. @param itemResultId the number that will be returned from the show() method
  31881. if the user picks this item. The value should never be
  31882. zero, because that's used to indicate that the user didn't
  31883. select anything.
  31884. @param itemText the text to show.
  31885. @param isActive if false, the item will be shown 'greyed-out' and can't be
  31886. picked
  31887. @param isTicked if true, the item will be shown with a tick next to it
  31888. @param iconToUse if this is non-zero, it should be an image that will be
  31889. displayed to the left of the item. This method will take its
  31890. own copy of the image passed-in, so there's no need to keep
  31891. it hanging around.
  31892. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  31893. */
  31894. void addItem (int itemResultId,
  31895. const String& itemText,
  31896. bool isActive = true,
  31897. bool isTicked = false,
  31898. const Image& iconToUse = Image::null);
  31899. /** Adds an item that represents one of the commands in a command manager object.
  31900. @param commandManager the manager to use to trigger the command and get information
  31901. about it
  31902. @param commandID the ID of the command
  31903. @param displayName if this is non-empty, then this string will be used instead of
  31904. the command's registered name
  31905. */
  31906. void addCommandItem (ApplicationCommandManager* commandManager,
  31907. int commandID,
  31908. const String& displayName = String::empty);
  31909. /** Appends a text item with a special colour.
  31910. This is the same as addItem(), but specifies a colour to use for the
  31911. text, which will override the default colours that are used by the
  31912. current look-and-feel. See addItem() for a description of the parameters.
  31913. */
  31914. void addColouredItem (int itemResultId,
  31915. const String& itemText,
  31916. const Colour& itemTextColour,
  31917. bool isActive = true,
  31918. bool isTicked = false,
  31919. const Image& iconToUse = Image::null);
  31920. /** Appends a custom menu item that can't be used to trigger a result.
  31921. This will add a user-defined component to use as a menu item. Unlike the
  31922. addCustomItem() method that takes a PopupMenu::CustomComponent, this version
  31923. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  31924. delete the component when it's finished, so it's the caller's responsibility
  31925. to manage the component that is passed-in.
  31926. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  31927. detection of a mouse-click on your component, and use that to trigger the
  31928. menu ID specified in itemResultId. If this is false, the menu item can't
  31929. be triggered, so itemResultId is not used.
  31930. @see CustomComponent
  31931. */
  31932. void addCustomItem (int itemResultId,
  31933. Component* customComponent,
  31934. int idealWidth, int idealHeight,
  31935. bool triggerMenuItemAutomaticallyWhenClicked);
  31936. /** Appends a sub-menu.
  31937. If the menu that's passed in is empty, it will appear as an inactive item.
  31938. */
  31939. void addSubMenu (const String& subMenuName,
  31940. const PopupMenu& subMenu,
  31941. bool isActive = true,
  31942. const Image& iconToUse = Image::null,
  31943. bool isTicked = false);
  31944. /** Appends a separator to the menu, to help break it up into sections.
  31945. The menu class is smart enough not to display separators at the top or bottom
  31946. of the menu, and it will replace mutliple adjacent separators with a single
  31947. one, so your code can be quite free and easy about adding these, and it'll
  31948. always look ok.
  31949. */
  31950. void addSeparator();
  31951. /** Adds a non-clickable text item to the menu.
  31952. This is a bold-font items which can be used as a header to separate the items
  31953. into named groups.
  31954. */
  31955. void addSectionHeader (const String& title);
  31956. /** Returns the number of items that the menu currently contains.
  31957. (This doesn't count separators).
  31958. */
  31959. int getNumItems() const noexcept;
  31960. /** Returns true if the menu contains a command item that triggers the given command. */
  31961. bool containsCommandItem (int commandID) const;
  31962. /** Returns true if the menu contains any items that can be used. */
  31963. bool containsAnyActiveItems() const noexcept;
  31964. /** Class used to create a set of options to pass to the show() method.
  31965. You can chain together a series of calls to this class's methods to create
  31966. a set of whatever options you want to specify.
  31967. E.g. @code
  31968. PopupMenu menu;
  31969. ...
  31970. menu.showMenu (PopupMenu::Options().withMaximumWidth (100),
  31971. .withMaximumNumColumns (3)
  31972. .withTargetComponent (myComp));
  31973. @endcode
  31974. */
  31975. class JUCE_API Options
  31976. {
  31977. public:
  31978. Options();
  31979. const Options withTargetComponent (Component* targetComponent) const;
  31980. const Options withTargetScreenArea (const Rectangle<int>& targetArea) const;
  31981. const Options withMinimumWidth (int minWidth) const;
  31982. const Options withMaximumNumColumns (int maxNumColumns) const;
  31983. const Options withStandardItemHeight (int standardHeight) const;
  31984. const Options withItemThatMustBeVisible (int idOfItemToBeVisible) const;
  31985. private:
  31986. friend class PopupMenu;
  31987. Rectangle<int> targetArea;
  31988. Component* targetComponent;
  31989. int visibleItemID, minWidth, maxColumns, standardHeight;
  31990. };
  31991. #if JUCE_MODAL_LOOPS_PERMITTED
  31992. /** Displays the menu and waits for the user to pick something.
  31993. This will display the menu modally, and return the ID of the item that the
  31994. user picks. If they click somewhere off the menu to get rid of it without
  31995. choosing anything, this will return 0.
  31996. The current location of the mouse will be used as the position to show the
  31997. menu - to explicitly set the menu's position, use showAt() instead. Depending
  31998. on where this point is on the screen, the menu will appear above, below or
  31999. to the side of the point.
  32000. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  32001. then when the menu first appears, it will make sure
  32002. that this item is visible. So if the menu has too many
  32003. items to fit on the screen, it will be scrolled to a
  32004. position where this item is visible.
  32005. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  32006. than this if some items are too long to fit.
  32007. @param maximumNumColumns if there are too many items to fit on-screen in a single
  32008. vertical column, the menu may be laid out as a series of
  32009. columns - this is the maximum number allowed. To use the
  32010. default value for this (probably about 7), you can pass
  32011. in zero.
  32012. @param standardItemHeight if this is non-zero, it will be used as the standard
  32013. height for menu items (apart from custom items)
  32014. @param callback if this is non-zero, the menu will be launched asynchronously,
  32015. returning immediately, and the callback will receive a
  32016. call when the menu is either dismissed or has an item
  32017. selected. This object will be owned and deleted by the
  32018. system, so make sure that it works safely and that any
  32019. pointers that it uses are safely within scope.
  32020. @see showAt
  32021. */
  32022. int show (int itemIdThatMustBeVisible = 0,
  32023. int minimumWidth = 0,
  32024. int maximumNumColumns = 0,
  32025. int standardItemHeight = 0,
  32026. ModalComponentManager::Callback* callback = nullptr);
  32027. /** Displays the menu at a specific location.
  32028. This is the same as show(), but uses a specific location (in global screen
  32029. co-ordinates) rather than the current mouse position.
  32030. The screenAreaToAttachTo parameter indicates a screen area to which the menu
  32031. will be adjacent. Depending on where this is, the menu will decide which edge to
  32032. attach itself to, in order to fit itself fully on-screen. If you just want to
  32033. trigger a menu at a specific point, you can pass in a rectangle of size (0, 0)
  32034. with the position that you want.
  32035. @see show()
  32036. */
  32037. int showAt (const Rectangle<int>& screenAreaToAttachTo,
  32038. int itemIdThatMustBeVisible = 0,
  32039. int minimumWidth = 0,
  32040. int maximumNumColumns = 0,
  32041. int standardItemHeight = 0,
  32042. ModalComponentManager::Callback* callback = nullptr);
  32043. /** Displays the menu as if it's attached to a component such as a button.
  32044. This is similar to showAt(), but will position it next to the given component, e.g.
  32045. so that the menu's edge is aligned with that of the component. This is intended for
  32046. things like buttons that trigger a pop-up menu.
  32047. */
  32048. int showAt (Component* componentToAttachTo,
  32049. int itemIdThatMustBeVisible = 0,
  32050. int minimumWidth = 0,
  32051. int maximumNumColumns = 0,
  32052. int standardItemHeight = 0,
  32053. ModalComponentManager::Callback* callback = nullptr);
  32054. /** Displays and runs the menu modally, with a set of options.
  32055. */
  32056. int showMenu (const Options& options);
  32057. #endif
  32058. /** Runs the menu asynchronously, with a user-provided callback that will receive the result. */
  32059. void showMenuAsync (const Options& options,
  32060. ModalComponentManager::Callback* callback);
  32061. /** Closes any menus that are currently open.
  32062. This might be useful if you have a situation where your window is being closed
  32063. by some means other than a user action, and you'd like to make sure that menus
  32064. aren't left hanging around.
  32065. */
  32066. static bool JUCE_CALLTYPE dismissAllActiveMenus();
  32067. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  32068. This can be called before show() if you need a customised menu. Be careful
  32069. not to delete the LookAndFeel object before the menu has been deleted.
  32070. */
  32071. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  32072. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  32073. These constants can be used either via the LookAndFeel::setColour()
  32074. method for the look and feel that is set for this menu with setLookAndFeel()
  32075. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  32076. */
  32077. enum ColourIds
  32078. {
  32079. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  32080. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  32081. colour is specified when the item is added). */
  32082. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  32083. addSectionHeader() method). */
  32084. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  32085. highlighted menu item. */
  32086. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  32087. highlighted item. */
  32088. };
  32089. /**
  32090. Allows you to iterate through the items in a pop-up menu, and examine
  32091. their properties.
  32092. To use this, just create one and repeatedly call its next() method. When this
  32093. returns true, all the member variables of the iterator are filled-out with
  32094. information describing the menu item. When it returns false, the end of the
  32095. list has been reached.
  32096. */
  32097. class JUCE_API MenuItemIterator
  32098. {
  32099. public:
  32100. /** Creates an iterator that will scan through the items in the specified
  32101. menu.
  32102. Be careful not to add any items to a menu while it is being iterated,
  32103. or things could get out of step.
  32104. */
  32105. MenuItemIterator (const PopupMenu& menu);
  32106. /** Destructor. */
  32107. ~MenuItemIterator();
  32108. /** Returns true if there is another item, and sets up all this object's
  32109. member variables to reflect that item's properties.
  32110. */
  32111. bool next();
  32112. String itemName;
  32113. const PopupMenu* subMenu;
  32114. int itemId;
  32115. bool isSeparator;
  32116. bool isTicked;
  32117. bool isEnabled;
  32118. bool isCustomComponent;
  32119. bool isSectionHeader;
  32120. const Colour* customColour;
  32121. Image customImage;
  32122. ApplicationCommandManager* commandManager;
  32123. private:
  32124. const PopupMenu& menu;
  32125. int index;
  32126. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuItemIterator);
  32127. };
  32128. /** A user-defined copmonent that can be used as an item in a popup menu.
  32129. @see PopupMenu::addCustomItem
  32130. */
  32131. class JUCE_API CustomComponent : public Component,
  32132. public ReferenceCountedObject
  32133. {
  32134. public:
  32135. /** Creates a custom item.
  32136. If isTriggeredAutomatically is true, then the menu will automatically detect
  32137. a mouse-click on this component and use that to invoke the menu item. If it's
  32138. false, then it's up to your class to manually trigger the item when it wants to.
  32139. */
  32140. CustomComponent (bool isTriggeredAutomatically = true);
  32141. /** Destructor. */
  32142. ~CustomComponent();
  32143. /** Returns a rectangle with the size that this component would like to have.
  32144. Note that the size which this method returns isn't necessarily the one that
  32145. the menu will give it, as the items will be stretched to have a uniform width.
  32146. */
  32147. virtual void getIdealSize (int& idealWidth, int& idealHeight) = 0;
  32148. /** Dismisses the menu, indicating that this item has been chosen.
  32149. This will cause the menu to exit from its modal state, returning
  32150. this item's id as the result.
  32151. */
  32152. void triggerMenuItem();
  32153. /** Returns true if this item should be highlighted because the mouse is over it.
  32154. You can call this method in your paint() method to find out whether
  32155. to draw a highlight.
  32156. */
  32157. bool isItemHighlighted() const noexcept { return isHighlighted; }
  32158. /** @internal */
  32159. bool isTriggeredAutomatically() const noexcept { return triggeredAutomatically; }
  32160. /** @internal */
  32161. void setHighlighted (bool shouldBeHighlighted);
  32162. private:
  32163. bool isHighlighted, triggeredAutomatically;
  32164. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponent);
  32165. };
  32166. /** Appends a custom menu item.
  32167. This will add a user-defined component to use as a menu item. The component
  32168. passed in will be deleted by this menu when it's no longer needed.
  32169. @see CustomComponent
  32170. */
  32171. void addCustomItem (int itemResultId, CustomComponent* customComponent);
  32172. private:
  32173. class Item;
  32174. class ItemComponent;
  32175. class Window;
  32176. friend class MenuItemIterator;
  32177. friend class ItemComponent;
  32178. friend class Window;
  32179. friend class CustomComponent;
  32180. friend class MenuBarComponent;
  32181. friend class OwnedArray <Item>;
  32182. friend class OwnedArray <ItemComponent>;
  32183. friend class ScopedPointer <Window>;
  32184. OwnedArray <Item> items;
  32185. LookAndFeel* lookAndFeel;
  32186. bool separatorPending;
  32187. void addSeparatorIfPending();
  32188. Component* createWindow (const Options&, ApplicationCommandManager**) const;
  32189. int showWithOptionalCallback (const Options&, ModalComponentManager::Callback*, bool);
  32190. JUCE_LEAK_DETECTOR (PopupMenu);
  32191. };
  32192. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  32193. /*** End of inlined file: juce_PopupMenu.h ***/
  32194. /*** Start of inlined file: juce_TextInputTarget.h ***/
  32195. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  32196. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  32197. /**
  32198. An abstract base class which can be implemented by components that function as
  32199. text editors.
  32200. This class allows different types of text editor component to provide a uniform
  32201. interface, which can be used by things like OS-specific input methods, on-screen
  32202. keyboards, etc.
  32203. */
  32204. class JUCE_API TextInputTarget
  32205. {
  32206. public:
  32207. /** */
  32208. TextInputTarget() {}
  32209. /** Destructor. */
  32210. virtual ~TextInputTarget() {}
  32211. /** Returns true if this input target is currently accepting input.
  32212. For example, a text editor might return false if it's in read-only mode.
  32213. */
  32214. virtual bool isTextInputActive() const = 0;
  32215. /** Returns the extents of the selected text region, or an empty range if
  32216. nothing is selected,
  32217. */
  32218. virtual const Range<int> getHighlightedRegion() const = 0;
  32219. /** Sets the currently-selected text region. */
  32220. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  32221. /** Sets a number of temporarily underlined sections.
  32222. This is needed by MS Windows input method UI.
  32223. */
  32224. virtual void setTemporaryUnderlining (const Array <Range<int> >& underlinedRegions) = 0;
  32225. /** Returns a specified sub-section of the text. */
  32226. virtual const String getTextInRange (const Range<int>& range) const = 0;
  32227. /** Inserts some text, overwriting the selected text region, if there is one. */
  32228. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  32229. /** Returns the position of the caret, relative to the component's origin. */
  32230. virtual const Rectangle<int> getCaretRectangle() = 0;
  32231. };
  32232. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  32233. /*** End of inlined file: juce_TextInputTarget.h ***/
  32234. /*** Start of inlined file: juce_CaretComponent.h ***/
  32235. #ifndef __JUCE_CARETCOMPONENT_JUCEHEADER__
  32236. #define __JUCE_CARETCOMPONENT_JUCEHEADER__
  32237. /**
  32238. */
  32239. class JUCE_API CaretComponent : public Component,
  32240. public Timer
  32241. {
  32242. public:
  32243. /** Creates the caret component.
  32244. The keyFocusOwner is an optional component which the caret will check, making
  32245. itself visible only when the keyFocusOwner has keyboard focus.
  32246. */
  32247. CaretComponent (Component* keyFocusOwner);
  32248. /** Destructor. */
  32249. ~CaretComponent();
  32250. /** Sets the caret's position to place it next to the given character.
  32251. The area is the rectangle containing the entire character that the caret is
  32252. positioned on, so by default a vertical-line caret may choose to just show itself
  32253. at the left of this area. You can override this method to customise its size.
  32254. This method will also force the caret to reset its timer and become visible (if
  32255. appropriate), so that as it moves, you can see where it is.
  32256. */
  32257. virtual void setCaretPosition (const Rectangle<int>& characterArea);
  32258. /** A set of colour IDs to use to change the colour of various aspects of the caret.
  32259. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32260. methods.
  32261. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32262. */
  32263. enum ColourIds
  32264. {
  32265. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  32266. };
  32267. /** @internal */
  32268. void paint (Graphics& g);
  32269. /** @internal */
  32270. void timerCallback();
  32271. private:
  32272. Component* owner;
  32273. bool shouldBeShown() const;
  32274. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  32275. };
  32276. #endif // __JUCE_CARETCOMPONENT_JUCEHEADER__
  32277. /*** End of inlined file: juce_CaretComponent.h ***/
  32278. /**
  32279. A component containing text that can be edited.
  32280. A TextEditor can either be in single- or multi-line mode, and supports mixed
  32281. fonts and colours.
  32282. @see TextEditor::Listener, Label
  32283. */
  32284. class JUCE_API TextEditor : public Component,
  32285. public TextInputTarget,
  32286. public SettableTooltipClient
  32287. {
  32288. public:
  32289. /** Creates a new, empty text editor.
  32290. @param componentName the name to pass to the component for it to use as its name
  32291. @param passwordCharacter if this is not zero, this character will be used as a replacement
  32292. for all characters that are drawn on screen - e.g. to create
  32293. a password-style textbox containing circular blobs instead of text,
  32294. you could set this value to 0x25cf, which is the unicode character
  32295. for a black splodge (not all fonts include this, though), or 0x2022,
  32296. which is a bullet (probably the best choice for linux).
  32297. */
  32298. explicit TextEditor (const String& componentName = String::empty,
  32299. juce_wchar passwordCharacter = 0);
  32300. /** Destructor. */
  32301. virtual ~TextEditor();
  32302. /** Puts the editor into either multi- or single-line mode.
  32303. By default, the editor will be in single-line mode, so use this if you need a multi-line
  32304. editor.
  32305. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  32306. on if you want a multi-line editor with line-breaks.
  32307. @see isMultiLine, setReturnKeyStartsNewLine
  32308. */
  32309. void setMultiLine (bool shouldBeMultiLine,
  32310. bool shouldWordWrap = true);
  32311. /** Returns true if the editor is in multi-line mode.
  32312. */
  32313. bool isMultiLine() const;
  32314. /** Changes the behaviour of the return key.
  32315. If set to true, the return key will insert a new-line into the text; if false
  32316. it will trigger a call to the TextEditor::Listener::textEditorReturnKeyPressed()
  32317. method. By default this is set to false, and when true it will only insert
  32318. new-lines when in multi-line mode (see setMultiLine()).
  32319. */
  32320. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  32321. /** Returns the value set by setReturnKeyStartsNewLine().
  32322. See setReturnKeyStartsNewLine() for more info.
  32323. */
  32324. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  32325. /** Indicates whether the tab key should be accepted and used to input a tab character,
  32326. or whether it gets ignored.
  32327. By default the tab key is ignored, so that it can be used to switch keyboard focus
  32328. between components.
  32329. */
  32330. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  32331. /** Returns true if the tab key is being used for input.
  32332. @see setTabKeyUsedAsCharacter
  32333. */
  32334. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  32335. /** Changes the editor to read-only mode.
  32336. By default, the text editor is not read-only. If you're making it read-only, you
  32337. might also want to call setCaretVisible (false) to get rid of the caret.
  32338. The text can still be highlighted and copied when in read-only mode.
  32339. @see isReadOnly, setCaretVisible
  32340. */
  32341. void setReadOnly (bool shouldBeReadOnly);
  32342. /** Returns true if the editor is in read-only mode.
  32343. */
  32344. bool isReadOnly() const;
  32345. /** Makes the caret visible or invisible.
  32346. By default the caret is visible.
  32347. @see setCaretColour, setCaretPosition
  32348. */
  32349. void setCaretVisible (bool shouldBeVisible);
  32350. /** Returns true if the caret is enabled.
  32351. @see setCaretVisible
  32352. */
  32353. bool isCaretVisible() const { return caret != nullptr; }
  32354. /** Enables/disables a vertical scrollbar.
  32355. (This only applies when in multi-line mode). When the text gets too long to fit
  32356. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  32357. this is enabled, the scrollbar will be hidden unless it's needed.
  32358. By default the scrollbar is enabled.
  32359. */
  32360. void setScrollbarsShown (bool shouldBeEnabled);
  32361. /** Returns true if scrollbars are enabled.
  32362. @see setScrollbarsShown
  32363. */
  32364. bool areScrollbarsShown() const { return scrollbarVisible; }
  32365. /** Changes the password character used to disguise the text.
  32366. @param passwordCharacter if this is not zero, this character will be used as a replacement
  32367. for all characters that are drawn on screen - e.g. to create
  32368. a password-style textbox containing circular blobs instead of text,
  32369. you could set this value to 0x25cf, which is the unicode character
  32370. for a black splodge (not all fonts include this, though), or 0x2022,
  32371. which is a bullet (probably the best choice for linux).
  32372. */
  32373. void setPasswordCharacter (juce_wchar passwordCharacter);
  32374. /** Returns the current password character.
  32375. @see setPasswordCharacter
  32376. */
  32377. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  32378. /** Allows a right-click menu to appear for the editor.
  32379. (This defaults to being enabled).
  32380. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  32381. of options such as cut/copy/paste, undo/redo, etc.
  32382. */
  32383. void setPopupMenuEnabled (bool menuEnabled);
  32384. /** Returns true if the right-click menu is enabled.
  32385. @see setPopupMenuEnabled
  32386. */
  32387. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  32388. /** Returns true if a popup-menu is currently being displayed.
  32389. */
  32390. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  32391. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  32392. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32393. methods.
  32394. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32395. */
  32396. enum ColourIds
  32397. {
  32398. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  32399. transparent if necessary. */
  32400. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  32401. that because the editor can contain multiple colours, calling this
  32402. method won't change the colour of existing text - to do that, call
  32403. applyFontToAllText() after calling this method.*/
  32404. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  32405. the text - this can be transparent if you don't want to show any
  32406. highlighting.*/
  32407. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  32408. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  32409. the edge of the component. */
  32410. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  32411. the edge of the component when it has focus. */
  32412. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  32413. around the edge of the editor. */
  32414. };
  32415. /** Sets the font to use for newly added text.
  32416. This will change the font that will be used next time any text is added or entered
  32417. into the editor. It won't change the font of any existing text - to do that, use
  32418. applyFontToAllText() instead.
  32419. @see applyFontToAllText
  32420. */
  32421. void setFont (const Font& newFont);
  32422. /** Applies a font to all the text in the editor.
  32423. This will also set the current font to use for any new text that's added.
  32424. @see setFont
  32425. */
  32426. void applyFontToAllText (const Font& newFont);
  32427. /** Returns the font that's currently being used for new text.
  32428. @see setFont
  32429. */
  32430. const Font getFont() const;
  32431. /** If set to true, focusing on the editor will highlight all its text.
  32432. (Set to false by default).
  32433. This is useful for boxes where you expect the user to re-enter all the
  32434. text when they focus on the component, rather than editing what's already there.
  32435. */
  32436. void setSelectAllWhenFocused (bool b);
  32437. /** Sets limits on the characters that can be entered.
  32438. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  32439. limit is set
  32440. @param allowedCharacters if this is non-empty, then only characters that occur in
  32441. this string are allowed to be entered into the editor.
  32442. */
  32443. void setInputRestrictions (int maxTextLength,
  32444. const String& allowedCharacters = String::empty);
  32445. /** When the text editor is empty, it can be set to display a message.
  32446. This is handy for things like telling the user what to type in the box - the
  32447. string is only displayed, it's not taken to actually be the contents of
  32448. the editor.
  32449. */
  32450. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  32451. /** Changes the size of the scrollbars that are used.
  32452. Handy if you need smaller scrollbars for a small text box.
  32453. */
  32454. void setScrollBarThickness (int newThicknessPixels);
  32455. /** Shows or hides the buttons on any scrollbars that are used.
  32456. @see ScrollBar::setButtonVisibility
  32457. */
  32458. void setScrollBarButtonVisibility (bool buttonsVisible);
  32459. /**
  32460. Receives callbacks from a TextEditor component when it changes.
  32461. @see TextEditor::addListener
  32462. */
  32463. class JUCE_API Listener
  32464. {
  32465. public:
  32466. /** Destructor. */
  32467. virtual ~Listener() {}
  32468. /** Called when the user changes the text in some way. */
  32469. virtual void textEditorTextChanged (TextEditor& editor);
  32470. /** Called when the user presses the return key. */
  32471. virtual void textEditorReturnKeyPressed (TextEditor& editor);
  32472. /** Called when the user presses the escape key. */
  32473. virtual void textEditorEscapeKeyPressed (TextEditor& editor);
  32474. /** Called when the text editor loses focus. */
  32475. virtual void textEditorFocusLost (TextEditor& editor);
  32476. };
  32477. /** Registers a listener to be told when things happen to the text.
  32478. @see removeListener
  32479. */
  32480. void addListener (Listener* newListener);
  32481. /** Deregisters a listener.
  32482. @see addListener
  32483. */
  32484. void removeListener (Listener* listenerToRemove);
  32485. /** Returns the entire contents of the editor. */
  32486. const String getText() const;
  32487. /** Returns a section of the contents of the editor. */
  32488. const String getTextInRange (const Range<int>& textRange) const;
  32489. /** Returns true if there are no characters in the editor.
  32490. This is more efficient than calling getText().isEmpty().
  32491. */
  32492. bool isEmpty() const;
  32493. /** Sets the entire content of the editor.
  32494. This will clear the editor and insert the given text (using the current text colour
  32495. and font). You can set the current text colour using
  32496. @code setColour (TextEditor::textColourId, ...);
  32497. @endcode
  32498. @param newText the text to add
  32499. @param sendTextChangeMessage if true, this will cause a change message to
  32500. be sent to all the listeners.
  32501. @see insertText
  32502. */
  32503. void setText (const String& newText,
  32504. bool sendTextChangeMessage = true);
  32505. /** Returns a Value object that can be used to get or set the text.
  32506. Bear in mind that this operate quite slowly if your text box contains large
  32507. amounts of text, as it needs to dynamically build the string that's involved. It's
  32508. best used for small text boxes.
  32509. */
  32510. Value& getTextValue();
  32511. /** Inserts some text at the current caret position.
  32512. If a section of the text is highlighted, it will be replaced by
  32513. this string, otherwise it will be inserted.
  32514. To delete a section of text, you can use setHighlightedRegion() to
  32515. highlight it, and call insertTextAtCursor (String::empty).
  32516. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  32517. */
  32518. void insertTextAtCaret (const String& textToInsert);
  32519. /** Deletes all the text from the editor. */
  32520. void clear();
  32521. /** Deletes the currently selected region.
  32522. This doesn't copy the deleted section to the clipboard - if you need to do that, call copy() first.
  32523. @see copy, paste, SystemClipboard
  32524. */
  32525. void cut();
  32526. /** Copies the currently selected region to the clipboard.
  32527. @see cut, paste, SystemClipboard
  32528. */
  32529. void copy();
  32530. /** Pastes the contents of the clipboard into the editor at the caret position.
  32531. @see cut, copy, SystemClipboard
  32532. */
  32533. void paste();
  32534. /** Moves the caret to be in front of a given character.
  32535. @see getCaretPosition
  32536. */
  32537. void setCaretPosition (int newIndex);
  32538. /** Returns the current index of the caret.
  32539. @see setCaretPosition
  32540. */
  32541. int getCaretPosition() const;
  32542. /** Attempts to scroll the text editor so that the caret ends up at
  32543. a specified position.
  32544. This won't affect the caret's position within the text, it tries to scroll
  32545. the entire editor vertically and horizontally so that the caret is sitting
  32546. at the given position (relative to the top-left of this component).
  32547. Depending on the amount of text available, it might not be possible to
  32548. scroll far enough for the caret to reach this exact position, but it
  32549. will go as far as it can in that direction.
  32550. */
  32551. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  32552. /** Get the graphical position of the caret.
  32553. The rectangle returned is relative to the component's top-left corner.
  32554. @see scrollEditorToPositionCaret
  32555. */
  32556. const Rectangle<int> getCaretRectangle();
  32557. /** Selects a section of the text. */
  32558. void setHighlightedRegion (const Range<int>& newSelection);
  32559. /** Returns the range of characters that are selected.
  32560. If nothing is selected, this will return an empty range.
  32561. @see setHighlightedRegion
  32562. */
  32563. const Range<int> getHighlightedRegion() const { return selection; }
  32564. /** Returns the section of text that is currently selected. */
  32565. const String getHighlightedText() const;
  32566. /** Finds the index of the character at a given position.
  32567. The co-ordinates are relative to the component's top-left.
  32568. */
  32569. int getTextIndexAt (int x, int y);
  32570. /** Counts the number of characters in the text.
  32571. This is quicker than getting the text as a string if you just need to know
  32572. the length.
  32573. */
  32574. int getTotalNumChars() const;
  32575. /** Returns the total width of the text, as it is currently laid-out.
  32576. This may be larger than the size of the TextEditor, and can change when
  32577. the TextEditor is resized or the text changes.
  32578. */
  32579. int getTextWidth() const;
  32580. /** Returns the maximum height of the text, as it is currently laid-out.
  32581. This may be larger than the size of the TextEditor, and can change when
  32582. the TextEditor is resized or the text changes.
  32583. */
  32584. int getTextHeight() const;
  32585. /** Changes the size of the gap at the top and left-edge of the editor.
  32586. By default there's a gap of 4 pixels.
  32587. */
  32588. void setIndents (int newLeftIndent, int newTopIndent);
  32589. /** Changes the size of border left around the edge of the component.
  32590. @see getBorder
  32591. */
  32592. void setBorder (const BorderSize<int>& border);
  32593. /** Returns the size of border around the edge of the component.
  32594. @see setBorder
  32595. */
  32596. const BorderSize<int> getBorder() const;
  32597. /** Used to disable the auto-scrolling which keeps the caret visible.
  32598. If true (the default), the editor will scroll when the caret moves offscreen. If
  32599. set to false, it won't.
  32600. */
  32601. void setScrollToShowCursor (bool shouldScrollToShowCaret);
  32602. /** @internal */
  32603. void paint (Graphics& g);
  32604. /** @internal */
  32605. void paintOverChildren (Graphics& g);
  32606. /** @internal */
  32607. void mouseDown (const MouseEvent& e);
  32608. /** @internal */
  32609. void mouseUp (const MouseEvent& e);
  32610. /** @internal */
  32611. void mouseDrag (const MouseEvent& e);
  32612. /** @internal */
  32613. void mouseDoubleClick (const MouseEvent& e);
  32614. /** @internal */
  32615. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  32616. /** @internal */
  32617. bool keyPressed (const KeyPress& key);
  32618. /** @internal */
  32619. bool keyStateChanged (bool isKeyDown);
  32620. /** @internal */
  32621. void focusGained (FocusChangeType cause);
  32622. /** @internal */
  32623. void focusLost (FocusChangeType cause);
  32624. /** @internal */
  32625. void resized();
  32626. /** @internal */
  32627. void enablementChanged();
  32628. /** @internal */
  32629. void colourChanged();
  32630. /** @internal */
  32631. void lookAndFeelChanged();
  32632. /** @internal */
  32633. bool isTextInputActive() const;
  32634. /** @internal */
  32635. void setTemporaryUnderlining (const Array <Range<int> >&);
  32636. /** This adds the items to the popup menu.
  32637. By default it adds the cut/copy/paste items, but you can override this if
  32638. you need to replace these with your own items.
  32639. If you want to add your own items to the existing ones, you can override this,
  32640. call the base class's addPopupMenuItems() method, then append your own items.
  32641. When the menu has been shown, performPopupMenuAction() will be called to
  32642. perform the item that the user has chosen.
  32643. The default menu items will be added using item IDs in the range
  32644. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  32645. menu IDs.
  32646. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  32647. a pointer to the info about it, or may be null if the menu is being triggered
  32648. by some other means.
  32649. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  32650. */
  32651. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  32652. const MouseEvent* mouseClickEvent);
  32653. /** This is called to perform one of the items that was shown on the popup menu.
  32654. If you've overridden addPopupMenuItems(), you should also override this
  32655. to perform the actions that you've added.
  32656. If you've overridden addPopupMenuItems() but have still left the default items
  32657. on the menu, remember to call the superclass's performPopupMenuAction()
  32658. so that it can perform the default actions if that's what the user clicked on.
  32659. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  32660. */
  32661. virtual void performPopupMenuAction (int menuItemID);
  32662. protected:
  32663. /** Scrolls the minimum distance needed to get the caret into view. */
  32664. void scrollToMakeSureCursorIsVisible();
  32665. /** @internal */
  32666. void moveCaret (int newCaretPos);
  32667. /** @internal */
  32668. void moveCaretTo (int newPosition, bool isSelecting);
  32669. /** Used internally to dispatch a text-change message. */
  32670. void textChanged();
  32671. /** Begins a new transaction in the UndoManager. */
  32672. void newTransaction();
  32673. /** Used internally to trigger an undo or redo. */
  32674. void doUndoRedo (bool isRedo);
  32675. /** Can be overridden to intercept return key presses directly */
  32676. virtual void returnPressed();
  32677. /** Can be overridden to intercept escape key presses directly */
  32678. virtual void escapePressed();
  32679. /** @internal */
  32680. void handleCommandMessage (int commandId);
  32681. private:
  32682. class Iterator;
  32683. class UniformTextSection;
  32684. class TextHolderComponent;
  32685. class InsertAction;
  32686. class RemoveAction;
  32687. friend class InsertAction;
  32688. friend class RemoveAction;
  32689. ScopedPointer <Viewport> viewport;
  32690. TextHolderComponent* textHolder;
  32691. BorderSize<int> borderSize;
  32692. bool readOnly : 1;
  32693. bool multiline : 1;
  32694. bool wordWrap : 1;
  32695. bool returnKeyStartsNewLine : 1;
  32696. bool popupMenuEnabled : 1;
  32697. bool selectAllTextWhenFocused : 1;
  32698. bool scrollbarVisible : 1;
  32699. bool wasFocused : 1;
  32700. bool keepCaretOnScreen : 1;
  32701. bool tabKeyUsed : 1;
  32702. bool menuActive : 1;
  32703. bool valueTextNeedsUpdating : 1;
  32704. UndoManager undoManager;
  32705. ScopedPointer<CaretComponent> caret;
  32706. int maxTextLength;
  32707. Range<int> selection;
  32708. int leftIndent, topIndent;
  32709. unsigned int lastTransactionTime;
  32710. Font currentFont;
  32711. mutable int totalNumChars;
  32712. int caretPosition;
  32713. Array <UniformTextSection*> sections;
  32714. String textToShowWhenEmpty;
  32715. Colour colourForTextWhenEmpty;
  32716. juce_wchar passwordCharacter;
  32717. Value textValue;
  32718. enum
  32719. {
  32720. notDragging,
  32721. draggingSelectionStart,
  32722. draggingSelectionEnd
  32723. } dragType;
  32724. String allowedCharacters;
  32725. ListenerList <Listener> listeners;
  32726. Array <Range<int> > underlinedSections;
  32727. void coalesceSimilarSections();
  32728. void splitSection (int sectionIndex, int charToSplitAt);
  32729. void clearInternal (UndoManager* um);
  32730. void insert (const String& text, int insertIndex, const Font& font,
  32731. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  32732. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  32733. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  32734. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  32735. void updateCaretPosition();
  32736. void textWasChangedByValue();
  32737. int indexAtPosition (float x, float y);
  32738. int findWordBreakAfter (int position) const;
  32739. int findWordBreakBefore (int position) const;
  32740. friend class TextHolderComponent;
  32741. friend class TextEditorViewport;
  32742. void drawContent (Graphics& g);
  32743. void updateTextHolderSize();
  32744. float getWordWrapWidth() const;
  32745. void timerCallbackInt();
  32746. void repaintText (const Range<int>& range);
  32747. UndoManager* getUndoManager() noexcept;
  32748. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditor);
  32749. };
  32750. /** This typedef is just for compatibility with old code - newer code should use the TextEditor::Listener class directly. */
  32751. typedef TextEditor::Listener TextEditorListener;
  32752. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  32753. /*** End of inlined file: juce_TextEditor.h ***/
  32754. #if JUCE_VC6
  32755. #define Listener ButtonListener
  32756. #endif
  32757. /**
  32758. A component that displays a text string, and can optionally become a text
  32759. editor when clicked.
  32760. */
  32761. class JUCE_API Label : public Component,
  32762. public SettableTooltipClient,
  32763. protected TextEditorListener,
  32764. private ComponentListener,
  32765. private ValueListener
  32766. {
  32767. public:
  32768. /** Creates a Label.
  32769. @param componentName the name to give the component
  32770. @param labelText the text to show in the label
  32771. */
  32772. Label (const String& componentName = String::empty,
  32773. const String& labelText = String::empty);
  32774. /** Destructor. */
  32775. ~Label();
  32776. /** Changes the label text.
  32777. If broadcastChangeMessage is true and the new text is different to the current
  32778. text, then the class will broadcast a change message to any Label::Listener objects
  32779. that are registered.
  32780. */
  32781. void setText (const String& newText, bool broadcastChangeMessage);
  32782. /** Returns the label's current text.
  32783. @param returnActiveEditorContents if this is true and the label is currently
  32784. being edited, then this method will return the
  32785. text as it's being shown in the editor. If false,
  32786. then the value returned here won't be updated until
  32787. the user has finished typing and pressed the return
  32788. key.
  32789. */
  32790. const String getText (bool returnActiveEditorContents = false) const;
  32791. /** Returns the text content as a Value object.
  32792. You can call Value::referTo() on this object to make the label read and control
  32793. a Value object that you supply.
  32794. */
  32795. Value& getTextValue() { return textValue; }
  32796. /** Changes the font to use to draw the text.
  32797. @see getFont
  32798. */
  32799. void setFont (const Font& newFont);
  32800. /** Returns the font currently being used.
  32801. @see setFont
  32802. */
  32803. const Font& getFont() const noexcept;
  32804. /** A set of colour IDs to use to change the colour of various aspects of the label.
  32805. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32806. methods.
  32807. Note that you can also use the constants from TextEditor::ColourIds to change the
  32808. colour of the text editor that is opened when a label is editable.
  32809. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32810. */
  32811. enum ColourIds
  32812. {
  32813. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  32814. textColourId = 0x1000281, /**< The colour for the text. */
  32815. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  32816. Leave this transparent to not have an outline. */
  32817. };
  32818. /** Sets the style of justification to be used for positioning the text.
  32819. (The default is Justification::centredLeft)
  32820. */
  32821. void setJustificationType (const Justification& justification);
  32822. /** Returns the type of justification, as set in setJustificationType(). */
  32823. const Justification getJustificationType() const noexcept { return justification; }
  32824. /** Changes the gap that is left between the edge of the component and the text.
  32825. By default there's a small gap left at the sides of the component to allow for
  32826. the drawing of the border, but you can change this if necessary.
  32827. */
  32828. void setBorderSize (int horizontalBorder, int verticalBorder);
  32829. /** Returns the size of the horizontal gap being left around the text.
  32830. */
  32831. int getHorizontalBorderSize() const noexcept { return horizontalBorderSize; }
  32832. /** Returns the size of the vertical gap being left around the text.
  32833. */
  32834. int getVerticalBorderSize() const noexcept { return verticalBorderSize; }
  32835. /** Makes this label "stick to" another component.
  32836. This will cause the label to follow another component around, staying
  32837. either to its left or above it.
  32838. @param owner the component to follow
  32839. @param onLeft if true, the label will stay on the left of its component; if
  32840. false, it will stay above it.
  32841. */
  32842. void attachToComponent (Component* owner, bool onLeft);
  32843. /** If this label has been attached to another component using attachToComponent, this
  32844. returns the other component.
  32845. Returns 0 if the label is not attached.
  32846. */
  32847. Component* getAttachedComponent() const;
  32848. /** If the label is attached to the left of another component, this returns true.
  32849. Returns false if the label is above the other component. This is only relevent if
  32850. attachToComponent() has been called.
  32851. */
  32852. bool isAttachedOnLeft() const noexcept { return leftOfOwnerComp; }
  32853. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  32854. using ellipsis.
  32855. @see Graphics::drawFittedText
  32856. */
  32857. void setMinimumHorizontalScale (float newScale);
  32858. float getMinimumHorizontalScale() const noexcept { return minimumHorizontalScale; }
  32859. /**
  32860. A class for receiving events from a Label.
  32861. You can register a Label::Listener with a Label using the Label::addListener()
  32862. method, and it will be called when the text of the label changes, either because
  32863. of a call to Label::setText() or by the user editing the text (if the label is
  32864. editable).
  32865. @see Label::addListener, Label::removeListener
  32866. */
  32867. class JUCE_API Listener
  32868. {
  32869. public:
  32870. /** Destructor. */
  32871. virtual ~Listener() {}
  32872. /** Called when a Label's text has changed.
  32873. */
  32874. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  32875. };
  32876. /** Registers a listener that will be called when the label's text changes. */
  32877. void addListener (Listener* listener);
  32878. /** Deregisters a previously-registered listener. */
  32879. void removeListener (Listener* listener);
  32880. /** Makes the label turn into a TextEditor when clicked.
  32881. By default this is turned off.
  32882. If turned on, then single- or double-clicking will turn the label into
  32883. an editor. If the user then changes the text, then the ChangeBroadcaster
  32884. base class will be used to send change messages to any listeners that
  32885. have registered.
  32886. If the user changes the text, the textWasEdited() method will be called
  32887. afterwards, and subclasses can override this if they need to do anything
  32888. special.
  32889. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  32890. @param editOnDoubleClick if true, a double-click is needed to start editing
  32891. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  32892. edited will discard any changes; if false, then this will
  32893. commit the changes.
  32894. @see showEditor, setEditorColours, TextEditor
  32895. */
  32896. void setEditable (bool editOnSingleClick,
  32897. bool editOnDoubleClick = false,
  32898. bool lossOfFocusDiscardsChanges = false);
  32899. /** Returns true if this option was set using setEditable(). */
  32900. bool isEditableOnSingleClick() const noexcept { return editSingleClick; }
  32901. /** Returns true if this option was set using setEditable(). */
  32902. bool isEditableOnDoubleClick() const noexcept { return editDoubleClick; }
  32903. /** Returns true if this option has been set in a call to setEditable(). */
  32904. bool doesLossOfFocusDiscardChanges() const noexcept { return lossOfFocusDiscardsChanges; }
  32905. /** Returns true if the user can edit this label's text. */
  32906. bool isEditable() const noexcept { return editSingleClick || editDoubleClick; }
  32907. /** Makes the editor appear as if the label had been clicked by the user.
  32908. @see textWasEdited, setEditable
  32909. */
  32910. void showEditor();
  32911. /** Hides the editor if it was being shown.
  32912. @param discardCurrentEditorContents if true, the label's text will be
  32913. reset to whatever it was before the editor
  32914. was shown; if false, the current contents of the
  32915. editor will be used to set the label's text
  32916. before it is hidden.
  32917. */
  32918. void hideEditor (bool discardCurrentEditorContents);
  32919. /** Returns true if the editor is currently focused and active. */
  32920. bool isBeingEdited() const noexcept;
  32921. protected:
  32922. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  32923. Subclasses can override this if they need to customise this component in some way.
  32924. */
  32925. virtual TextEditor* createEditorComponent();
  32926. /** Called after the user changes the text. */
  32927. virtual void textWasEdited();
  32928. /** Called when the text has been altered. */
  32929. virtual void textWasChanged();
  32930. /** Called when the text editor has just appeared, due to a user click or other focus change. */
  32931. virtual void editorShown (TextEditor* editorComponent);
  32932. /** Called when the text editor is going to be deleted, after editing has finished. */
  32933. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  32934. /** @internal */
  32935. void paint (Graphics& g);
  32936. /** @internal */
  32937. void resized();
  32938. /** @internal */
  32939. void mouseUp (const MouseEvent& e);
  32940. /** @internal */
  32941. void mouseDoubleClick (const MouseEvent& e);
  32942. /** @internal */
  32943. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  32944. /** @internal */
  32945. void componentParentHierarchyChanged (Component& component);
  32946. /** @internal */
  32947. void componentVisibilityChanged (Component& component);
  32948. /** @internal */
  32949. void inputAttemptWhenModal();
  32950. /** @internal */
  32951. void focusGained (FocusChangeType);
  32952. /** @internal */
  32953. void enablementChanged();
  32954. /** @internal */
  32955. KeyboardFocusTraverser* createFocusTraverser();
  32956. /** @internal */
  32957. void textEditorTextChanged (TextEditor& editor);
  32958. /** @internal */
  32959. void textEditorReturnKeyPressed (TextEditor& editor);
  32960. /** @internal */
  32961. void textEditorEscapeKeyPressed (TextEditor& editor);
  32962. /** @internal */
  32963. void textEditorFocusLost (TextEditor& editor);
  32964. /** @internal */
  32965. void colourChanged();
  32966. /** @internal */
  32967. void valueChanged (Value&);
  32968. private:
  32969. Value textValue;
  32970. String lastTextValue;
  32971. Font font;
  32972. Justification justification;
  32973. ScopedPointer<TextEditor> editor;
  32974. ListenerList<Listener> listeners;
  32975. WeakReference<Component> ownerComponent;
  32976. int horizontalBorderSize, verticalBorderSize;
  32977. float minimumHorizontalScale;
  32978. bool editSingleClick : 1;
  32979. bool editDoubleClick : 1;
  32980. bool lossOfFocusDiscardsChanges : 1;
  32981. bool leftOfOwnerComp : 1;
  32982. bool updateFromTextEditorContents (TextEditor&);
  32983. void callChangeListeners();
  32984. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Label);
  32985. };
  32986. /** This typedef is just for compatibility with old code - newer code should use the Label::Listener class directly. */
  32987. typedef Label::Listener LabelListener;
  32988. #if JUCE_VC6
  32989. #undef Listener
  32990. #endif
  32991. #endif // __JUCE_LABEL_JUCEHEADER__
  32992. /*** End of inlined file: juce_Label.h ***/
  32993. #if JUCE_VC6
  32994. #define Listener SliderListener
  32995. #endif
  32996. /**
  32997. A component that lets the user choose from a drop-down list of choices.
  32998. The combo-box has a list of text strings, each with an associated id number,
  32999. that will be shown in the drop-down list when the user clicks on the component.
  33000. The currently selected choice is displayed in the combo-box, and this can
  33001. either be read-only text, or editable.
  33002. To find out when the user selects a different item or edits the text, you
  33003. can register a ComboBox::Listener to receive callbacks.
  33004. @see ComboBox::Listener
  33005. */
  33006. class JUCE_API ComboBox : public Component,
  33007. public SettableTooltipClient,
  33008. public LabelListener, // (can't use Label::Listener due to idiotic VC2005 bug)
  33009. public ValueListener,
  33010. private AsyncUpdater
  33011. {
  33012. public:
  33013. /** Creates a combo-box.
  33014. On construction, the text field will be empty, so you should call the
  33015. setSelectedId() or setText() method to choose the initial value before
  33016. displaying it.
  33017. @param componentName the name to set for the component (see Component::setName())
  33018. */
  33019. explicit ComboBox (const String& componentName = String::empty);
  33020. /** Destructor. */
  33021. ~ComboBox();
  33022. /** Sets whether the test in the combo-box is editable.
  33023. The default state for a new ComboBox is non-editable, and can only be changed
  33024. by choosing from the drop-down list.
  33025. */
  33026. void setEditableText (bool isEditable);
  33027. /** Returns true if the text is directly editable.
  33028. @see setEditableText
  33029. */
  33030. bool isTextEditable() const noexcept;
  33031. /** Sets the style of justification to be used for positioning the text.
  33032. The default is Justification::centredLeft. The text is displayed using a
  33033. Label component inside the ComboBox.
  33034. */
  33035. void setJustificationType (const Justification& justification);
  33036. /** Returns the current justification for the text box.
  33037. @see setJustificationType
  33038. */
  33039. const Justification getJustificationType() const noexcept;
  33040. /** Adds an item to be shown in the drop-down list.
  33041. @param newItemText the text of the item to show in the list
  33042. @param newItemId an associated ID number that can be set or retrieved - see
  33043. getSelectedId() and setSelectedId(). Note that this value can not
  33044. be 0!
  33045. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  33046. */
  33047. void addItem (const String& newItemText, int newItemId);
  33048. /** Adds a separator line to the drop-down list.
  33049. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  33050. */
  33051. void addSeparator();
  33052. /** Adds a heading to the drop-down list, so that you can group the items into
  33053. different sections.
  33054. The headings are indented slightly differently to set them apart from the
  33055. items on the list, and obviously can't be selected. You might want to add
  33056. separators between your sections too.
  33057. @see addItem, addSeparator
  33058. */
  33059. void addSectionHeading (const String& headingName);
  33060. /** This allows items in the drop-down list to be selectively disabled.
  33061. When you add an item, it's enabled by default, but you can call this
  33062. method to change its status.
  33063. If you disable an item which is already selected, this won't change the
  33064. current selection - it just stops the user choosing that item from the list.
  33065. */
  33066. void setItemEnabled (int itemId, bool shouldBeEnabled);
  33067. /** Returns true if the given item is enabled. */
  33068. bool isItemEnabled (int itemId) const noexcept;
  33069. /** Changes the text for an existing item.
  33070. */
  33071. void changeItemText (int itemId, const String& newText);
  33072. /** Removes all the items from the drop-down list.
  33073. If this call causes the content to be cleared, then a change-message
  33074. will be broadcast unless dontSendChangeMessage is true.
  33075. @see addItem, removeItem, getNumItems
  33076. */
  33077. void clear (bool dontSendChangeMessage = false);
  33078. /** Returns the number of items that have been added to the list.
  33079. Note that this doesn't include headers or separators.
  33080. */
  33081. int getNumItems() const noexcept;
  33082. /** Returns the text for one of the items in the list.
  33083. Note that this doesn't include headers or separators.
  33084. @param index the item's index from 0 to (getNumItems() - 1)
  33085. */
  33086. const String getItemText (int index) const;
  33087. /** Returns the ID for one of the items in the list.
  33088. Note that this doesn't include headers or separators.
  33089. @param index the item's index from 0 to (getNumItems() - 1)
  33090. */
  33091. int getItemId (int index) const noexcept;
  33092. /** Returns the index in the list of a particular item ID.
  33093. If no such ID is found, this will return -1.
  33094. */
  33095. int indexOfItemId (int itemId) const noexcept;
  33096. /** Returns the ID of the item that's currently shown in the box.
  33097. If no item is selected, or if the text is editable and the user
  33098. has entered something which isn't one of the items in the list, then
  33099. this will return 0.
  33100. @see setSelectedId, getSelectedItemIndex, getText
  33101. */
  33102. int getSelectedId() const noexcept;
  33103. /** Returns a Value object that can be used to get or set the selected item's ID.
  33104. You can call Value::referTo() on this object to make the combo box control
  33105. another Value object.
  33106. */
  33107. Value& getSelectedIdAsValue() { return currentId; }
  33108. /** Sets one of the items to be the current selection.
  33109. This will set the ComboBox's text to that of the item that matches
  33110. this ID.
  33111. @param newItemId the new item to select
  33112. @param dontSendChangeMessage if set to true, this method won't trigger a
  33113. change notification
  33114. @see getSelectedId, setSelectedItemIndex, setText
  33115. */
  33116. void setSelectedId (int newItemId, bool dontSendChangeMessage = false);
  33117. /** Returns the index of the item that's currently shown in the box.
  33118. If no item is selected, or if the text is editable and the user
  33119. has entered something which isn't one of the items in the list, then
  33120. this will return -1.
  33121. @see setSelectedItemIndex, getSelectedId, getText
  33122. */
  33123. int getSelectedItemIndex() const;
  33124. /** Sets one of the items to be the current selection.
  33125. This will set the ComboBox's text to that of the item at the given
  33126. index in the list.
  33127. @param newItemIndex the new item to select
  33128. @param dontSendChangeMessage if set to true, this method won't trigger a
  33129. change notification
  33130. @see getSelectedItemIndex, setSelectedId, setText
  33131. */
  33132. void setSelectedItemIndex (int newItemIndex, bool dontSendChangeMessage = false);
  33133. /** Returns the text that is currently shown in the combo-box's text field.
  33134. If the ComboBox has editable text, then this text may have been edited
  33135. by the user; otherwise it will be one of the items from the list, or
  33136. possibly an empty string if nothing was selected.
  33137. @see setText, getSelectedId, getSelectedItemIndex
  33138. */
  33139. const String getText() const;
  33140. /** Sets the contents of the combo-box's text field.
  33141. The text passed-in will be set as the current text regardless of whether
  33142. it is one of the items in the list. If the current text isn't one of the
  33143. items, then getSelectedId() will return -1, otherwise it wil return
  33144. the approriate ID.
  33145. @param newText the text to select
  33146. @param dontSendChangeMessage if set to true, this method won't trigger a
  33147. change notification
  33148. @see getText
  33149. */
  33150. void setText (const String& newText, bool dontSendChangeMessage = false);
  33151. /** Programmatically opens the text editor to allow the user to edit the current item.
  33152. This is the same effect as when the box is clicked-on.
  33153. @see Label::showEditor();
  33154. */
  33155. void showEditor();
  33156. /** Pops up the combo box's list. */
  33157. void showPopup();
  33158. /**
  33159. A class for receiving events from a ComboBox.
  33160. You can register a ComboBox::Listener with a ComboBox using the ComboBox::addListener()
  33161. method, and it will be called when the selected item in the box changes.
  33162. @see ComboBox::addListener, ComboBox::removeListener
  33163. */
  33164. class JUCE_API Listener
  33165. {
  33166. public:
  33167. /** Destructor. */
  33168. virtual ~Listener() {}
  33169. /** Called when a ComboBox has its selected item changed. */
  33170. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  33171. };
  33172. /** Registers a listener that will be called when the box's content changes. */
  33173. void addListener (Listener* listener);
  33174. /** Deregisters a previously-registered listener. */
  33175. void removeListener (Listener* listener);
  33176. /** Sets a message to display when there is no item currently selected.
  33177. @see getTextWhenNothingSelected
  33178. */
  33179. void setTextWhenNothingSelected (const String& newMessage);
  33180. /** Returns the text that is shown when no item is selected.
  33181. @see setTextWhenNothingSelected
  33182. */
  33183. const String getTextWhenNothingSelected() const;
  33184. /** Sets the message to show when there are no items in the list, and the user clicks
  33185. on the drop-down box.
  33186. By default it just says "no choices", but this lets you change it to something more
  33187. meaningful.
  33188. */
  33189. void setTextWhenNoChoicesAvailable (const String& newMessage);
  33190. /** Returns the text shown when no items have been added to the list.
  33191. @see setTextWhenNoChoicesAvailable
  33192. */
  33193. const String getTextWhenNoChoicesAvailable() const;
  33194. /** Gives the ComboBox a tooltip. */
  33195. void setTooltip (const String& newTooltip);
  33196. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  33197. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33198. methods.
  33199. To change the colours of the menu that pops up
  33200. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33201. */
  33202. enum ColourIds
  33203. {
  33204. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  33205. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  33206. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  33207. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  33208. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  33209. };
  33210. /** @internal */
  33211. void labelTextChanged (Label*);
  33212. /** @internal */
  33213. void enablementChanged();
  33214. /** @internal */
  33215. void colourChanged();
  33216. /** @internal */
  33217. void focusGained (Component::FocusChangeType cause);
  33218. /** @internal */
  33219. void focusLost (Component::FocusChangeType cause);
  33220. /** @internal */
  33221. void handleAsyncUpdate();
  33222. /** @internal */
  33223. const String getTooltip() { return label->getTooltip(); }
  33224. /** @internal */
  33225. void mouseDown (const MouseEvent&);
  33226. /** @internal */
  33227. void mouseDrag (const MouseEvent&);
  33228. /** @internal */
  33229. void mouseUp (const MouseEvent&);
  33230. /** @internal */
  33231. void lookAndFeelChanged();
  33232. /** @internal */
  33233. void paint (Graphics&);
  33234. /** @internal */
  33235. void resized();
  33236. /** @internal */
  33237. bool keyStateChanged (bool isKeyDown);
  33238. /** @internal */
  33239. bool keyPressed (const KeyPress&);
  33240. /** @internal */
  33241. void valueChanged (Value&);
  33242. private:
  33243. struct ItemInfo
  33244. {
  33245. ItemInfo (const String& name, int itemId, bool isEnabled, bool isHeading);
  33246. bool isSeparator() const noexcept;
  33247. bool isRealItem() const noexcept;
  33248. String name;
  33249. int itemId;
  33250. bool isEnabled : 1, isHeading : 1;
  33251. };
  33252. OwnedArray <ItemInfo> items;
  33253. Value currentId;
  33254. int lastCurrentId;
  33255. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  33256. ListenerList <Listener> listeners;
  33257. ScopedPointer<Label> label;
  33258. String textWhenNothingSelected, noChoicesMessage;
  33259. ItemInfo* getItemForId (int itemId) const noexcept;
  33260. ItemInfo* getItemForIndex (int index) const noexcept;
  33261. bool selectIfEnabled (int index);
  33262. static void popupMenuFinishedCallback (int, ComboBox*);
  33263. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBox);
  33264. };
  33265. /** This typedef is just for compatibility with old code - newer code should use the ComboBox::Listener class directly. */
  33266. typedef ComboBox::Listener ComboBoxListener;
  33267. #if JUCE_VC6
  33268. #undef Listener
  33269. #endif
  33270. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  33271. /*** End of inlined file: juce_ComboBox.h ***/
  33272. /**
  33273. Manages the state of some audio and midi i/o devices.
  33274. This class keeps tracks of a currently-selected audio device, through
  33275. with which it continuously streams data from an audio callback, as well as
  33276. one or more midi inputs.
  33277. The idea is that your application will create one global instance of this object,
  33278. and let it take care of creating and deleting specific types of audio devices
  33279. internally. So when the device is changed, your callbacks will just keep running
  33280. without having to worry about this.
  33281. The manager can save and reload all of its device settings as XML, which
  33282. makes it very easy for you to save and reload the audio setup of your
  33283. application.
  33284. And to make it easy to let the user change its settings, there's a component
  33285. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  33286. device selection/sample-rate/latency controls.
  33287. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  33288. call addAudioCallback() to register your audio callback with it, and use that to process
  33289. your audio data.
  33290. The manager also acts as a handy hub for incoming midi messages, allowing a
  33291. listener to register for messages from either a specific midi device, or from whatever
  33292. the current default midi input device is. The listener then doesn't have to worry about
  33293. re-registering with different midi devices if they are changed or deleted.
  33294. And yet another neat trick is that amount of CPU time being used is measured and
  33295. available with the getCpuUsage() method.
  33296. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  33297. listeners whenever one of its settings is changed.
  33298. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  33299. */
  33300. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  33301. {
  33302. public:
  33303. /** Creates a default AudioDeviceManager.
  33304. Initially no audio device will be selected. You should call the initialise() method
  33305. and register an audio callback with setAudioCallback() before it'll be able to
  33306. actually make any noise.
  33307. */
  33308. AudioDeviceManager();
  33309. /** Destructor. */
  33310. ~AudioDeviceManager();
  33311. /**
  33312. This structure holds a set of properties describing the current audio setup.
  33313. An AudioDeviceManager uses this class to save/load its current settings, and to
  33314. specify your preferred options when opening a device.
  33315. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  33316. */
  33317. struct JUCE_API AudioDeviceSetup
  33318. {
  33319. /** Creates an AudioDeviceSetup object.
  33320. The default constructor sets all the member variables to indicate default values.
  33321. You can then fill-in any values you want to before passing the object to
  33322. AudioDeviceManager::initialise().
  33323. */
  33324. AudioDeviceSetup();
  33325. bool operator== (const AudioDeviceSetup& other) const;
  33326. /** The name of the audio device used for output.
  33327. The name has to be one of the ones listed by the AudioDeviceManager's currently
  33328. selected device type.
  33329. This may be the same as the input device.
  33330. An empty string indicates the default device.
  33331. */
  33332. String outputDeviceName;
  33333. /** The name of the audio device used for input.
  33334. This may be the same as the output device.
  33335. An empty string indicates the default device.
  33336. */
  33337. String inputDeviceName;
  33338. /** The current sample rate.
  33339. This rate is used for both the input and output devices.
  33340. A value of 0 indicates the default rate.
  33341. */
  33342. double sampleRate;
  33343. /** The buffer size, in samples.
  33344. This buffer size is used for both the input and output devices.
  33345. A value of 0 indicates the default buffer size.
  33346. */
  33347. int bufferSize;
  33348. /** The set of active input channels.
  33349. The bits that are set in this array indicate the channels of the
  33350. input device that are active.
  33351. If useDefaultInputChannels is true, this value is ignored.
  33352. */
  33353. BigInteger inputChannels;
  33354. /** If this is true, it indicates that the inputChannels array
  33355. should be ignored, and instead, the device's default channels
  33356. should be used.
  33357. */
  33358. bool useDefaultInputChannels;
  33359. /** The set of active output channels.
  33360. The bits that are set in this array indicate the channels of the
  33361. input device that are active.
  33362. If useDefaultOutputChannels is true, this value is ignored.
  33363. */
  33364. BigInteger outputChannels;
  33365. /** If this is true, it indicates that the outputChannels array
  33366. should be ignored, and instead, the device's default channels
  33367. should be used.
  33368. */
  33369. bool useDefaultOutputChannels;
  33370. };
  33371. /** Opens a set of audio devices ready for use.
  33372. This will attempt to open either a default audio device, or one that was
  33373. previously saved as XML.
  33374. @param numInputChannelsNeeded a minimum number of input channels needed
  33375. by your app.
  33376. @param numOutputChannelsNeeded a minimum number of output channels to open
  33377. @param savedState either a previously-saved state that was produced
  33378. by createStateXml(), or 0 if you want the manager
  33379. to choose the best device to open.
  33380. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  33381. fails to open, then a default device will be used
  33382. instead. If false, then on failure, no device is
  33383. opened.
  33384. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  33385. name, then that will be used as the default device
  33386. (assuming that there wasn't one specified in the XML).
  33387. The string can actually be a simple wildcard, containing "*"
  33388. and "?" characters
  33389. @param preferredSetupOptions if this is non-null, the structure will be used as the
  33390. set of preferred settings when opening the device. If you
  33391. use this parameter, the preferredDefaultDeviceName
  33392. field will be ignored
  33393. @returns an error message if anything went wrong, or an empty string if it worked ok.
  33394. */
  33395. const String initialise (int numInputChannelsNeeded,
  33396. int numOutputChannelsNeeded,
  33397. const XmlElement* savedState,
  33398. bool selectDefaultDeviceOnFailure,
  33399. const String& preferredDefaultDeviceName = String::empty,
  33400. const AudioDeviceSetup* preferredSetupOptions = 0);
  33401. /** Returns some XML representing the current state of the manager.
  33402. This stores the current device, its samplerate, block size, etc, and
  33403. can be restored later with initialise().
  33404. */
  33405. XmlElement* createStateXml() const;
  33406. /** Returns the current device properties that are in use.
  33407. @see setAudioDeviceSetup
  33408. */
  33409. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  33410. /** Changes the current device or its settings.
  33411. If you want to change a device property, like the current sample rate or
  33412. block size, you can call getAudioDeviceSetup() to retrieve the current
  33413. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  33414. and pass it back into this method to apply the new settings.
  33415. @param newSetup the settings that you'd like to use
  33416. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  33417. settings will be taken as having been explicitly chosen by the
  33418. user, and the next time createStateXml() is called, these settings
  33419. will be returned. If it's false, then the device is treated as a
  33420. temporary or default device, and a call to createStateXml() will
  33421. return either the last settings that were made with treatAsChosenDevice
  33422. as true, or the last XML settings that were passed into initialise().
  33423. @returns an error message if anything went wrong, or an empty string if it worked ok.
  33424. @see getAudioDeviceSetup
  33425. */
  33426. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  33427. bool treatAsChosenDevice);
  33428. /** Returns the currently-active audio device. */
  33429. AudioIODevice* getCurrentAudioDevice() const noexcept { return currentAudioDevice; }
  33430. /** Returns the type of audio device currently in use.
  33431. @see setCurrentAudioDeviceType
  33432. */
  33433. const String getCurrentAudioDeviceType() const { return currentDeviceType; }
  33434. /** Returns the currently active audio device type object.
  33435. Don't keep a copy of this pointer - it's owned by the device manager and could
  33436. change at any time.
  33437. */
  33438. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  33439. /** Changes the class of audio device being used.
  33440. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  33441. this because there's only one type: CoreAudio.
  33442. For a list of types, see getAvailableDeviceTypes().
  33443. */
  33444. void setCurrentAudioDeviceType (const String& type,
  33445. bool treatAsChosenDevice);
  33446. /** Closes the currently-open device.
  33447. You can call restartLastAudioDevice() later to reopen it in the same state
  33448. that it was just in.
  33449. */
  33450. void closeAudioDevice();
  33451. /** Tries to reload the last audio device that was running.
  33452. Note that this only reloads the last device that was running before
  33453. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  33454. and can only be called after a device has been opened with SetAudioDevice().
  33455. If a device is already open, this call will do nothing.
  33456. */
  33457. void restartLastAudioDevice();
  33458. /** Registers an audio callback to be used.
  33459. The manager will redirect callbacks from whatever audio device is currently
  33460. in use to all registered callback objects. If more than one callback is
  33461. active, they will all be given the same input data, and their outputs will
  33462. be summed.
  33463. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  33464. object before returning.
  33465. To remove a callback, use removeAudioCallback().
  33466. */
  33467. void addAudioCallback (AudioIODeviceCallback* newCallback);
  33468. /** Deregisters a previously added callback.
  33469. If necessary, this method will invoke audioDeviceStopped() on the callback
  33470. object before returning.
  33471. @see addAudioCallback
  33472. */
  33473. void removeAudioCallback (AudioIODeviceCallback* callback);
  33474. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  33475. Returns a value between 0 and 1.0
  33476. */
  33477. double getCpuUsage() const;
  33478. /** Enables or disables a midi input device.
  33479. The list of devices can be obtained with the MidiInput::getDevices() method.
  33480. Any incoming messages from enabled input devices will be forwarded on to all the
  33481. listeners that have been registered with the addMidiInputCallback() method. They
  33482. can either register for messages from a particular device, or from just the
  33483. "default" midi input.
  33484. Routing the midi input via an AudioDeviceManager means that when a listener
  33485. registers for the default midi input, this default device can be changed by the
  33486. manager without the listeners having to know about it or re-register.
  33487. It also means that a listener can stay registered for a midi input that is disabled
  33488. or not present, so that when the input is re-enabled, the listener will start
  33489. receiving messages again.
  33490. @see addMidiInputCallback, isMidiInputEnabled
  33491. */
  33492. void setMidiInputEnabled (const String& midiInputDeviceName, bool enabled);
  33493. /** Returns true if a given midi input device is being used.
  33494. @see setMidiInputEnabled
  33495. */
  33496. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  33497. /** Registers a listener for callbacks when midi events arrive from a midi input.
  33498. The device name can be empty to indicate that it wants events from whatever the
  33499. current "default" device is. Or it can be the name of one of the midi input devices
  33500. (see MidiInput::getDevices() for the names).
  33501. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  33502. events forwarded on to listeners.
  33503. */
  33504. void addMidiInputCallback (const String& midiInputDeviceName,
  33505. MidiInputCallback* callback);
  33506. /** Removes a listener that was previously registered with addMidiInputCallback().
  33507. */
  33508. void removeMidiInputCallback (const String& midiInputDeviceName,
  33509. MidiInputCallback* callback);
  33510. /** Sets a midi output device to use as the default.
  33511. The list of devices can be obtained with the MidiOutput::getDevices() method.
  33512. The specified device will be opened automatically and can be retrieved with the
  33513. getDefaultMidiOutput() method.
  33514. Pass in an empty string to deselect all devices. For the default device, you
  33515. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  33516. @see getDefaultMidiOutput, getDefaultMidiOutputName
  33517. */
  33518. void setDefaultMidiOutput (const String& deviceName);
  33519. /** Returns the name of the default midi output.
  33520. @see setDefaultMidiOutput, getDefaultMidiOutput
  33521. */
  33522. const String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  33523. /** Returns the current default midi output device.
  33524. If no device has been selected, or the device can't be opened, this will
  33525. return 0.
  33526. @see getDefaultMidiOutputName
  33527. */
  33528. MidiOutput* getDefaultMidiOutput() const noexcept { return defaultMidiOutput; }
  33529. /** Returns a list of the types of device supported.
  33530. */
  33531. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  33532. /** Creates a list of available types.
  33533. This will add a set of new AudioIODeviceType objects to the specified list, to
  33534. represent each available types of device.
  33535. You can override this if your app needs to do something specific, like avoid
  33536. using DirectSound devices, etc.
  33537. */
  33538. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  33539. /** Plays a beep through the current audio device.
  33540. This is here to allow the audio setup UI panels to easily include a "test"
  33541. button so that the user can check where the audio is coming from.
  33542. */
  33543. void playTestSound();
  33544. /** Turns on level-measuring.
  33545. When enabled, the device manager will measure the peak input level
  33546. across all channels, and you can get this level by calling getCurrentInputLevel().
  33547. This is mainly intended for audio setup UI panels to use to create a mic
  33548. level display, so that the user can check that they've selected the right
  33549. device.
  33550. A simple filter is used to make the level decay smoothly, but this is
  33551. only intended for giving rough feedback, and not for any kind of accurate
  33552. measurement.
  33553. */
  33554. void enableInputLevelMeasurement (bool enableMeasurement);
  33555. /** Returns the current input level.
  33556. To use this, you must first enable it by calling enableInputLevelMeasurement().
  33557. See enableInputLevelMeasurement() for more info.
  33558. */
  33559. double getCurrentInputLevel() const;
  33560. /** Returns the a lock that can be used to synchronise access to the audio callback.
  33561. Obviously while this is locked, you're blocking the audio thread from running, so
  33562. it must only be used for very brief periods when absolutely necessary.
  33563. */
  33564. CriticalSection& getAudioCallbackLock() noexcept { return audioCallbackLock; }
  33565. /** Returns the a lock that can be used to synchronise access to the midi callback.
  33566. Obviously while this is locked, you're blocking the midi system from running, so
  33567. it must only be used for very brief periods when absolutely necessary.
  33568. */
  33569. CriticalSection& getMidiCallbackLock() noexcept { return midiCallbackLock; }
  33570. private:
  33571. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  33572. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  33573. AudioDeviceSetup currentSetup;
  33574. ScopedPointer <AudioIODevice> currentAudioDevice;
  33575. SortedSet <AudioIODeviceCallback*> callbacks;
  33576. int numInputChansNeeded, numOutputChansNeeded;
  33577. String currentDeviceType;
  33578. BigInteger inputChannels, outputChannels;
  33579. ScopedPointer <XmlElement> lastExplicitSettings;
  33580. mutable bool listNeedsScanning;
  33581. bool useInputNames;
  33582. int inputLevelMeasurementEnabledCount;
  33583. double inputLevel;
  33584. ScopedPointer <AudioSampleBuffer> testSound;
  33585. int testSoundPosition;
  33586. AudioSampleBuffer tempBuffer;
  33587. StringArray midiInsFromXml;
  33588. OwnedArray <MidiInput> enabledMidiInputs;
  33589. Array <MidiInputCallback*> midiCallbacks;
  33590. StringArray midiCallbackDevices;
  33591. String defaultMidiOutputName;
  33592. ScopedPointer <MidiOutput> defaultMidiOutput;
  33593. CriticalSection audioCallbackLock, midiCallbackLock;
  33594. double cpuUsageMs, timeToCpuScale;
  33595. class CallbackHandler : public AudioIODeviceCallback,
  33596. public MidiInputCallback
  33597. {
  33598. public:
  33599. void audioDeviceIOCallback (const float**, int, float**, int, int);
  33600. void audioDeviceAboutToStart (AudioIODevice*);
  33601. void audioDeviceStopped();
  33602. void handleIncomingMidiMessage (MidiInput*, const MidiMessage&);
  33603. AudioDeviceManager* owner;
  33604. };
  33605. CallbackHandler callbackHandler;
  33606. friend class CallbackHandler;
  33607. void audioDeviceIOCallbackInt (const float** inputChannelData, int totalNumInputChannels,
  33608. float** outputChannelData, int totalNumOutputChannels, int numSamples);
  33609. void audioDeviceAboutToStartInt (AudioIODevice*);
  33610. void audioDeviceStoppedInt();
  33611. void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
  33612. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  33613. const BigInteger& ins, const BigInteger& outs);
  33614. void stopDevice();
  33615. void updateXml();
  33616. void createDeviceTypesIfNeeded();
  33617. void scanDevicesIfNeeded();
  33618. void deleteCurrentDevice();
  33619. double chooseBestSampleRate (double preferred) const;
  33620. int chooseBestBufferSize (int preferred) const;
  33621. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  33622. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  33623. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager);
  33624. };
  33625. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  33626. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  33627. #endif
  33628. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  33629. #endif
  33630. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  33631. #endif
  33632. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  33633. #endif
  33634. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  33635. #endif
  33636. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  33637. /*** Start of inlined file: juce_Decibels.h ***/
  33638. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  33639. #define __JUCE_DECIBELS_JUCEHEADER__
  33640. /**
  33641. This class contains some helpful static methods for dealing with decibel values.
  33642. */
  33643. class Decibels
  33644. {
  33645. public:
  33646. /** Converts a dBFS value to its equivalent gain level.
  33647. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values. Any
  33648. decibel value lower than minusInfinityDb will return a gain of 0.
  33649. */
  33650. template <typename Type>
  33651. static Type decibelsToGain (const Type decibels,
  33652. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  33653. {
  33654. return decibels > minusInfinityDb ? powf ((Type) 10.0, decibels * (Type) 0.05)
  33655. : Type();
  33656. }
  33657. /** Converts a gain level into a dBFS value.
  33658. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values.
  33659. If the gain is 0 (or negative), then the method will return the value
  33660. provided as minusInfinityDb.
  33661. */
  33662. template <typename Type>
  33663. static Type gainToDecibels (const Type gain,
  33664. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  33665. {
  33666. return gain > Type() ? jmax (minusInfinityDb, (Type) std::log10 (gain) * (Type) 20.0)
  33667. : minusInfinityDb;
  33668. }
  33669. /** Converts a decibel reading to a string, with the 'dB' suffix.
  33670. If the decibel value is lower than minusInfinityDb, the return value will
  33671. be "-INF dB".
  33672. */
  33673. template <typename Type>
  33674. static const String toString (const Type decibels,
  33675. const int decimalPlaces = 2,
  33676. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  33677. {
  33678. String s;
  33679. if (decibels <= minusInfinityDb)
  33680. {
  33681. s = "-INF dB";
  33682. }
  33683. else
  33684. {
  33685. if (decibels >= Type())
  33686. s << '+';
  33687. s << String (decibels, decimalPlaces) << " dB";
  33688. }
  33689. return s;
  33690. }
  33691. private:
  33692. enum
  33693. {
  33694. defaultMinusInfinitydB = -100
  33695. };
  33696. Decibels(); // This class can't be instantiated, it's just a holder for static methods..
  33697. JUCE_DECLARE_NON_COPYABLE (Decibels);
  33698. };
  33699. #endif // __JUCE_DECIBELS_JUCEHEADER__
  33700. /*** End of inlined file: juce_Decibels.h ***/
  33701. #endif
  33702. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  33703. #endif
  33704. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  33705. #endif
  33706. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  33707. /*** Start of inlined file: juce_MidiFile.h ***/
  33708. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  33709. #define __JUCE_MIDIFILE_JUCEHEADER__
  33710. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  33711. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33712. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33713. /**
  33714. A sequence of timestamped midi messages.
  33715. This allows the sequence to be manipulated, and also to be read from and
  33716. written to a standard midi file.
  33717. @see MidiMessage, MidiFile
  33718. */
  33719. class JUCE_API MidiMessageSequence
  33720. {
  33721. public:
  33722. /** Creates an empty midi sequence object. */
  33723. MidiMessageSequence();
  33724. /** Creates a copy of another sequence. */
  33725. MidiMessageSequence (const MidiMessageSequence& other);
  33726. /** Replaces this sequence with another one. */
  33727. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  33728. /** Destructor. */
  33729. ~MidiMessageSequence();
  33730. /** Structure used to hold midi events in the sequence.
  33731. These structures act as 'handles' on the events as they are moved about in
  33732. the list, and make it quick to find the matching note-offs for note-on events.
  33733. @see MidiMessageSequence::getEventPointer
  33734. */
  33735. class MidiEventHolder
  33736. {
  33737. public:
  33738. /** Destructor. */
  33739. ~MidiEventHolder();
  33740. /** The message itself, whose timestamp is used to specify the event's time.
  33741. */
  33742. MidiMessage message;
  33743. /** The matching note-off event (if this is a note-on event).
  33744. If this isn't a note-on, this pointer will be null.
  33745. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  33746. note-offs up-to-date after events have been moved around in the sequence
  33747. or deleted.
  33748. */
  33749. MidiEventHolder* noteOffObject;
  33750. private:
  33751. friend class MidiMessageSequence;
  33752. MidiEventHolder (const MidiMessage& message);
  33753. JUCE_LEAK_DETECTOR (MidiEventHolder);
  33754. };
  33755. /** Clears the sequence. */
  33756. void clear();
  33757. /** Returns the number of events in the sequence. */
  33758. int getNumEvents() const;
  33759. /** Returns a pointer to one of the events. */
  33760. MidiEventHolder* getEventPointer (int index) const;
  33761. /** Returns the time of the note-up that matches the note-on at this index.
  33762. If the event at this index isn't a note-on, it'll just return 0.
  33763. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  33764. */
  33765. double getTimeOfMatchingKeyUp (int index) const;
  33766. /** Returns the index of the note-up that matches the note-on at this index.
  33767. If the event at this index isn't a note-on, it'll just return -1.
  33768. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  33769. */
  33770. int getIndexOfMatchingKeyUp (int index) const;
  33771. /** Returns the index of an event. */
  33772. int getIndexOf (MidiEventHolder* event) const;
  33773. /** Returns the index of the first event on or after the given timestamp.
  33774. If the time is beyond the end of the sequence, this will return the
  33775. number of events.
  33776. */
  33777. int getNextIndexAtTime (double timeStamp) const;
  33778. /** Returns the timestamp of the first event in the sequence.
  33779. @see getEndTime
  33780. */
  33781. double getStartTime() const;
  33782. /** Returns the timestamp of the last event in the sequence.
  33783. @see getStartTime
  33784. */
  33785. double getEndTime() const;
  33786. /** Returns the timestamp of the event at a given index.
  33787. If the index is out-of-range, this will return 0.0
  33788. */
  33789. double getEventTime (int index) const;
  33790. /** Inserts a midi message into the sequence.
  33791. The index at which the new message gets inserted will depend on its timestamp,
  33792. because the sequence is kept sorted.
  33793. Remember to call updateMatchedPairs() after adding note-on events.
  33794. @param newMessage the new message to add (an internal copy will be made)
  33795. @param timeAdjustment an optional value to add to the timestamp of the message
  33796. that will be inserted
  33797. @see updateMatchedPairs
  33798. */
  33799. void addEvent (const MidiMessage& newMessage,
  33800. double timeAdjustment = 0);
  33801. /** Deletes one of the events in the sequence.
  33802. Remember to call updateMatchedPairs() after removing events.
  33803. @param index the index of the event to delete
  33804. @param deleteMatchingNoteUp whether to also remove the matching note-off
  33805. if the event you're removing is a note-on
  33806. */
  33807. void deleteEvent (int index, bool deleteMatchingNoteUp);
  33808. /** Merges another sequence into this one.
  33809. Remember to call updateMatchedPairs() after using this method.
  33810. @param other the sequence to add from
  33811. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  33812. as they are read from the other sequence
  33813. @param firstAllowableDestTime events will not be added if their time is earlier
  33814. than this time. (This is after their time has been adjusted
  33815. by the timeAdjustmentDelta)
  33816. @param endOfAllowableDestTimes events will not be added if their time is equal to
  33817. or greater than this time. (This is after their time has
  33818. been adjusted by the timeAdjustmentDelta)
  33819. */
  33820. void addSequence (const MidiMessageSequence& other,
  33821. double timeAdjustmentDelta,
  33822. double firstAllowableDestTime,
  33823. double endOfAllowableDestTimes);
  33824. /** Makes sure all the note-on and note-off pairs are up-to-date.
  33825. Call this after moving messages about or deleting/adding messages, and it
  33826. will scan the list and make sure all the note-offs in the MidiEventHolder
  33827. structures are pointing at the correct ones.
  33828. */
  33829. void updateMatchedPairs();
  33830. /** Copies all the messages for a particular midi channel to another sequence.
  33831. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  33832. @param destSequence the sequence that the chosen events should be copied to
  33833. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  33834. channel) will also be copied across.
  33835. @see extractSysExMessages
  33836. */
  33837. void extractMidiChannelMessages (int channelNumberToExtract,
  33838. MidiMessageSequence& destSequence,
  33839. bool alsoIncludeMetaEvents) const;
  33840. /** Copies all midi sys-ex messages to another sequence.
  33841. @param destSequence this is the sequence to which any sys-exes in this sequence
  33842. will be added
  33843. @see extractMidiChannelMessages
  33844. */
  33845. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  33846. /** Removes any messages in this sequence that have a specific midi channel.
  33847. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  33848. */
  33849. void deleteMidiChannelMessages (int channelNumberToRemove);
  33850. /** Removes any sys-ex messages from this sequence.
  33851. */
  33852. void deleteSysExMessages();
  33853. /** Adds an offset to the timestamps of all events in the sequence.
  33854. @param deltaTime the amount to add to each timestamp.
  33855. */
  33856. void addTimeToMessages (double deltaTime);
  33857. /** Scans through the sequence to determine the state of any midi controllers at
  33858. a given time.
  33859. This will create a sequence of midi controller changes that can be
  33860. used to set all midi controllers to the state they would be in at the
  33861. specified time within this sequence.
  33862. As well as controllers, it will also recreate the midi program number
  33863. and pitch bend position.
  33864. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  33865. for other channels will be ignored.
  33866. @param time the time at which you want to find out the state - there are
  33867. no explicit units for this time measurement, it's the same units
  33868. as used for the timestamps of the messages
  33869. @param resultMessages an array to which midi controller-change messages will be added. This
  33870. will be the minimum number of controller changes to recreate the
  33871. state at the required time.
  33872. */
  33873. void createControllerUpdatesForTime (int channelNumber, double time,
  33874. OwnedArray<MidiMessage>& resultMessages);
  33875. /** Swaps this sequence with another one. */
  33876. void swapWith (MidiMessageSequence& other) noexcept;
  33877. /** @internal */
  33878. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  33879. const MidiMessageSequence::MidiEventHolder* second) noexcept;
  33880. private:
  33881. friend class MidiFile;
  33882. OwnedArray <MidiEventHolder> list;
  33883. void sort();
  33884. JUCE_LEAK_DETECTOR (MidiMessageSequence);
  33885. };
  33886. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33887. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  33888. /**
  33889. Reads/writes standard midi format files.
  33890. To read a midi file, create a MidiFile object and call its readFrom() method. You
  33891. can then get the individual midi tracks from it using the getTrack() method.
  33892. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  33893. to it using the addTrack() method, and then call its writeTo() method to stream
  33894. it out.
  33895. @see MidiMessageSequence
  33896. */
  33897. class JUCE_API MidiFile
  33898. {
  33899. public:
  33900. /** Creates an empty MidiFile object.
  33901. */
  33902. MidiFile();
  33903. /** Destructor. */
  33904. ~MidiFile();
  33905. /** Returns the number of tracks in the file.
  33906. @see getTrack, addTrack
  33907. */
  33908. int getNumTracks() const noexcept;
  33909. /** Returns a pointer to one of the tracks in the file.
  33910. @returns a pointer to the track, or 0 if the index is out-of-range
  33911. @see getNumTracks, addTrack
  33912. */
  33913. const MidiMessageSequence* getTrack (int index) const noexcept;
  33914. /** Adds a midi track to the file.
  33915. This will make its own internal copy of the sequence that is passed-in.
  33916. @see getNumTracks, getTrack
  33917. */
  33918. void addTrack (const MidiMessageSequence& trackSequence);
  33919. /** Removes all midi tracks from the file.
  33920. @see getNumTracks
  33921. */
  33922. void clear();
  33923. /** Returns the raw time format code that will be written to a stream.
  33924. After reading a midi file, this method will return the time-format that
  33925. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  33926. or setSmpteTimeFormat() methods.
  33927. If the value returned is positive, it indicates the number of midi ticks
  33928. per quarter-note - see setTicksPerQuarterNote().
  33929. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  33930. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  33931. */
  33932. short getTimeFormat() const noexcept;
  33933. /** Sets the time format to use when this file is written to a stream.
  33934. If this is called, the file will be written as bars/beats using the
  33935. specified resolution, rather than SMPTE absolute times, as would be
  33936. used if setSmpteTimeFormat() had been called instead.
  33937. @param ticksPerQuarterNote e.g. 96, 960
  33938. @see setSmpteTimeFormat
  33939. */
  33940. void setTicksPerQuarterNote (int ticksPerQuarterNote) noexcept;
  33941. /** Sets the time format to use when this file is written to a stream.
  33942. If this is called, the file will be written using absolute times, rather
  33943. than bars/beats as would be the case if setTicksPerBeat() had been called
  33944. instead.
  33945. @param framesPerSecond must be 24, 25, 29 or 30
  33946. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  33947. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  33948. timing, setSmpteTimeFormat (25, 40)
  33949. @see setTicksPerBeat
  33950. */
  33951. void setSmpteTimeFormat (int framesPerSecond,
  33952. int subframeResolution) noexcept;
  33953. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  33954. Useful for finding the positions of all the tempo changes in a file.
  33955. @param tempoChangeEvents a list to which all the events will be added
  33956. */
  33957. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  33958. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  33959. Useful for finding the positions of all the tempo changes in a file.
  33960. @param timeSigEvents a list to which all the events will be added
  33961. */
  33962. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  33963. /** Returns the latest timestamp in any of the tracks.
  33964. (Useful for finding the length of the file).
  33965. */
  33966. double getLastTimestamp() const;
  33967. /** Reads a midi file format stream.
  33968. After calling this, you can get the tracks that were read from the file by using the
  33969. getNumTracks() and getTrack() methods.
  33970. The timestamps of the midi events in the tracks will represent their positions in
  33971. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  33972. method.
  33973. @returns true if the stream was read successfully
  33974. */
  33975. bool readFrom (InputStream& sourceStream);
  33976. /** Writes the midi tracks as a standard midi file.
  33977. @returns true if the operation succeeded.
  33978. */
  33979. bool writeTo (OutputStream& destStream);
  33980. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  33981. This will use the midi time format and tempo/time signature info in the
  33982. tracks to convert all the timestamps to absolute values in seconds.
  33983. */
  33984. void convertTimestampTicksToSeconds();
  33985. private:
  33986. OwnedArray <MidiMessageSequence> tracks;
  33987. short timeFormat;
  33988. void readNextTrack (const uint8* data, int size);
  33989. void writeTrack (OutputStream& mainOut, int trackNum);
  33990. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiFile);
  33991. };
  33992. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  33993. /*** End of inlined file: juce_MidiFile.h ***/
  33994. #endif
  33995. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  33996. #endif
  33997. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33998. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  33999. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  34000. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  34001. class MidiKeyboardState;
  34002. /**
  34003. Receives events from a MidiKeyboardState object.
  34004. @see MidiKeyboardState
  34005. */
  34006. class JUCE_API MidiKeyboardStateListener
  34007. {
  34008. public:
  34009. MidiKeyboardStateListener() noexcept {}
  34010. virtual ~MidiKeyboardStateListener() {}
  34011. /** Called when one of the MidiKeyboardState's keys is pressed.
  34012. This will be called synchronously when the state is either processing a
  34013. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  34014. when a note is being played with its MidiKeyboardState::noteOn() method.
  34015. Note that this callback could happen from an audio callback thread, so be
  34016. careful not to block, and avoid any UI activity in the callback.
  34017. */
  34018. virtual void handleNoteOn (MidiKeyboardState* source,
  34019. int midiChannel, int midiNoteNumber, float velocity) = 0;
  34020. /** Called when one of the MidiKeyboardState's keys is released.
  34021. This will be called synchronously when the state is either processing a
  34022. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  34023. when a note is being played with its MidiKeyboardState::noteOff() method.
  34024. Note that this callback could happen from an audio callback thread, so be
  34025. careful not to block, and avoid any UI activity in the callback.
  34026. */
  34027. virtual void handleNoteOff (MidiKeyboardState* source,
  34028. int midiChannel, int midiNoteNumber) = 0;
  34029. };
  34030. /**
  34031. Represents a piano keyboard, keeping track of which keys are currently pressed.
  34032. This object can parse a stream of midi events, using them to update its idea
  34033. of which keys are pressed for each individiual midi channel.
  34034. When keys go up or down, it can broadcast these events to listener objects.
  34035. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  34036. methods, and midi messages for these events will be merged into the
  34037. midi stream that gets processed by processNextMidiBuffer().
  34038. */
  34039. class JUCE_API MidiKeyboardState
  34040. {
  34041. public:
  34042. MidiKeyboardState();
  34043. ~MidiKeyboardState();
  34044. /** Resets the state of the object.
  34045. All internal data for all the channels is reset, but no events are sent as a
  34046. result.
  34047. If you want to release any keys that are currently down, and to send out note-up
  34048. midi messages for this, use the allNotesOff() method instead.
  34049. */
  34050. void reset();
  34051. /** Returns true if the given midi key is currently held down for the given midi channel.
  34052. The channel number must be between 1 and 16. If you want to see if any notes are
  34053. on for a range of channels, use the isNoteOnForChannels() method.
  34054. */
  34055. bool isNoteOn (int midiChannel, int midiNoteNumber) const noexcept;
  34056. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  34057. The channel mask has a bit set for each midi channel you want to test for - bit
  34058. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  34059. If a note is on for at least one of the specified channels, this returns true.
  34060. */
  34061. bool isNoteOnForChannels (int midiChannelMask, int midiNoteNumber) const noexcept;
  34062. /** Turns a specified note on.
  34063. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  34064. next call to processNextMidiBuffer().
  34065. It will also trigger a synchronous callback to the listeners to tell them that the key has
  34066. gone down.
  34067. */
  34068. void noteOn (int midiChannel, int midiNoteNumber, float velocity);
  34069. /** Turns a specified note off.
  34070. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  34071. next call to processNextMidiBuffer().
  34072. It will also trigger a synchronous callback to the listeners to tell them that the key has
  34073. gone up.
  34074. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  34075. */
  34076. void noteOff (int midiChannel, int midiNoteNumber);
  34077. /** This will turn off any currently-down notes for the given midi channel.
  34078. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  34079. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  34080. and events being added to the midi stream.
  34081. */
  34082. void allNotesOff (int midiChannel);
  34083. /** Looks at a key-up/down event and uses it to update the state of this object.
  34084. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  34085. instead.
  34086. */
  34087. void processNextMidiEvent (const MidiMessage& message);
  34088. /** Scans a midi stream for up/down events and adds its own events to it.
  34089. This will look for any up/down events and use them to update the internal state,
  34090. synchronously making suitable callbacks to the listeners.
  34091. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  34092. and noteOff() calls will be added into the buffer.
  34093. Only the section of the buffer whose timestamps are between startSample and
  34094. (startSample + numSamples) will be affected, and any events added will be placed
  34095. between these times.
  34096. If you're going to use this method, you'll need to keep calling it regularly for
  34097. it to work satisfactorily.
  34098. To process a single midi event at a time, use the processNextMidiEvent() method
  34099. instead.
  34100. */
  34101. void processNextMidiBuffer (MidiBuffer& buffer,
  34102. int startSample,
  34103. int numSamples,
  34104. bool injectIndirectEvents);
  34105. /** Registers a listener for callbacks when keys go up or down.
  34106. @see removeListener
  34107. */
  34108. void addListener (MidiKeyboardStateListener* listener);
  34109. /** Deregisters a listener.
  34110. @see addListener
  34111. */
  34112. void removeListener (MidiKeyboardStateListener* listener);
  34113. private:
  34114. CriticalSection lock;
  34115. uint16 noteStates [128];
  34116. MidiBuffer eventsToAdd;
  34117. Array <MidiKeyboardStateListener*> listeners;
  34118. void noteOnInternal (int midiChannel, int midiNoteNumber, float velocity);
  34119. void noteOffInternal (int midiChannel, int midiNoteNumber);
  34120. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardState);
  34121. };
  34122. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  34123. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  34124. #endif
  34125. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  34126. #endif
  34127. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  34128. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  34129. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  34130. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  34131. /**
  34132. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  34133. processing by a block-based audio callback.
  34134. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  34135. so it can easily use a midi input or keyboard component as its source.
  34136. @see MidiMessage, MidiInput
  34137. */
  34138. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  34139. public MidiInputCallback
  34140. {
  34141. public:
  34142. /** Creates a MidiMessageCollector. */
  34143. MidiMessageCollector();
  34144. /** Destructor. */
  34145. ~MidiMessageCollector();
  34146. /** Clears any messages from the queue.
  34147. You need to call this method before starting to use the collector, so that
  34148. it knows the correct sample rate to use.
  34149. */
  34150. void reset (double sampleRate);
  34151. /** Takes an incoming real-time message and adds it to the queue.
  34152. The message's timestamp is taken, and it will be ready for retrieval as part
  34153. of the block returned by the next call to removeNextBlockOfMessages().
  34154. This method is fully thread-safe when overlapping calls are made with
  34155. removeNextBlockOfMessages().
  34156. */
  34157. void addMessageToQueue (const MidiMessage& message);
  34158. /** Removes all the pending messages from the queue as a buffer.
  34159. This will also correct the messages' timestamps to make sure they're in
  34160. the range 0 to numSamples - 1.
  34161. This call should be made regularly by something like an audio processing
  34162. callback, because the time that it happens is used in calculating the
  34163. midi event positions.
  34164. This method is fully thread-safe when overlapping calls are made with
  34165. addMessageToQueue().
  34166. */
  34167. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  34168. /** @internal */
  34169. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  34170. /** @internal */
  34171. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  34172. /** @internal */
  34173. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  34174. private:
  34175. double lastCallbackTime;
  34176. CriticalSection midiCallbackLock;
  34177. MidiBuffer incomingMessages;
  34178. double sampleRate;
  34179. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiMessageCollector);
  34180. };
  34181. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  34182. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  34183. #endif
  34184. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  34185. #endif
  34186. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  34187. #endif
  34188. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  34189. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  34190. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  34191. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  34192. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  34193. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  34194. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  34195. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  34196. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  34197. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  34198. /*** Start of inlined file: juce_AudioProcessor.h ***/
  34199. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  34200. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  34201. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  34202. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  34203. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  34204. class AudioProcessor;
  34205. /**
  34206. Base class for the component that acts as the GUI for an AudioProcessor.
  34207. Derive your editor component from this class, and create an instance of it
  34208. by overriding the AudioProcessor::createEditor() method.
  34209. @see AudioProcessor, GenericAudioProcessorEditor
  34210. */
  34211. class JUCE_API AudioProcessorEditor : public Component
  34212. {
  34213. protected:
  34214. /** Creates an editor for the specified processor.
  34215. */
  34216. AudioProcessorEditor (AudioProcessor* owner);
  34217. public:
  34218. /** Destructor. */
  34219. ~AudioProcessorEditor();
  34220. /** Returns a pointer to the processor that this editor represents. */
  34221. AudioProcessor* getAudioProcessor() const noexcept { return owner; }
  34222. private:
  34223. AudioProcessor* const owner;
  34224. JUCE_DECLARE_NON_COPYABLE (AudioProcessorEditor);
  34225. };
  34226. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  34227. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  34228. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  34229. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  34230. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  34231. class AudioProcessor;
  34232. /**
  34233. Base class for listeners that want to know about changes to an AudioProcessor.
  34234. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  34235. @see AudioProcessor
  34236. */
  34237. class JUCE_API AudioProcessorListener
  34238. {
  34239. public:
  34240. /** Destructor. */
  34241. virtual ~AudioProcessorListener() {}
  34242. /** Receives a callback when a parameter is changed.
  34243. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  34244. many audio processors will change their parameter during their audio callback.
  34245. This means that not only has your handler code got to be completely thread-safe,
  34246. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  34247. this event on your message thread, use this callback to trigger an AsyncUpdater
  34248. or ChangeBroadcaster which you can respond to on the message thread.
  34249. */
  34250. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  34251. int parameterIndex,
  34252. float newValue) = 0;
  34253. /** Called to indicate that something else in the plugin has changed, like its
  34254. program, number of parameters, etc.
  34255. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  34256. call it during their audio callback. This means that not only has your handler code
  34257. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  34258. blocking. If you need to handle this event on your message thread, use this callback
  34259. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  34260. message thread.
  34261. */
  34262. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  34263. /** Indicates that a parameter change gesture has started.
  34264. E.g. if the user is dragging a slider, this would be called when they first
  34265. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  34266. called when they release it.
  34267. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  34268. call it during their audio callback. This means that not only has your handler code
  34269. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  34270. blocking. If you need to handle this event on your message thread, use this callback
  34271. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  34272. message thread.
  34273. @see audioProcessorParameterChangeGestureEnd
  34274. */
  34275. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  34276. int parameterIndex);
  34277. /** Indicates that a parameter change gesture has finished.
  34278. E.g. if the user is dragging a slider, this would be called when they release
  34279. the mouse button.
  34280. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  34281. call it during their audio callback. This means that not only has your handler code
  34282. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  34283. blocking. If you need to handle this event on your message thread, use this callback
  34284. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  34285. message thread.
  34286. @see audioProcessorParameterChangeGestureBegin
  34287. */
  34288. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  34289. int parameterIndex);
  34290. };
  34291. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  34292. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  34293. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  34294. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  34295. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  34296. /**
  34297. A subclass of AudioPlayHead can supply information about the position and
  34298. status of a moving play head during audio playback.
  34299. One of these can be supplied to an AudioProcessor object so that it can find
  34300. out about the position of the audio that it is rendering.
  34301. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  34302. */
  34303. class JUCE_API AudioPlayHead
  34304. {
  34305. protected:
  34306. AudioPlayHead() {}
  34307. public:
  34308. virtual ~AudioPlayHead() {}
  34309. /** Frame rate types. */
  34310. enum FrameRateType
  34311. {
  34312. fps24 = 0,
  34313. fps25 = 1,
  34314. fps2997 = 2,
  34315. fps30 = 3,
  34316. fps2997drop = 4,
  34317. fps30drop = 5,
  34318. fpsUnknown = 99
  34319. };
  34320. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  34321. */
  34322. struct CurrentPositionInfo
  34323. {
  34324. /** The tempo in BPM */
  34325. double bpm;
  34326. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  34327. int timeSigNumerator;
  34328. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  34329. int timeSigDenominator;
  34330. /** The current play position, in seconds from the start of the edit. */
  34331. double timeInSeconds;
  34332. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  34333. double editOriginTime;
  34334. /** The current play position in pulses-per-quarter-note.
  34335. This is the number of quarter notes since the edit start.
  34336. */
  34337. double ppqPosition;
  34338. /** The position of the start of the last bar, in pulses-per-quarter-note.
  34339. This is the number of quarter notes from the start of the edit to the
  34340. start of the current bar.
  34341. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  34342. it's not available, the value will be 0.
  34343. */
  34344. double ppqPositionOfLastBarStart;
  34345. /** The video frame rate, if applicable. */
  34346. FrameRateType frameRate;
  34347. /** True if the transport is currently playing. */
  34348. bool isPlaying;
  34349. /** True if the transport is currently recording.
  34350. (When isRecording is true, then isPlaying will also be true).
  34351. */
  34352. bool isRecording;
  34353. bool operator== (const CurrentPositionInfo& other) const noexcept;
  34354. bool operator!= (const CurrentPositionInfo& other) const noexcept;
  34355. void resetToDefault();
  34356. };
  34357. /** Fills-in the given structure with details about the transport's
  34358. position at the start of the current processing block.
  34359. */
  34360. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  34361. };
  34362. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  34363. /*** End of inlined file: juce_AudioPlayHead.h ***/
  34364. /**
  34365. Base class for audio processing filters or plugins.
  34366. This is intended to act as a base class of audio filter that is general enough to
  34367. be wrapped as a VST, AU, RTAS, etc, or used internally.
  34368. It is also used by the plugin hosting code as the wrapper around an instance
  34369. of a loaded plugin.
  34370. Derive your filter class from this base class, and if you're building a plugin,
  34371. you should implement a global function called createPluginFilter() which creates
  34372. and returns a new instance of your subclass.
  34373. */
  34374. class JUCE_API AudioProcessor
  34375. {
  34376. protected:
  34377. /** Constructor.
  34378. You can also do your initialisation tasks in the initialiseFilterInfo()
  34379. call, which will be made after this object has been created.
  34380. */
  34381. AudioProcessor();
  34382. public:
  34383. /** Destructor. */
  34384. virtual ~AudioProcessor();
  34385. /** Returns the name of this processor.
  34386. */
  34387. virtual const String getName() const = 0;
  34388. /** Called before playback starts, to let the filter prepare itself.
  34389. The sample rate is the target sample rate, and will remain constant until
  34390. playback stops.
  34391. The estimatedSamplesPerBlock value is a HINT about the typical number of
  34392. samples that will be processed for each callback, but isn't any kind
  34393. of guarantee. The actual block sizes that the host uses may be different
  34394. each time the callback happens, and may be more or less than this value.
  34395. */
  34396. virtual void prepareToPlay (double sampleRate,
  34397. int estimatedSamplesPerBlock) = 0;
  34398. /** Called after playback has stopped, to let the filter free up any resources it
  34399. no longer needs.
  34400. */
  34401. virtual void releaseResources() = 0;
  34402. /** Renders the next block.
  34403. When this method is called, the buffer contains a number of channels which is
  34404. at least as great as the maximum number of input and output channels that
  34405. this filter is using. It will be filled with the filter's input data and
  34406. should be replaced with the filter's output.
  34407. So for example if your filter has 2 input channels and 4 output channels, then
  34408. the buffer will contain 4 channels, the first two being filled with the
  34409. input data. Your filter should read these, do its processing, and replace
  34410. the contents of all 4 channels with its output.
  34411. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  34412. all filled with data, and your filter should overwrite the first 2 of these
  34413. with its output. But be VERY careful not to write anything to the last 3
  34414. channels, as these might be mapped to memory that the host assumes is read-only!
  34415. Note that if you have more outputs than inputs, then only those channels that
  34416. correspond to an input channel are guaranteed to contain sensible data - e.g.
  34417. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  34418. but the last two channels may contain garbage, so you should be careful not to
  34419. let this pass through without being overwritten or cleared.
  34420. Also note that the buffer may have more channels than are strictly necessary,
  34421. but your should only read/write from the ones that your filter is supposed to
  34422. be using.
  34423. The number of samples in these buffers is NOT guaranteed to be the same for every
  34424. callback, and may be more or less than the estimated value given to prepareToPlay().
  34425. Your code must be able to cope with variable-sized blocks, or you're going to get
  34426. clicks and crashes!
  34427. If the filter is receiving a midi input, then the midiMessages array will be filled
  34428. with the midi messages for this block. Each message's timestamp will indicate the
  34429. message's time, as a number of samples from the start of the block.
  34430. Any messages left in the midi buffer when this method has finished are assumed to
  34431. be the filter's midi output. This means that your filter should be careful to
  34432. clear any incoming messages from the array if it doesn't want them to be passed-on.
  34433. Be very careful about what you do in this callback - it's going to be called by
  34434. the audio thread, so any kind of interaction with the UI is absolutely
  34435. out of the question. If you change a parameter in here and need to tell your UI to
  34436. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  34437. the UI components register as listeners, and then call sendChangeMessage() inside the
  34438. processBlock() method to send out an asynchronous message. You could also use
  34439. the AsyncUpdater class in a similar way.
  34440. */
  34441. virtual void processBlock (AudioSampleBuffer& buffer,
  34442. MidiBuffer& midiMessages) = 0;
  34443. /** Returns the current AudioPlayHead object that should be used to find
  34444. out the state and position of the playhead.
  34445. You can call this from your processBlock() method, and use the AudioPlayHead
  34446. object to get the details about the time of the start of the block currently
  34447. being processed.
  34448. If the host hasn't supplied a playhead object, this will return 0.
  34449. */
  34450. AudioPlayHead* getPlayHead() const noexcept { return playHead; }
  34451. /** Returns the current sample rate.
  34452. This can be called from your processBlock() method - it's not guaranteed
  34453. to be valid at any other time, and may return 0 if it's unknown.
  34454. */
  34455. double getSampleRate() const noexcept { return sampleRate; }
  34456. /** Returns the current typical block size that is being used.
  34457. This can be called from your processBlock() method - it's not guaranteed
  34458. to be valid at any other time.
  34459. Remember it's not the ONLY block size that may be used when calling
  34460. processBlock, it's just the normal one. The actual block sizes used may be
  34461. larger or smaller than this, and will vary between successive calls.
  34462. */
  34463. int getBlockSize() const noexcept { return blockSize; }
  34464. /** Returns the number of input channels that the host will be sending the filter.
  34465. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  34466. number of channels that your filter would prefer to have, and this method lets
  34467. you know how many the host is actually using.
  34468. Note that this method is only valid during or after the prepareToPlay()
  34469. method call. Until that point, the number of channels will be unknown.
  34470. */
  34471. int getNumInputChannels() const noexcept { return numInputChannels; }
  34472. /** Returns the number of output channels that the host will be sending the filter.
  34473. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  34474. number of channels that your filter would prefer to have, and this method lets
  34475. you know how many the host is actually using.
  34476. Note that this method is only valid during or after the prepareToPlay()
  34477. method call. Until that point, the number of channels will be unknown.
  34478. */
  34479. int getNumOutputChannels() const noexcept { return numOutputChannels; }
  34480. /** Returns the name of one of the input channels, as returned by the host.
  34481. The host might not supply very useful names for channels, and this might be
  34482. something like "1", "2", "left", "right", etc.
  34483. */
  34484. virtual const String getInputChannelName (int channelIndex) const = 0;
  34485. /** Returns the name of one of the output channels, as returned by the host.
  34486. The host might not supply very useful names for channels, and this might be
  34487. something like "1", "2", "left", "right", etc.
  34488. */
  34489. virtual const String getOutputChannelName (int channelIndex) const = 0;
  34490. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  34491. virtual bool isInputChannelStereoPair (int index) const = 0;
  34492. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  34493. virtual bool isOutputChannelStereoPair (int index) const = 0;
  34494. /** This returns the number of samples delay that the filter imposes on the audio
  34495. passing through it.
  34496. The host will call this to find the latency - the filter itself should set this value
  34497. by calling setLatencySamples() as soon as it can during its initialisation.
  34498. */
  34499. int getLatencySamples() const noexcept { return latencySamples; }
  34500. /** The filter should call this to set the number of samples delay that it introduces.
  34501. The filter should call this as soon as it can during initialisation, and can call it
  34502. later if the value changes.
  34503. */
  34504. void setLatencySamples (int newLatency);
  34505. /** Returns true if the processor wants midi messages. */
  34506. virtual bool acceptsMidi() const = 0;
  34507. /** Returns true if the processor produces midi messages. */
  34508. virtual bool producesMidi() const = 0;
  34509. /** This returns a critical section that will automatically be locked while the host
  34510. is calling the processBlock() method.
  34511. Use it from your UI or other threads to lock access to variables that are used
  34512. by the process callback, but obviously be careful not to keep it locked for
  34513. too long, because that could cause stuttering playback. If you need to do something
  34514. that'll take a long time and need the processing to stop while it happens, use the
  34515. suspendProcessing() method instead.
  34516. @see suspendProcessing
  34517. */
  34518. const CriticalSection& getCallbackLock() const noexcept { return callbackLock; }
  34519. /** Enables and disables the processing callback.
  34520. If you need to do something time-consuming on a thread and would like to make sure
  34521. the audio processing callback doesn't happen until you've finished, use this
  34522. to disable the callback and re-enable it again afterwards.
  34523. E.g.
  34524. @code
  34525. void loadNewPatch()
  34526. {
  34527. suspendProcessing (true);
  34528. ..do something that takes ages..
  34529. suspendProcessing (false);
  34530. }
  34531. @endcode
  34532. If the host tries to make an audio callback while processing is suspended, the
  34533. filter will return an empty buffer, but won't block the audio thread like it would
  34534. do if you use the getCallbackLock() critical section to synchronise access.
  34535. If you're going to use this, your processBlock() method must call isSuspended() and
  34536. check whether it's suspended or not. If it is, then it should skip doing any real
  34537. processing, either emitting silence or passing the input through unchanged.
  34538. @see getCallbackLock
  34539. */
  34540. void suspendProcessing (bool shouldBeSuspended);
  34541. /** Returns true if processing is currently suspended.
  34542. @see suspendProcessing
  34543. */
  34544. bool isSuspended() const noexcept { return suspended; }
  34545. /** A plugin can override this to be told when it should reset any playing voices.
  34546. The default implementation does nothing, but a host may call this to tell the
  34547. plugin that it should stop any tails or sounds that have been left running.
  34548. */
  34549. virtual void reset();
  34550. /** Returns true if the processor is being run in an offline mode for rendering.
  34551. If the processor is being run live on realtime signals, this returns false.
  34552. If the mode is unknown, this will assume it's realtime and return false.
  34553. This value may be unreliable until the prepareToPlay() method has been called,
  34554. and could change each time prepareToPlay() is called.
  34555. @see setNonRealtime()
  34556. */
  34557. bool isNonRealtime() const noexcept { return nonRealtime; }
  34558. /** Called by the host to tell this processor whether it's being used in a non-realime
  34559. capacity for offline rendering or bouncing.
  34560. Whatever value is passed-in will be
  34561. */
  34562. void setNonRealtime (bool isNonRealtime) noexcept;
  34563. /** Creates the filter's UI.
  34564. This can return 0 if you want a UI-less filter, in which case the host may create
  34565. a generic UI that lets the user twiddle the parameters directly.
  34566. If you do want to pass back a component, the component should be created and set to
  34567. the correct size before returning it. If you implement this method, you must
  34568. also implement the hasEditor() method and make it return true.
  34569. Remember not to do anything silly like allowing your filter to keep a pointer to
  34570. the component that gets created - it could be deleted later without any warning, which
  34571. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  34572. The correct way to handle the connection between an editor component and its
  34573. filter is to use something like a ChangeBroadcaster so that the editor can
  34574. register itself as a listener, and be told when a change occurs. This lets them
  34575. safely unregister themselves when they are deleted.
  34576. Here are a few things to bear in mind when writing an editor:
  34577. - Initially there won't be an editor, until the user opens one, or they might
  34578. not open one at all. Your filter mustn't rely on it being there.
  34579. - An editor object may be deleted and a replacement one created again at any time.
  34580. - It's safe to assume that an editor will be deleted before its filter.
  34581. @see hasEditor
  34582. */
  34583. virtual AudioProcessorEditor* createEditor() = 0;
  34584. /** Your filter must override this and return true if it can create an editor component.
  34585. @see createEditor
  34586. */
  34587. virtual bool hasEditor() const = 0;
  34588. /** Returns the active editor, if there is one.
  34589. Bear in mind this can return 0, even if an editor has previously been
  34590. opened.
  34591. */
  34592. AudioProcessorEditor* getActiveEditor() const noexcept { return activeEditor; }
  34593. /** Returns the active editor, or if there isn't one, it will create one.
  34594. This may call createEditor() internally to create the component.
  34595. */
  34596. AudioProcessorEditor* createEditorIfNeeded();
  34597. /** This must return the correct value immediately after the object has been
  34598. created, and mustn't change the number of parameters later.
  34599. */
  34600. virtual int getNumParameters() = 0;
  34601. /** Returns the name of a particular parameter. */
  34602. virtual const String getParameterName (int parameterIndex) = 0;
  34603. /** Called by the host to find out the value of one of the filter's parameters.
  34604. The host will expect the value returned to be between 0 and 1.0.
  34605. This could be called quite frequently, so try to make your code efficient.
  34606. It's also likely to be called by non-UI threads, so the code in here should
  34607. be thread-aware.
  34608. */
  34609. virtual float getParameter (int parameterIndex) = 0;
  34610. /** Returns the value of a parameter as a text string. */
  34611. virtual const String getParameterText (int parameterIndex) = 0;
  34612. /** The host will call this method to change the value of one of the filter's parameters.
  34613. The host may call this at any time, including during the audio processing
  34614. callback, so the filter has to process this very fast and avoid blocking.
  34615. If you want to set the value of a parameter internally, e.g. from your
  34616. editor component, then don't call this directly - instead, use the
  34617. setParameterNotifyingHost() method, which will also send a message to
  34618. the host telling it about the change. If the message isn't sent, the host
  34619. won't be able to automate your parameters properly.
  34620. The value passed will be between 0 and 1.0.
  34621. */
  34622. virtual void setParameter (int parameterIndex,
  34623. float newValue) = 0;
  34624. /** Your filter can call this when it needs to change one of its parameters.
  34625. This could happen when the editor or some other internal operation changes
  34626. a parameter. This method will call the setParameter() method to change the
  34627. value, and will then send a message to the host telling it about the change.
  34628. Note that to make sure the host correctly handles automation, you should call
  34629. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  34630. tell the host when the user has started and stopped changing the parameter.
  34631. */
  34632. void setParameterNotifyingHost (int parameterIndex,
  34633. float newValue);
  34634. /** Returns true if the host can automate this parameter.
  34635. By default, this returns true for all parameters.
  34636. */
  34637. virtual bool isParameterAutomatable (int parameterIndex) const;
  34638. /** Should return true if this parameter is a "meta" parameter.
  34639. A meta-parameter is a parameter that changes other params. It is used
  34640. by some hosts (e.g. AudioUnit hosts).
  34641. By default this returns false.
  34642. */
  34643. virtual bool isMetaParameter (int parameterIndex) const;
  34644. /** Sends a signal to the host to tell it that the user is about to start changing this
  34645. parameter.
  34646. This allows the host to know when a parameter is actively being held by the user, and
  34647. it may use this information to help it record automation.
  34648. If you call this, it must be matched by a later call to endParameterChangeGesture().
  34649. */
  34650. void beginParameterChangeGesture (int parameterIndex);
  34651. /** Tells the host that the user has finished changing this parameter.
  34652. This allows the host to know when a parameter is actively being held by the user, and
  34653. it may use this information to help it record automation.
  34654. A call to this method must follow a call to beginParameterChangeGesture().
  34655. */
  34656. void endParameterChangeGesture (int parameterIndex);
  34657. /** The filter can call this when something (apart from a parameter value) has changed.
  34658. It sends a hint to the host that something like the program, number of parameters,
  34659. etc, has changed, and that it should update itself.
  34660. */
  34661. void updateHostDisplay();
  34662. /** Returns the number of preset programs the filter supports.
  34663. The value returned must be valid as soon as this object is created, and
  34664. must not change over its lifetime.
  34665. This value shouldn't be less than 1.
  34666. */
  34667. virtual int getNumPrograms() = 0;
  34668. /** Returns the number of the currently active program.
  34669. */
  34670. virtual int getCurrentProgram() = 0;
  34671. /** Called by the host to change the current program.
  34672. */
  34673. virtual void setCurrentProgram (int index) = 0;
  34674. /** Must return the name of a given program. */
  34675. virtual const String getProgramName (int index) = 0;
  34676. /** Called by the host to rename a program.
  34677. */
  34678. virtual void changeProgramName (int index, const String& newName) = 0;
  34679. /** The host will call this method when it wants to save the filter's internal state.
  34680. This must copy any info about the filter's state into the block of memory provided,
  34681. so that the host can store this and later restore it using setStateInformation().
  34682. Note that there's also a getCurrentProgramStateInformation() method, which only
  34683. stores the current program, not the state of the entire filter.
  34684. See also the helper function copyXmlToBinary() for storing settings as XML.
  34685. @see getCurrentProgramStateInformation
  34686. */
  34687. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  34688. /** The host will call this method if it wants to save the state of just the filter's
  34689. current program.
  34690. Unlike getStateInformation, this should only return the current program's state.
  34691. Not all hosts support this, and if you don't implement it, the base class
  34692. method just calls getStateInformation() instead. If you do implement it, be
  34693. sure to also implement getCurrentProgramStateInformation.
  34694. @see getStateInformation, setCurrentProgramStateInformation
  34695. */
  34696. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  34697. /** This must restore the filter's state from a block of data previously created
  34698. using getStateInformation().
  34699. Note that there's also a setCurrentProgramStateInformation() method, which tries
  34700. to restore just the current program, not the state of the entire filter.
  34701. See also the helper function getXmlFromBinary() for loading settings as XML.
  34702. @see setCurrentProgramStateInformation
  34703. */
  34704. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  34705. /** The host will call this method if it wants to restore the state of just the filter's
  34706. current program.
  34707. Not all hosts support this, and if you don't implement it, the base class
  34708. method just calls setStateInformation() instead. If you do implement it, be
  34709. sure to also implement getCurrentProgramStateInformation.
  34710. @see setStateInformation, getCurrentProgramStateInformation
  34711. */
  34712. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  34713. /** Adds a listener that will be called when an aspect of this processor changes. */
  34714. void addListener (AudioProcessorListener* newListener);
  34715. /** Removes a previously added listener. */
  34716. void removeListener (AudioProcessorListener* listenerToRemove);
  34717. /** Tells the processor to use this playhead object.
  34718. The processor will not take ownership of the object, so the caller must delete it when
  34719. it is no longer being used.
  34720. */
  34721. void setPlayHead (AudioPlayHead* newPlayHead) noexcept;
  34722. /** Not for public use - this is called before deleting an editor component. */
  34723. void editorBeingDeleted (AudioProcessorEditor* editor) noexcept;
  34724. /** Not for public use - this is called to initialise the processor before playing. */
  34725. void setPlayConfigDetails (int numIns, int numOuts,
  34726. double sampleRate,
  34727. int blockSize) noexcept;
  34728. protected:
  34729. /** Helper function that just converts an xml element into a binary blob.
  34730. Use this in your filter's getStateInformation() method if you want to
  34731. store its state as xml.
  34732. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  34733. from a binary blob.
  34734. */
  34735. static void copyXmlToBinary (const XmlElement& xml,
  34736. JUCE_NAMESPACE::MemoryBlock& destData);
  34737. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  34738. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  34739. an XmlElement object that the caller must delete when no longer needed.
  34740. */
  34741. static XmlElement* getXmlFromBinary (const void* data, int sizeInBytes);
  34742. /** @internal */
  34743. AudioPlayHead* playHead;
  34744. /** @internal */
  34745. void sendParamChangeMessageToListeners (int parameterIndex, float newValue);
  34746. private:
  34747. Array <AudioProcessorListener*> listeners;
  34748. Component::SafePointer<AudioProcessorEditor> activeEditor;
  34749. double sampleRate;
  34750. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  34751. bool suspended, nonRealtime;
  34752. CriticalSection callbackLock, listenerLock;
  34753. #if JUCE_DEBUG
  34754. BigInteger changingParams;
  34755. #endif
  34756. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessor);
  34757. };
  34758. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  34759. /*** End of inlined file: juce_AudioProcessor.h ***/
  34760. /*** Start of inlined file: juce_PluginDescription.h ***/
  34761. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34762. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34763. /**
  34764. A small class to represent some facts about a particular type of plugin.
  34765. This class is for storing and managing the details about a plugin without
  34766. actually having to load an instance of it.
  34767. A KnownPluginList contains a list of PluginDescription objects.
  34768. @see KnownPluginList
  34769. */
  34770. class JUCE_API PluginDescription
  34771. {
  34772. public:
  34773. PluginDescription();
  34774. PluginDescription (const PluginDescription& other);
  34775. PluginDescription& operator= (const PluginDescription& other);
  34776. ~PluginDescription();
  34777. /** The name of the plugin. */
  34778. String name;
  34779. /** A more descriptive name for the plugin.
  34780. This may be the same as the 'name' field, but some plugins may provide an
  34781. alternative name.
  34782. */
  34783. String descriptiveName;
  34784. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  34785. */
  34786. String pluginFormatName;
  34787. /** A category, such as "Dynamics", "Reverbs", etc.
  34788. */
  34789. String category;
  34790. /** The manufacturer. */
  34791. String manufacturerName;
  34792. /** The version. This string doesn't have any particular format. */
  34793. String version;
  34794. /** Either the file containing the plugin module, or some other unique way
  34795. of identifying it.
  34796. E.g. for an AU, this would be an ID string that the component manager
  34797. could use to retrieve the plugin. For a VST, it's the file path.
  34798. */
  34799. String fileOrIdentifier;
  34800. /** The last time the plugin file was changed.
  34801. This is handy when scanning for new or changed plugins.
  34802. */
  34803. Time lastFileModTime;
  34804. /** A unique ID for the plugin.
  34805. Note that this might not be unique between formats, e.g. a VST and some
  34806. other format might actually have the same id.
  34807. @see createIdentifierString
  34808. */
  34809. int uid;
  34810. /** True if the plugin identifies itself as a synthesiser. */
  34811. bool isInstrument;
  34812. /** The number of inputs. */
  34813. int numInputChannels;
  34814. /** The number of outputs. */
  34815. int numOutputChannels;
  34816. /** Returns true if the two descriptions refer the the same plugin.
  34817. This isn't quite as simple as them just having the same file (because of
  34818. shell plugins).
  34819. */
  34820. bool isDuplicateOf (const PluginDescription& other) const;
  34821. /** Returns a string that can be saved and used to uniquely identify the
  34822. plugin again.
  34823. This contains less info than the XML encoding, and is independent of the
  34824. plugin's file location, so can be used to store a plugin ID for use
  34825. across different machines.
  34826. */
  34827. const String createIdentifierString() const;
  34828. /** Creates an XML object containing these details.
  34829. @see loadFromXml
  34830. */
  34831. XmlElement* createXml() const;
  34832. /** Reloads the info in this structure from an XML record that was previously
  34833. saved with createXML().
  34834. Returns true if the XML was a valid plugin description.
  34835. */
  34836. bool loadFromXml (const XmlElement& xml);
  34837. private:
  34838. JUCE_LEAK_DETECTOR (PluginDescription);
  34839. };
  34840. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34841. /*** End of inlined file: juce_PluginDescription.h ***/
  34842. /**
  34843. Base class for an active instance of a plugin.
  34844. This derives from the AudioProcessor class, and adds some extra functionality
  34845. that helps when wrapping dynamically loaded plugins.
  34846. @see AudioProcessor, AudioPluginFormat
  34847. */
  34848. class JUCE_API AudioPluginInstance : public AudioProcessor
  34849. {
  34850. public:
  34851. /** Destructor.
  34852. Make sure that you delete any UI components that belong to this plugin before
  34853. deleting the plugin.
  34854. */
  34855. virtual ~AudioPluginInstance();
  34856. /** Fills-in the appropriate parts of this plugin description object.
  34857. */
  34858. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  34859. /** Returns a pointer to some kind of platform-specific data about the plugin.
  34860. E.g. For a VST, this value can be cast to an AEffect*. For an AudioUnit, it can be
  34861. cast to an AudioUnit handle.
  34862. */
  34863. virtual void* getPlatformSpecificData();
  34864. protected:
  34865. AudioPluginInstance();
  34866. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginInstance);
  34867. };
  34868. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  34869. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  34870. class PluginDescription;
  34871. /**
  34872. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  34873. Use the static getNumFormats() and getFormat() calls to find the types
  34874. of format that are available.
  34875. */
  34876. class JUCE_API AudioPluginFormat
  34877. {
  34878. public:
  34879. /** Destructor. */
  34880. virtual ~AudioPluginFormat();
  34881. /** Returns the format name.
  34882. E.g. "VST", "AudioUnit", etc.
  34883. */
  34884. virtual const String getName() const = 0;
  34885. /** This tries to create descriptions for all the plugin types available in
  34886. a binary module file.
  34887. The file will be some kind of DLL or bundle.
  34888. Normally there will only be one type returned, but some plugins
  34889. (e.g. VST shells) can use a single DLL to create a set of different plugin
  34890. subtypes, so in that case, each subtype is returned as a separate object.
  34891. */
  34892. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  34893. const String& fileOrIdentifier) = 0;
  34894. /** Tries to recreate a type from a previously generated PluginDescription.
  34895. @see PluginDescription::createInstance
  34896. */
  34897. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  34898. /** Should do a quick check to see if this file or directory might be a plugin of
  34899. this format.
  34900. This is for searching for potential files, so it shouldn't actually try to
  34901. load the plugin or do anything time-consuming.
  34902. */
  34903. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  34904. /** Returns a readable version of the name of the plugin that this identifier refers to.
  34905. */
  34906. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  34907. /** Checks whether this plugin could possibly be loaded.
  34908. It doesn't actually need to load it, just to check whether the file or component
  34909. still exists.
  34910. */
  34911. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  34912. /** Searches a suggested set of directories for any plugins in this format.
  34913. The path might be ignored, e.g. by AUs, which are found by the OS rather
  34914. than manually.
  34915. */
  34916. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  34917. bool recursive) = 0;
  34918. /** Returns the typical places to look for this kind of plugin.
  34919. Note that if this returns no paths, it means that the format can't be scanned-for
  34920. (i.e. it's an internal format that doesn't live in files)
  34921. */
  34922. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  34923. protected:
  34924. AudioPluginFormat() noexcept;
  34925. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormat);
  34926. };
  34927. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  34928. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  34929. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  34930. /**
  34931. Implements a plugin format manager for AudioUnits.
  34932. */
  34933. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  34934. {
  34935. public:
  34936. AudioUnitPluginFormat();
  34937. ~AudioUnitPluginFormat();
  34938. const String getName() const { return "AudioUnit"; }
  34939. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34940. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34941. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34942. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  34943. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  34944. bool doesPluginStillExist (const PluginDescription& desc);
  34945. const FileSearchPath getDefaultLocationsToSearch();
  34946. private:
  34947. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginFormat);
  34948. };
  34949. #endif
  34950. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  34951. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  34952. #endif
  34953. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34954. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  34955. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34956. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34957. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  34958. // Sorry, this file is just a placeholder at the moment!...
  34959. /**
  34960. Implements a plugin format manager for DirectX plugins.
  34961. */
  34962. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  34963. {
  34964. public:
  34965. DirectXPluginFormat();
  34966. ~DirectXPluginFormat();
  34967. const String getName() const { return "DirectX"; }
  34968. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34969. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34970. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34971. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  34972. const FileSearchPath getDefaultLocationsToSearch();
  34973. private:
  34974. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectXPluginFormat);
  34975. };
  34976. #endif
  34977. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34978. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  34979. #endif
  34980. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34981. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  34982. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34983. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34984. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  34985. // Sorry, this file is just a placeholder at the moment!...
  34986. /**
  34987. Implements a plugin format manager for DirectX plugins.
  34988. */
  34989. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  34990. {
  34991. public:
  34992. LADSPAPluginFormat();
  34993. ~LADSPAPluginFormat();
  34994. const String getName() const { return "LADSPA"; }
  34995. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34996. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34997. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34998. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  34999. const FileSearchPath getDefaultLocationsToSearch();
  35000. private:
  35001. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LADSPAPluginFormat);
  35002. };
  35003. #endif
  35004. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  35005. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  35006. #endif
  35007. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  35008. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  35009. #ifdef __aeffect__
  35010. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  35011. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  35012. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  35013. events to the list.
  35014. This is used by both the VST hosting code and the plugin wrapper.
  35015. */
  35016. class VSTMidiEventList
  35017. {
  35018. public:
  35019. VSTMidiEventList()
  35020. : numEventsUsed (0), numEventsAllocated (0)
  35021. {
  35022. }
  35023. ~VSTMidiEventList()
  35024. {
  35025. freeEvents();
  35026. }
  35027. void clear()
  35028. {
  35029. numEventsUsed = 0;
  35030. if (events != nullptr)
  35031. events->numEvents = 0;
  35032. }
  35033. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  35034. {
  35035. ensureSize (numEventsUsed + 1);
  35036. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  35037. events->numEvents = ++numEventsUsed;
  35038. if (numBytes <= 4)
  35039. {
  35040. if (e->type == kVstSysExType)
  35041. {
  35042. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  35043. e->type = kVstMidiType;
  35044. e->byteSize = sizeof (VstMidiEvent);
  35045. e->noteLength = 0;
  35046. e->noteOffset = 0;
  35047. e->detune = 0;
  35048. e->noteOffVelocity = 0;
  35049. }
  35050. e->deltaFrames = frameOffset;
  35051. memcpy (e->midiData, midiData, numBytes);
  35052. }
  35053. else
  35054. {
  35055. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  35056. if (se->type == kVstSysExType)
  35057. delete[] se->sysexDump;
  35058. se->sysexDump = new char [numBytes];
  35059. memcpy (se->sysexDump, midiData, numBytes);
  35060. se->type = kVstSysExType;
  35061. se->byteSize = sizeof (VstMidiSysexEvent);
  35062. se->deltaFrames = frameOffset;
  35063. se->flags = 0;
  35064. se->dumpBytes = numBytes;
  35065. se->resvd1 = 0;
  35066. se->resvd2 = 0;
  35067. }
  35068. }
  35069. // Handy method to pull the events out of an event buffer supplied by the host
  35070. // or plugin.
  35071. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  35072. {
  35073. for (int i = 0; i < events->numEvents; ++i)
  35074. {
  35075. const VstEvent* const e = events->events[i];
  35076. if (e != nullptr)
  35077. {
  35078. if (e->type == kVstMidiType)
  35079. {
  35080. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  35081. 4, e->deltaFrames);
  35082. }
  35083. else if (e->type == kVstSysExType)
  35084. {
  35085. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  35086. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  35087. e->deltaFrames);
  35088. }
  35089. }
  35090. }
  35091. }
  35092. void ensureSize (int numEventsNeeded)
  35093. {
  35094. if (numEventsNeeded > numEventsAllocated)
  35095. {
  35096. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  35097. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  35098. if (events == nullptr)
  35099. events.calloc (size, 1);
  35100. else
  35101. events.realloc (size, 1);
  35102. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  35103. {
  35104. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  35105. (int) sizeof (VstMidiSysexEvent)));
  35106. e->type = kVstMidiType;
  35107. e->byteSize = sizeof (VstMidiEvent);
  35108. events->events[i] = (VstEvent*) e;
  35109. }
  35110. numEventsAllocated = numEventsNeeded;
  35111. }
  35112. }
  35113. void freeEvents()
  35114. {
  35115. if (events != nullptr)
  35116. {
  35117. for (int i = numEventsAllocated; --i >= 0;)
  35118. {
  35119. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  35120. if (e->type == kVstSysExType)
  35121. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  35122. juce_free (e);
  35123. }
  35124. events.free();
  35125. numEventsUsed = 0;
  35126. numEventsAllocated = 0;
  35127. }
  35128. }
  35129. HeapBlock <VstEvents> events;
  35130. private:
  35131. int numEventsUsed, numEventsAllocated;
  35132. };
  35133. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  35134. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  35135. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  35136. #endif
  35137. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  35138. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  35139. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  35140. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  35141. #if JUCE_PLUGINHOST_VST
  35142. /**
  35143. Implements a plugin format manager for VSTs.
  35144. */
  35145. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  35146. {
  35147. public:
  35148. VSTPluginFormat();
  35149. ~VSTPluginFormat();
  35150. const String getName() const { return "VST"; }
  35151. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  35152. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  35153. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  35154. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  35155. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  35156. bool doesPluginStillExist (const PluginDescription& desc);
  35157. const FileSearchPath getDefaultLocationsToSearch();
  35158. private:
  35159. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  35160. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginFormat);
  35161. };
  35162. #endif
  35163. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  35164. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  35165. #endif
  35166. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  35167. #endif
  35168. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  35169. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  35170. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  35171. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  35172. /**
  35173. This maintains a list of known AudioPluginFormats.
  35174. @see AudioPluginFormat
  35175. */
  35176. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  35177. {
  35178. public:
  35179. AudioPluginFormatManager();
  35180. /** Destructor. */
  35181. ~AudioPluginFormatManager();
  35182. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  35183. /** Adds any formats that it knows about, e.g. VST.
  35184. */
  35185. void addDefaultFormats();
  35186. /** Returns the number of types of format that are available.
  35187. Use getFormat() to get one of them.
  35188. */
  35189. int getNumFormats();
  35190. /** Returns one of the available formats.
  35191. @see getNumFormats
  35192. */
  35193. AudioPluginFormat* getFormat (int index);
  35194. /** Adds a format to the list.
  35195. The object passed in will be owned and deleted by the manager.
  35196. */
  35197. void addFormat (AudioPluginFormat* format);
  35198. /** Tries to load the type for this description, by trying all the formats
  35199. that this manager knows about.
  35200. The caller is responsible for deleting the object that is returned.
  35201. If it can't load the plugin, it returns 0 and leaves a message in the
  35202. errorMessage string.
  35203. */
  35204. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  35205. String& errorMessage) const;
  35206. /** Checks that the file or component for this plugin actually still exists.
  35207. (This won't try to load the plugin)
  35208. */
  35209. bool doesPluginStillExist (const PluginDescription& description) const;
  35210. private:
  35211. OwnedArray <AudioPluginFormat> formats;
  35212. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormatManager);
  35213. };
  35214. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  35215. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  35216. #endif
  35217. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  35218. #endif
  35219. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  35220. /*** Start of inlined file: juce_KnownPluginList.h ***/
  35221. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  35222. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  35223. /**
  35224. Manages a list of plugin types.
  35225. This can be easily edited, saved and loaded, and used to create instances of
  35226. the plugin types in it.
  35227. @see PluginListComponent
  35228. */
  35229. class JUCE_API KnownPluginList : public ChangeBroadcaster
  35230. {
  35231. public:
  35232. /** Creates an empty list.
  35233. */
  35234. KnownPluginList();
  35235. /** Destructor. */
  35236. ~KnownPluginList();
  35237. /** Clears the list. */
  35238. void clear();
  35239. /** Returns the number of types currently in the list.
  35240. @see getType
  35241. */
  35242. int getNumTypes() const noexcept { return types.size(); }
  35243. /** Returns one of the types.
  35244. @see getNumTypes
  35245. */
  35246. PluginDescription* getType (int index) const noexcept { return types [index]; }
  35247. /** Looks for a type in the list which comes from this file.
  35248. */
  35249. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const;
  35250. /** Looks for a type in the list which matches a plugin type ID.
  35251. The identifierString parameter must have been created by
  35252. PluginDescription::createIdentifierString().
  35253. */
  35254. PluginDescription* getTypeForIdentifierString (const String& identifierString) const;
  35255. /** Adds a type manually from its description. */
  35256. bool addType (const PluginDescription& type);
  35257. /** Removes a type. */
  35258. void removeType (int index);
  35259. /** Looks for all types that can be loaded from a given file, and adds them
  35260. to the list.
  35261. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  35262. re-tested if it's not already in the list, or if the file's modification
  35263. time has changed since the list was created. If dontRescanIfAlreadyInList is
  35264. false, the file will always be reloaded and tested.
  35265. Returns true if any new types were added, and all the types found in this
  35266. file (even if it was already known and hasn't been re-scanned) get returned
  35267. in the array.
  35268. */
  35269. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  35270. bool dontRescanIfAlreadyInList,
  35271. OwnedArray <PluginDescription>& typesFound,
  35272. AudioPluginFormat& formatToUse);
  35273. /** Returns true if the specified file is already known about and if it
  35274. hasn't been modified since our entry was created.
  35275. */
  35276. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const;
  35277. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  35278. If any types are found in the files, their descriptions are returned in the array.
  35279. */
  35280. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  35281. OwnedArray <PluginDescription>& typesFound);
  35282. /** Sort methods used to change the order of the plugins in the list.
  35283. */
  35284. enum SortMethod
  35285. {
  35286. defaultOrder = 0,
  35287. sortAlphabetically,
  35288. sortByCategory,
  35289. sortByManufacturer,
  35290. sortByFileSystemLocation
  35291. };
  35292. /** Adds all the plugin types to a popup menu so that the user can select one.
  35293. Depending on the sort method, it may add sub-menus for categories,
  35294. manufacturers, etc.
  35295. Use getIndexChosenByMenu() to find out the type that was chosen.
  35296. */
  35297. void addToMenu (PopupMenu& menu,
  35298. const SortMethod sortMethod) const;
  35299. /** Converts a menu item index that has been chosen into its index in this list.
  35300. Returns -1 if it's not an ID that was used.
  35301. @see addToMenu
  35302. */
  35303. int getIndexChosenByMenu (int menuResultCode) const;
  35304. /** Sorts the list. */
  35305. void sort (const SortMethod method);
  35306. /** Creates some XML that can be used to store the state of this list.
  35307. */
  35308. XmlElement* createXml() const;
  35309. /** Recreates the state of this list from its stored XML format.
  35310. */
  35311. void recreateFromXml (const XmlElement& xml);
  35312. private:
  35313. OwnedArray <PluginDescription> types;
  35314. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KnownPluginList);
  35315. };
  35316. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  35317. /*** End of inlined file: juce_KnownPluginList.h ***/
  35318. #endif
  35319. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  35320. #endif
  35321. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  35322. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  35323. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  35324. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  35325. /**
  35326. Scans a directory for plugins, and adds them to a KnownPluginList.
  35327. To use one of these, create it and call scanNextFile() repeatedly, until
  35328. it returns false.
  35329. */
  35330. class JUCE_API PluginDirectoryScanner
  35331. {
  35332. public:
  35333. /**
  35334. Creates a scanner.
  35335. @param listToAddResultsTo this will get the new types added to it.
  35336. @param formatToLookFor this is the type of format that you want to look for
  35337. @param directoriesToSearch the path to search
  35338. @param searchRecursively true to search recursively
  35339. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  35340. be used as a file to store the names of any plugins
  35341. that crash during initialisation. If there are
  35342. any plugins listed in it, then these will always
  35343. be scanned after all other possible files have
  35344. been tried - in this way, even if there's a few
  35345. dodgy plugins in your path, then a couple of rescans
  35346. will still manage to find all the proper plugins.
  35347. It's probably best to choose a file in the user's
  35348. application data directory (alongside your app's
  35349. settings file) for this. The file format it uses
  35350. is just a list of filenames of the modules that
  35351. failed.
  35352. */
  35353. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  35354. AudioPluginFormat& formatToLookFor,
  35355. FileSearchPath directoriesToSearch,
  35356. bool searchRecursively,
  35357. const File& deadMansPedalFile);
  35358. /** Destructor. */
  35359. ~PluginDirectoryScanner();
  35360. /** Tries the next likely-looking file.
  35361. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  35362. re-tested if it's not already in the list, or if the file's modification
  35363. time has changed since the list was created. If dontRescanIfAlreadyInList is
  35364. false, the file will always be reloaded and tested.
  35365. Returns false when there are no more files to try.
  35366. */
  35367. bool scanNextFile (bool dontRescanIfAlreadyInList);
  35368. /** Skips over the next file without scanning it.
  35369. Returns false when there are no more files to try.
  35370. */
  35371. bool skipNextFile();
  35372. /** Returns the description of the plugin that will be scanned during the next
  35373. call to scanNextFile().
  35374. This is handy if you want to show the user which file is currently getting
  35375. scanned.
  35376. */
  35377. const String getNextPluginFileThatWillBeScanned() const;
  35378. /** Returns the estimated progress, between 0 and 1.
  35379. */
  35380. float getProgress() const { return progress; }
  35381. /** This returns a list of all the filenames of things that looked like being
  35382. a plugin file, but which failed to open for some reason.
  35383. */
  35384. const StringArray& getFailedFiles() const noexcept { return failedFiles; }
  35385. private:
  35386. KnownPluginList& list;
  35387. AudioPluginFormat& format;
  35388. StringArray filesOrIdentifiersToScan;
  35389. File deadMansPedalFile;
  35390. StringArray failedFiles;
  35391. int nextIndex;
  35392. float progress;
  35393. const StringArray getDeadMansPedalFile();
  35394. void setDeadMansPedalFile (const StringArray& newContents);
  35395. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginDirectoryScanner);
  35396. };
  35397. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  35398. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  35399. #endif
  35400. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35401. /*** Start of inlined file: juce_PluginListComponent.h ***/
  35402. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35403. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35404. /*** Start of inlined file: juce_ListBox.h ***/
  35405. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  35406. #define __JUCE_LISTBOX_JUCEHEADER__
  35407. class ListViewport;
  35408. /**
  35409. A subclass of this is used to drive a ListBox.
  35410. @see ListBox
  35411. */
  35412. class JUCE_API ListBoxModel
  35413. {
  35414. public:
  35415. /** Destructor. */
  35416. virtual ~ListBoxModel() {}
  35417. /** This has to return the number of items in the list.
  35418. @see ListBox::getNumRows()
  35419. */
  35420. virtual int getNumRows() = 0;
  35421. /** This method must be implemented to draw a row of the list.
  35422. */
  35423. virtual void paintListBoxItem (int rowNumber,
  35424. Graphics& g,
  35425. int width, int height,
  35426. bool rowIsSelected) = 0;
  35427. /** This is used to create or update a custom component to go in a row of the list.
  35428. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  35429. and handle mouse clicks with listBoxItemClicked().
  35430. This method will be called whenever a custom component might need to be updated - e.g.
  35431. when the table is changed, or TableListBox::updateContent() is called.
  35432. If you don't need a custom component for the specified row, then return 0.
  35433. If you do want a custom component, and the existingComponentToUpdate is null, then
  35434. this method must create a suitable new component and return it.
  35435. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  35436. by this method. In this case, the method must either update it to make sure it's correctly representing
  35437. the given row (which may be different from the one that the component was created for), or it can
  35438. delete this component and return a new one.
  35439. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  35440. */
  35441. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  35442. Component* existingComponentToUpdate);
  35443. /** This can be overridden to react to the user clicking on a row.
  35444. @see listBoxItemDoubleClicked
  35445. */
  35446. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  35447. /** This can be overridden to react to the user double-clicking on a row.
  35448. @see listBoxItemClicked
  35449. */
  35450. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  35451. /** This can be overridden to react to the user double-clicking on a part of the list where
  35452. there are no rows.
  35453. @see listBoxItemClicked
  35454. */
  35455. virtual void backgroundClicked();
  35456. /** Override this to be informed when rows are selected or deselected.
  35457. This will be called whenever a row is selected or deselected. If a range of
  35458. rows is selected all at once, this will just be called once for that event.
  35459. @param lastRowSelected the last row that the user selected. If no
  35460. rows are currently selected, this may be -1.
  35461. */
  35462. virtual void selectedRowsChanged (int lastRowSelected);
  35463. /** Override this to be informed when the delete key is pressed.
  35464. If no rows are selected when they press the key, this won't be called.
  35465. @param lastRowSelected the last row that had been selected when they pressed the
  35466. key - if there are multiple selections, this might not be
  35467. very useful
  35468. */
  35469. virtual void deleteKeyPressed (int lastRowSelected);
  35470. /** Override this to be informed when the return key is pressed.
  35471. If no rows are selected when they press the key, this won't be called.
  35472. @param lastRowSelected the last row that had been selected when they pressed the
  35473. key - if there are multiple selections, this might not be
  35474. very useful
  35475. */
  35476. virtual void returnKeyPressed (int lastRowSelected);
  35477. /** Override this to be informed when the list is scrolled.
  35478. This might be caused by the user moving the scrollbar, or by programmatic changes
  35479. to the list position.
  35480. */
  35481. virtual void listWasScrolled();
  35482. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  35483. If this returns a non-null variant then when the user drags a row, the listbox will
  35484. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  35485. a drag-and-drop operation, using this string as the source description, with the listbox
  35486. itself as the source component.
  35487. @see DragAndDropContainer::startDragging
  35488. */
  35489. virtual const var getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  35490. /** You can override this to provide tool tips for specific rows.
  35491. @see TooltipClient
  35492. */
  35493. virtual const String getTooltipForRow (int row);
  35494. };
  35495. /**
  35496. A list of items that can be scrolled vertically.
  35497. To create a list, you'll need to create a subclass of ListBoxModel. This can
  35498. either paint each row of the list and respond to events via callbacks, or for
  35499. more specialised tasks, it can supply a custom component to fill each row.
  35500. @see ComboBox, TableListBox
  35501. */
  35502. class JUCE_API ListBox : public Component,
  35503. public SettableTooltipClient
  35504. {
  35505. public:
  35506. /** Creates a ListBox.
  35507. The model pointer passed-in can be null, in which case you can set it later
  35508. with setModel().
  35509. */
  35510. ListBox (const String& componentName = String::empty,
  35511. ListBoxModel* model = 0);
  35512. /** Destructor. */
  35513. ~ListBox();
  35514. /** Changes the current data model to display. */
  35515. void setModel (ListBoxModel* newModel);
  35516. /** Returns the current list model. */
  35517. ListBoxModel* getModel() const noexcept { return model; }
  35518. /** Causes the list to refresh its content.
  35519. Call this when the number of rows in the list changes, or if you want it
  35520. to call refreshComponentForRow() on all the row components.
  35521. Be careful not to call it from a different thread, though, as it's not
  35522. thread-safe.
  35523. */
  35524. void updateContent();
  35525. /** Turns on multiple-selection of rows.
  35526. By default this is disabled.
  35527. When your row component gets clicked you'll need to call the
  35528. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  35529. clicked and to get it to do the appropriate selection based on whether
  35530. the ctrl/shift keys are held down.
  35531. */
  35532. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  35533. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  35534. This function is here primarily for the ComboBox class to use, but might be
  35535. useful for some other purpose too.
  35536. */
  35537. void setMouseMoveSelectsRows (bool shouldSelect);
  35538. /** Selects a row.
  35539. If the row is already selected, this won't do anything.
  35540. @param rowNumber the row to select
  35541. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  35542. the selected row is off-screen, it'll scroll to make
  35543. sure that row is on-screen
  35544. @param deselectOthersFirst if true and there are multiple selections, these will
  35545. first be deselected before this item is selected
  35546. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  35547. deselectAllRows, selectRangeOfRows
  35548. */
  35549. void selectRow (int rowNumber,
  35550. bool dontScrollToShowThisRow = false,
  35551. bool deselectOthersFirst = true);
  35552. /** Selects a set of rows.
  35553. This will add these rows to the current selection, so you might need to
  35554. clear the current selection first with deselectAllRows()
  35555. @param firstRow the first row to select (inclusive)
  35556. @param lastRow the last row to select (inclusive)
  35557. */
  35558. void selectRangeOfRows (int firstRow,
  35559. int lastRow);
  35560. /** Deselects a row.
  35561. If it's not currently selected, this will do nothing.
  35562. @see selectRow, deselectAllRows
  35563. */
  35564. void deselectRow (int rowNumber);
  35565. /** Deselects any currently selected rows.
  35566. @see deselectRow
  35567. */
  35568. void deselectAllRows();
  35569. /** Selects or deselects a row.
  35570. If the row's currently selected, this deselects it, and vice-versa.
  35571. */
  35572. void flipRowSelection (int rowNumber);
  35573. /** Returns a sparse set indicating the rows that are currently selected.
  35574. @see setSelectedRows
  35575. */
  35576. const SparseSet<int> getSelectedRows() const;
  35577. /** Sets the rows that should be selected, based on an explicit set of ranges.
  35578. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  35579. method will be called. If it's false, no notification will be sent to the model.
  35580. @see getSelectedRows
  35581. */
  35582. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  35583. bool sendNotificationEventToModel = true);
  35584. /** Checks whether a row is selected.
  35585. */
  35586. bool isRowSelected (int rowNumber) const;
  35587. /** Returns the number of rows that are currently selected.
  35588. @see getSelectedRow, isRowSelected, getLastRowSelected
  35589. */
  35590. int getNumSelectedRows() const;
  35591. /** Returns the row number of a selected row.
  35592. This will return the row number of the Nth selected row. The row numbers returned will
  35593. be sorted in order from low to high.
  35594. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  35595. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  35596. selected
  35597. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  35598. */
  35599. int getSelectedRow (int index = 0) const;
  35600. /** Returns the last row that the user selected.
  35601. This isn't the same as the highest row number that is currently selected - if the user
  35602. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  35603. If nothing is selected, it will return -1.
  35604. */
  35605. int getLastRowSelected() const;
  35606. /** Multiply-selects rows based on the modifier keys.
  35607. If no modifier keys are down, this will select the given row and
  35608. deselect any others.
  35609. If the ctrl (or command on the Mac) key is down, it'll flip the
  35610. state of the selected row.
  35611. If the shift key is down, it'll select up to the given row from the
  35612. last row selected.
  35613. @see selectRow
  35614. */
  35615. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  35616. const ModifierKeys& modifiers,
  35617. bool isMouseUpEvent);
  35618. /** Scrolls the list to a particular position.
  35619. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  35620. 1.0 scrolls to the bottom.
  35621. If the total number of rows all fit onto the screen at once, then this
  35622. method won't do anything.
  35623. @see getVerticalPosition
  35624. */
  35625. void setVerticalPosition (double newProportion);
  35626. /** Returns the current vertical position as a proportion of the total.
  35627. This can be used in conjunction with setVerticalPosition() to save and restore
  35628. the list's position. It returns a value in the range 0 to 1.
  35629. @see setVerticalPosition
  35630. */
  35631. double getVerticalPosition() const;
  35632. /** Scrolls if necessary to make sure that a particular row is visible.
  35633. */
  35634. void scrollToEnsureRowIsOnscreen (int row);
  35635. /** Returns a pointer to the scrollbar.
  35636. (Unlikely to be useful for most people).
  35637. */
  35638. ScrollBar* getVerticalScrollBar() const noexcept;
  35639. /** Returns a pointer to the scrollbar.
  35640. (Unlikely to be useful for most people).
  35641. */
  35642. ScrollBar* getHorizontalScrollBar() const noexcept;
  35643. /** Finds the row index that contains a given x,y position.
  35644. The position is relative to the ListBox's top-left.
  35645. If no row exists at this position, the method will return -1.
  35646. @see getComponentForRowNumber
  35647. */
  35648. int getRowContainingPosition (int x, int y) const noexcept;
  35649. /** Finds a row index that would be the most suitable place to insert a new
  35650. item for a given position.
  35651. This is useful when the user is e.g. dragging and dropping onto the listbox,
  35652. because it lets you easily choose the best position to insert the item that
  35653. they drop, based on where they drop it.
  35654. If the position is out of range, this will return -1. If the position is
  35655. beyond the end of the list, it will return getNumRows() to indicate the end
  35656. of the list.
  35657. @see getComponentForRowNumber
  35658. */
  35659. int getInsertionIndexForPosition (int x, int y) const noexcept;
  35660. /** Returns the position of one of the rows, relative to the top-left of
  35661. the listbox.
  35662. This may be off-screen, and the range of the row number that is passed-in is
  35663. not checked to see if it's a valid row.
  35664. */
  35665. const Rectangle<int> getRowPosition (int rowNumber,
  35666. bool relativeToComponentTopLeft) const noexcept;
  35667. /** Finds the row component for a given row in the list.
  35668. The component returned will have been created using createRowComponent().
  35669. If the component for this row is off-screen or if the row is out-of-range,
  35670. this will return 0.
  35671. @see getRowContainingPosition
  35672. */
  35673. Component* getComponentForRowNumber (int rowNumber) const noexcept;
  35674. /** Returns the row number that the given component represents.
  35675. If the component isn't one of the list's rows, this will return -1.
  35676. */
  35677. int getRowNumberOfComponent (Component* rowComponent) const noexcept;
  35678. /** Returns the width of a row (which may be less than the width of this component
  35679. if there's a scrollbar).
  35680. */
  35681. int getVisibleRowWidth() const noexcept;
  35682. /** Sets the height of each row in the list.
  35683. The default height is 22 pixels.
  35684. @see getRowHeight
  35685. */
  35686. void setRowHeight (int newHeight);
  35687. /** Returns the height of a row in the list.
  35688. @see setRowHeight
  35689. */
  35690. int getRowHeight() const noexcept { return rowHeight; }
  35691. /** Returns the number of rows actually visible.
  35692. This is the number of whole rows which will fit on-screen, so the value might
  35693. be more than the actual number of rows in the list.
  35694. */
  35695. int getNumRowsOnScreen() const noexcept;
  35696. /** A set of colour IDs to use to change the colour of various aspects of the label.
  35697. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35698. methods.
  35699. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35700. */
  35701. enum ColourIds
  35702. {
  35703. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  35704. Make this transparent if you don't want the background to be filled. */
  35705. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  35706. Make this transparent to not have an outline. */
  35707. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  35708. };
  35709. /** Sets the thickness of a border that will be drawn around the box.
  35710. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  35711. @see outlineColourId
  35712. */
  35713. void setOutlineThickness (int outlineThickness);
  35714. /** Returns the thickness of outline that will be drawn around the listbox.
  35715. @see setOutlineColour
  35716. */
  35717. int getOutlineThickness() const noexcept { return outlineThickness; }
  35718. /** Sets a component that the list should use as a header.
  35719. This will position the given component at the top of the list, maintaining the
  35720. height of the component passed-in, but rescaling it horizontally to match the
  35721. width of the items in the listbox.
  35722. The component will be deleted when setHeaderComponent() is called with a
  35723. different component, or when the listbox is deleted.
  35724. */
  35725. void setHeaderComponent (Component* newHeaderComponent);
  35726. /** Changes the width of the rows in the list.
  35727. This can be used to make the list's row components wider than the list itself - the
  35728. width of the rows will be either the width of the list or this value, whichever is
  35729. greater, and if the rows become wider than the list, a horizontal scrollbar will
  35730. appear.
  35731. The default value for this is 0, which means that the rows will always
  35732. be the same width as the list.
  35733. */
  35734. void setMinimumContentWidth (int newMinimumWidth);
  35735. /** Returns the space currently available for the row items, taking into account
  35736. borders, scrollbars, etc.
  35737. */
  35738. int getVisibleContentWidth() const noexcept;
  35739. /** Repaints one of the rows.
  35740. This is a lightweight alternative to calling updateContent, and just causes a
  35741. repaint of the row's area.
  35742. */
  35743. void repaintRow (int rowNumber) noexcept;
  35744. /** This fairly obscure method creates an image that just shows the currently
  35745. selected row components.
  35746. It's a handy method for doing drag-and-drop, as it can be passed to the
  35747. DragAndDropContainer for use as the drag image.
  35748. Note that it will make the row components temporarily invisible, so if you're
  35749. using custom components this could affect them if they're sensitive to that
  35750. sort of thing.
  35751. @see Component::createComponentSnapshot
  35752. */
  35753. virtual const Image createSnapshotOfSelectedRows (int& x, int& y);
  35754. /** Returns the viewport that this ListBox uses.
  35755. You may need to use this to change parameters such as whether scrollbars
  35756. are shown, etc.
  35757. */
  35758. Viewport* getViewport() const noexcept;
  35759. /** @internal */
  35760. bool keyPressed (const KeyPress& key);
  35761. /** @internal */
  35762. bool keyStateChanged (bool isKeyDown);
  35763. /** @internal */
  35764. void paint (Graphics& g);
  35765. /** @internal */
  35766. void paintOverChildren (Graphics& g);
  35767. /** @internal */
  35768. void resized();
  35769. /** @internal */
  35770. void visibilityChanged();
  35771. /** @internal */
  35772. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  35773. /** @internal */
  35774. void mouseMove (const MouseEvent&);
  35775. /** @internal */
  35776. void mouseExit (const MouseEvent&);
  35777. /** @internal */
  35778. void mouseUp (const MouseEvent&);
  35779. /** @internal */
  35780. void colourChanged();
  35781. /** @internal */
  35782. void startDragAndDrop (const MouseEvent& e, const var& dragDescription, bool allowDraggingToOtherWindows = true);
  35783. private:
  35784. friend class ListViewport;
  35785. friend class TableListBox;
  35786. ListBoxModel* model;
  35787. ScopedPointer<ListViewport> viewport;
  35788. ScopedPointer<Component> headerComponent;
  35789. int totalItems, rowHeight, minimumRowWidth;
  35790. int outlineThickness;
  35791. int lastRowSelected;
  35792. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  35793. SparseSet <int> selected;
  35794. void selectRowInternal (int rowNumber,
  35795. bool dontScrollToShowThisRow,
  35796. bool deselectOthersFirst,
  35797. bool isMouseClick);
  35798. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBox);
  35799. };
  35800. #endif // __JUCE_LISTBOX_JUCEHEADER__
  35801. /*** End of inlined file: juce_ListBox.h ***/
  35802. /*** Start of inlined file: juce_TextButton.h ***/
  35803. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  35804. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  35805. /**
  35806. A button that uses the standard lozenge-shaped background with a line of
  35807. text on it.
  35808. @see Button, DrawableButton
  35809. */
  35810. class JUCE_API TextButton : public Button
  35811. {
  35812. public:
  35813. /** Creates a TextButton.
  35814. @param buttonName the text to put in the button (the component's name is also
  35815. initially set to this string, but these can be changed later
  35816. using the setName() and setButtonText() methods)
  35817. @param toolTip an optional string to use as a toolip
  35818. @see Button
  35819. */
  35820. TextButton (const String& buttonName = String::empty,
  35821. const String& toolTip = String::empty);
  35822. /** Destructor. */
  35823. ~TextButton();
  35824. /** A set of colour IDs to use to change the colour of various aspects of the button.
  35825. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35826. methods.
  35827. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35828. */
  35829. enum ColourIds
  35830. {
  35831. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  35832. 'off'). The look-and-feel class might re-interpret this to add
  35833. effects, etc. */
  35834. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  35835. 'on'). The look-and-feel class might re-interpret this to add
  35836. effects, etc. */
  35837. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  35838. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  35839. };
  35840. /** Resizes the button to fit neatly around its current text.
  35841. If newHeight is >= 0, the button's height will be changed to this
  35842. value. If it's less than zero, its height will be unaffected.
  35843. */
  35844. void changeWidthToFitText (int newHeight = -1);
  35845. /** This can be overridden to use different fonts than the default one.
  35846. Note that you'll need to set the font's size appropriately, too.
  35847. */
  35848. virtual const Font getFont();
  35849. protected:
  35850. /** @internal */
  35851. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  35852. /** @internal */
  35853. void colourChanged();
  35854. private:
  35855. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextButton);
  35856. };
  35857. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  35858. /*** End of inlined file: juce_TextButton.h ***/
  35859. /**
  35860. A component displaying a list of plugins, with options to scan for them,
  35861. add, remove and sort them.
  35862. */
  35863. class JUCE_API PluginListComponent : public Component,
  35864. public ListBoxModel,
  35865. public ChangeListener,
  35866. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  35867. public Timer
  35868. {
  35869. public:
  35870. /**
  35871. Creates the list component.
  35872. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  35873. The properties file, if supplied, is used to store the user's last search paths.
  35874. */
  35875. PluginListComponent (KnownPluginList& listToRepresent,
  35876. const File& deadMansPedalFile,
  35877. PropertiesFile* propertiesToUse);
  35878. /** Destructor. */
  35879. ~PluginListComponent();
  35880. /** @internal */
  35881. void resized();
  35882. /** @internal */
  35883. bool isInterestedInFileDrag (const StringArray& files);
  35884. /** @internal */
  35885. void filesDropped (const StringArray& files, int, int);
  35886. /** @internal */
  35887. int getNumRows();
  35888. /** @internal */
  35889. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  35890. /** @internal */
  35891. void deleteKeyPressed (int lastRowSelected);
  35892. /** @internal */
  35893. void buttonClicked (Button* b);
  35894. /** @internal */
  35895. void changeListenerCallback (ChangeBroadcaster*);
  35896. /** @internal */
  35897. void timerCallback();
  35898. private:
  35899. KnownPluginList& list;
  35900. File deadMansPedalFile;
  35901. ListBox listBox;
  35902. TextButton optionsButton;
  35903. PropertiesFile* propertiesToUse;
  35904. int typeToScan;
  35905. void scanFor (AudioPluginFormat* format);
  35906. static void optionsMenuStaticCallback (int result, PluginListComponent*);
  35907. void optionsMenuCallback (int result);
  35908. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginListComponent);
  35909. };
  35910. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35911. /*** End of inlined file: juce_PluginListComponent.h ***/
  35912. #endif
  35913. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  35914. #endif
  35915. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  35916. #endif
  35917. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  35918. #endif
  35919. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35920. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  35921. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35922. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35923. /**
  35924. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  35925. Use one of these objects if you want to wire-up a set of AudioProcessors
  35926. and play back the result.
  35927. Processors can be added to the graph as "nodes" using addNode(), and once
  35928. added, you can connect any of their input or output channels to other
  35929. nodes using addConnection().
  35930. To play back a graph through an audio device, you might want to use an
  35931. AudioProcessorPlayer object.
  35932. */
  35933. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  35934. public AsyncUpdater
  35935. {
  35936. public:
  35937. /** Creates an empty graph.
  35938. */
  35939. AudioProcessorGraph();
  35940. /** Destructor.
  35941. Any processor objects that have been added to the graph will also be deleted.
  35942. */
  35943. ~AudioProcessorGraph();
  35944. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  35945. To create a node, call AudioProcessorGraph::addNode().
  35946. */
  35947. class JUCE_API Node : public ReferenceCountedObject
  35948. {
  35949. public:
  35950. /** The ID number assigned to this node.
  35951. This is assigned by the graph that owns it, and can't be changed.
  35952. */
  35953. const uint32 nodeId;
  35954. /** The actual processor object that this node represents. */
  35955. AudioProcessor* getProcessor() const noexcept { return processor; }
  35956. /** A set of user-definable properties that are associated with this node.
  35957. This can be used to attach values to the node for whatever purpose seems
  35958. useful. For example, you might store an x and y position if your application
  35959. is displaying the nodes on-screen.
  35960. */
  35961. NamedValueSet properties;
  35962. /** A convenient typedef for referring to a pointer to a node object.
  35963. */
  35964. typedef ReferenceCountedObjectPtr <Node> Ptr;
  35965. private:
  35966. friend class AudioProcessorGraph;
  35967. const ScopedPointer<AudioProcessor> processor;
  35968. bool isPrepared;
  35969. Node (uint32 nodeId, AudioProcessor* processor) noexcept;
  35970. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  35971. void unprepare();
  35972. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Node);
  35973. };
  35974. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  35975. To create a connection, use AudioProcessorGraph::addConnection().
  35976. */
  35977. struct JUCE_API Connection
  35978. {
  35979. public:
  35980. Connection (uint32 sourceNodeId, int sourceChannelIndex,
  35981. uint32 destNodeId, int destChannelIndex) noexcept;
  35982. /** The ID number of the node which is the input source for this connection.
  35983. @see AudioProcessorGraph::getNodeForId
  35984. */
  35985. uint32 sourceNodeId;
  35986. /** The index of the output channel of the source node from which this
  35987. connection takes its data.
  35988. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35989. it is referring to the source node's midi output. Otherwise, it is the zero-based
  35990. index of an audio output channel in the source node.
  35991. */
  35992. int sourceChannelIndex;
  35993. /** The ID number of the node which is the destination for this connection.
  35994. @see AudioProcessorGraph::getNodeForId
  35995. */
  35996. uint32 destNodeId;
  35997. /** The index of the input channel of the destination node to which this
  35998. connection delivers its data.
  35999. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  36000. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  36001. index of an audio input channel in the destination node.
  36002. */
  36003. int destChannelIndex;
  36004. private:
  36005. JUCE_LEAK_DETECTOR (Connection);
  36006. };
  36007. /** Deletes all nodes and connections from this graph.
  36008. Any processor objects in the graph will be deleted.
  36009. */
  36010. void clear();
  36011. /** Returns the number of nodes in the graph. */
  36012. int getNumNodes() const { return nodes.size(); }
  36013. /** Returns a pointer to one of the nodes in the graph.
  36014. This will return 0 if the index is out of range.
  36015. @see getNodeForId
  36016. */
  36017. Node* getNode (const int index) const { return nodes [index]; }
  36018. /** Searches the graph for a node with the given ID number and returns it.
  36019. If no such node was found, this returns 0.
  36020. @see getNode
  36021. */
  36022. Node* getNodeForId (const uint32 nodeId) const;
  36023. /** Adds a node to the graph.
  36024. This creates a new node in the graph, for the specified processor. Once you have
  36025. added a processor to the graph, the graph owns it and will delete it later when
  36026. it is no longer needed.
  36027. The optional nodeId parameter lets you specify an ID to use for the node, but
  36028. if the value is already in use, this new node will overwrite the old one.
  36029. If this succeeds, it returns a pointer to the newly-created node.
  36030. */
  36031. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  36032. /** Deletes a node within the graph which has the specified ID.
  36033. This will also delete any connections that are attached to this node.
  36034. */
  36035. bool removeNode (uint32 nodeId);
  36036. /** Returns the number of connections in the graph. */
  36037. int getNumConnections() const { return connections.size(); }
  36038. /** Returns a pointer to one of the connections in the graph. */
  36039. const Connection* getConnection (int index) const { return connections [index]; }
  36040. /** Searches for a connection between some specified channels.
  36041. If no such connection is found, this returns 0.
  36042. */
  36043. const Connection* getConnectionBetween (uint32 sourceNodeId,
  36044. int sourceChannelIndex,
  36045. uint32 destNodeId,
  36046. int destChannelIndex) const;
  36047. /** Returns true if there is a connection between any of the channels of
  36048. two specified nodes.
  36049. */
  36050. bool isConnected (uint32 possibleSourceNodeId,
  36051. uint32 possibleDestNodeId) const;
  36052. /** Returns true if it would be legal to connect the specified points.
  36053. */
  36054. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  36055. uint32 destNodeId, int destChannelIndex) const;
  36056. /** Attempts to connect two specified channels of two nodes.
  36057. If this isn't allowed (e.g. because you're trying to connect a midi channel
  36058. to an audio one or other such nonsense), then it'll return false.
  36059. */
  36060. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  36061. uint32 destNodeId, int destChannelIndex);
  36062. /** Deletes the connection with the specified index.
  36063. Returns true if a connection was actually deleted.
  36064. */
  36065. void removeConnection (int index);
  36066. /** Deletes any connection between two specified points.
  36067. Returns true if a connection was actually deleted.
  36068. */
  36069. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  36070. uint32 destNodeId, int destChannelIndex);
  36071. /** Removes all connections from the specified node.
  36072. */
  36073. bool disconnectNode (uint32 nodeId);
  36074. /** Performs a sanity checks of all the connections.
  36075. This might be useful if some of the processors are doing things like changing
  36076. their channel counts, which could render some connections obsolete.
  36077. */
  36078. bool removeIllegalConnections();
  36079. /** A special number that represents the midi channel of a node.
  36080. This is used as a channel index value if you want to refer to the midi input
  36081. or output instead of an audio channel.
  36082. */
  36083. static const int midiChannelIndex;
  36084. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  36085. in order to use the audio that comes into and out of the graph itself.
  36086. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  36087. node in the graph which delivers the audio that is coming into the parent
  36088. graph. This allows you to stream the data to other nodes and process the
  36089. incoming audio.
  36090. Likewise, one of these in "output" mode can be sent data which it will add to
  36091. the sum of data being sent to the graph's output.
  36092. @see AudioProcessorGraph
  36093. */
  36094. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  36095. {
  36096. public:
  36097. /** Specifies the mode in which this processor will operate.
  36098. */
  36099. enum IODeviceType
  36100. {
  36101. audioInputNode, /**< In this mode, the processor has output channels
  36102. representing all the audio input channels that are
  36103. coming into its parent audio graph. */
  36104. audioOutputNode, /**< In this mode, the processor has input channels
  36105. representing all the audio output channels that are
  36106. going out of its parent audio graph. */
  36107. midiInputNode, /**< In this mode, the processor has a midi output which
  36108. delivers the same midi data that is arriving at its
  36109. parent graph. */
  36110. midiOutputNode /**< In this mode, the processor has a midi input and
  36111. any data sent to it will be passed out of the parent
  36112. graph. */
  36113. };
  36114. /** Returns the mode of this processor. */
  36115. IODeviceType getType() const { return type; }
  36116. /** Returns the parent graph to which this processor belongs, or 0 if it
  36117. hasn't yet been added to one. */
  36118. AudioProcessorGraph* getParentGraph() const { return graph; }
  36119. /** True if this is an audio or midi input. */
  36120. bool isInput() const;
  36121. /** True if this is an audio or midi output. */
  36122. bool isOutput() const;
  36123. AudioGraphIOProcessor (const IODeviceType type);
  36124. ~AudioGraphIOProcessor();
  36125. const String getName() const;
  36126. void fillInPluginDescription (PluginDescription& d) const;
  36127. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  36128. void releaseResources();
  36129. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  36130. const String getInputChannelName (int channelIndex) const;
  36131. const String getOutputChannelName (int channelIndex) const;
  36132. bool isInputChannelStereoPair (int index) const;
  36133. bool isOutputChannelStereoPair (int index) const;
  36134. bool acceptsMidi() const;
  36135. bool producesMidi() const;
  36136. bool hasEditor() const;
  36137. AudioProcessorEditor* createEditor();
  36138. int getNumParameters();
  36139. const String getParameterName (int);
  36140. float getParameter (int);
  36141. const String getParameterText (int);
  36142. void setParameter (int, float);
  36143. int getNumPrograms();
  36144. int getCurrentProgram();
  36145. void setCurrentProgram (int);
  36146. const String getProgramName (int);
  36147. void changeProgramName (int, const String&);
  36148. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  36149. void setStateInformation (const void* data, int sizeInBytes);
  36150. /** @internal */
  36151. void setParentGraph (AudioProcessorGraph* graph);
  36152. private:
  36153. const IODeviceType type;
  36154. AudioProcessorGraph* graph;
  36155. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioGraphIOProcessor);
  36156. };
  36157. // AudioProcessor methods:
  36158. const String getName() const;
  36159. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  36160. void releaseResources();
  36161. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  36162. const String getInputChannelName (int channelIndex) const;
  36163. const String getOutputChannelName (int channelIndex) const;
  36164. bool isInputChannelStereoPair (int index) const;
  36165. bool isOutputChannelStereoPair (int index) const;
  36166. bool acceptsMidi() const;
  36167. bool producesMidi() const;
  36168. bool hasEditor() const { return false; }
  36169. AudioProcessorEditor* createEditor() { return nullptr; }
  36170. int getNumParameters() { return 0; }
  36171. const String getParameterName (int) { return String::empty; }
  36172. float getParameter (int) { return 0; }
  36173. const String getParameterText (int) { return String::empty; }
  36174. void setParameter (int, float) { }
  36175. int getNumPrograms() { return 0; }
  36176. int getCurrentProgram() { return 0; }
  36177. void setCurrentProgram (int) { }
  36178. const String getProgramName (int) { return String::empty; }
  36179. void changeProgramName (int, const String&) { }
  36180. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  36181. void setStateInformation (const void* data, int sizeInBytes);
  36182. /** @internal */
  36183. void handleAsyncUpdate();
  36184. private:
  36185. ReferenceCountedArray <Node> nodes;
  36186. OwnedArray <Connection> connections;
  36187. int lastNodeId;
  36188. AudioSampleBuffer renderingBuffers;
  36189. OwnedArray <MidiBuffer> midiBuffers;
  36190. CriticalSection renderLock;
  36191. Array<void*> renderingOps;
  36192. friend class AudioGraphIOProcessor;
  36193. AudioSampleBuffer* currentAudioInputBuffer;
  36194. AudioSampleBuffer currentAudioOutputBuffer;
  36195. MidiBuffer* currentMidiInputBuffer;
  36196. MidiBuffer currentMidiOutputBuffer;
  36197. void clearRenderingSequence();
  36198. void buildRenderingSequence();
  36199. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  36200. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorGraph);
  36201. };
  36202. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  36203. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  36204. #endif
  36205. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  36206. #endif
  36207. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  36208. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  36209. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  36210. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  36211. /**
  36212. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  36213. To use one of these, just make it the callback used by your AudioIODevice, and
  36214. give it a processor to use by calling setProcessor().
  36215. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  36216. input to send both streams through the processor.
  36217. @see AudioProcessor, AudioProcessorGraph
  36218. */
  36219. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  36220. public MidiInputCallback
  36221. {
  36222. public:
  36223. /**
  36224. */
  36225. AudioProcessorPlayer();
  36226. /** Destructor. */
  36227. virtual ~AudioProcessorPlayer();
  36228. /** Sets the processor that should be played.
  36229. The processor that is passed in will not be deleted or owned by this object.
  36230. To stop anything playing, pass in 0 to this method.
  36231. */
  36232. void setProcessor (AudioProcessor* processorToPlay);
  36233. /** Returns the current audio processor that is being played.
  36234. */
  36235. AudioProcessor* getCurrentProcessor() const { return processor; }
  36236. /** Returns a midi message collector that you can pass midi messages to if you
  36237. want them to be injected into the midi stream that is being sent to the
  36238. processor.
  36239. */
  36240. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  36241. /** @internal */
  36242. void audioDeviceIOCallback (const float** inputChannelData,
  36243. int totalNumInputChannels,
  36244. float** outputChannelData,
  36245. int totalNumOutputChannels,
  36246. int numSamples);
  36247. /** @internal */
  36248. void audioDeviceAboutToStart (AudioIODevice* device);
  36249. /** @internal */
  36250. void audioDeviceStopped();
  36251. /** @internal */
  36252. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  36253. private:
  36254. AudioProcessor* processor;
  36255. CriticalSection lock;
  36256. double sampleRate;
  36257. int blockSize;
  36258. bool isPrepared;
  36259. int numInputChans, numOutputChans;
  36260. float* channels [128];
  36261. AudioSampleBuffer tempBuffer;
  36262. MidiBuffer incomingMidi;
  36263. MidiMessageCollector messageCollector;
  36264. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorPlayer);
  36265. };
  36266. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  36267. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  36268. #endif
  36269. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  36270. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  36271. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  36272. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  36273. /*** Start of inlined file: juce_PropertyPanel.h ***/
  36274. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  36275. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  36276. /*** Start of inlined file: juce_PropertyComponent.h ***/
  36277. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  36278. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  36279. class EditableProperty;
  36280. /**
  36281. A base class for a component that goes in a PropertyPanel and displays one of
  36282. an item's properties.
  36283. Subclasses of this are used to display a property in various forms, e.g. a
  36284. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  36285. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  36286. A subclass must implement the refresh() method which will be called to tell the
  36287. component to update itself, and is also responsible for calling this it when the
  36288. item that it refers to is changed.
  36289. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  36290. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  36291. */
  36292. class JUCE_API PropertyComponent : public Component,
  36293. public SettableTooltipClient
  36294. {
  36295. public:
  36296. /** Creates a PropertyComponent.
  36297. @param propertyName the name is stored as this component's name, and is
  36298. used as the name displayed next to this component in
  36299. a property panel
  36300. @param preferredHeight the height that the component should be given - some
  36301. items may need to be larger than a normal row height.
  36302. This value can also be set if a subclass changes the
  36303. preferredHeight member variable.
  36304. */
  36305. PropertyComponent (const String& propertyName,
  36306. int preferredHeight = 25);
  36307. /** Destructor. */
  36308. ~PropertyComponent();
  36309. /** Returns this item's preferred height.
  36310. This value is specified either in the constructor or by a subclass changing the
  36311. preferredHeight member variable.
  36312. */
  36313. int getPreferredHeight() const noexcept { return preferredHeight; }
  36314. void setPreferredHeight (int newHeight) noexcept { preferredHeight = newHeight; }
  36315. /** Updates the property component if the item it refers to has changed.
  36316. A subclass must implement this method, and other objects may call it to
  36317. force it to refresh itself.
  36318. The subclass should be economical in the amount of work is done, so for
  36319. example it should check whether it really needs to do a repaint rather than
  36320. just doing one every time this method is called, as it may be called when
  36321. the value being displayed hasn't actually changed.
  36322. */
  36323. virtual void refresh() = 0;
  36324. /** The default paint method fills the background and draws a label for the
  36325. item's name.
  36326. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  36327. */
  36328. void paint (Graphics& g);
  36329. /** The default resize method positions any child component to the right of this
  36330. one, based on the look and feel's default label size.
  36331. */
  36332. void resized();
  36333. /** By default, this just repaints the component. */
  36334. void enablementChanged();
  36335. protected:
  36336. /** Used by the PropertyPanel to determine how high this component needs to be.
  36337. A subclass can update this value in its constructor but shouldn't alter it later
  36338. as changes won't necessarily be picked up.
  36339. */
  36340. int preferredHeight;
  36341. private:
  36342. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyComponent);
  36343. };
  36344. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  36345. /*** End of inlined file: juce_PropertyComponent.h ***/
  36346. /**
  36347. A panel that holds a list of PropertyComponent objects.
  36348. This panel displays a list of PropertyComponents, and allows them to be organised
  36349. into collapsible sections.
  36350. To use, simply create one of these and add your properties to it with addProperties()
  36351. or addSection().
  36352. @see PropertyComponent
  36353. */
  36354. class JUCE_API PropertyPanel : public Component
  36355. {
  36356. public:
  36357. /** Creates an empty property panel. */
  36358. PropertyPanel();
  36359. /** Destructor. */
  36360. ~PropertyPanel();
  36361. /** Deletes all property components from the panel.
  36362. */
  36363. void clear();
  36364. /** Adds a set of properties to the panel.
  36365. The components in the list will be owned by this object and will be automatically
  36366. deleted later on when no longer needed.
  36367. These properties are added without them being inside a named section. If you
  36368. want them to be kept together in a collapsible section, use addSection() instead.
  36369. */
  36370. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  36371. /** Adds a set of properties to the panel.
  36372. These properties are added at the bottom of the list, under a section heading with
  36373. a plus/minus button that allows it to be opened and closed.
  36374. The components in the list will be owned by this object and will be automatically
  36375. deleted later on when no longer needed.
  36376. To add properies without them being in a section, use addProperties().
  36377. */
  36378. void addSection (const String& sectionTitle,
  36379. const Array <PropertyComponent*>& newPropertyComponents,
  36380. bool shouldSectionInitiallyBeOpen = true);
  36381. /** Calls the refresh() method of all PropertyComponents in the panel */
  36382. void refreshAll() const;
  36383. /** Returns a list of all the names of sections in the panel.
  36384. These are the sections that have been added with addSection().
  36385. */
  36386. const StringArray getSectionNames() const;
  36387. /** Returns true if the section at this index is currently open.
  36388. The index is from 0 up to the number of items returned by getSectionNames().
  36389. */
  36390. bool isSectionOpen (int sectionIndex) const;
  36391. /** Opens or closes one of the sections.
  36392. The index is from 0 up to the number of items returned by getSectionNames().
  36393. */
  36394. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  36395. /** Enables or disables one of the sections.
  36396. The index is from 0 up to the number of items returned by getSectionNames().
  36397. */
  36398. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  36399. /** Saves the current state of open/closed sections so it can be restored later.
  36400. The caller is responsible for deleting the object that is returned.
  36401. To restore this state, use restoreOpennessState().
  36402. @see restoreOpennessState
  36403. */
  36404. XmlElement* getOpennessState() const;
  36405. /** Restores a previously saved arrangement of open/closed sections.
  36406. This will try to restore a snapshot of the panel's state that was created by
  36407. the getOpennessState() method. If any of the sections named in the original
  36408. XML aren't present, they will be ignored.
  36409. @see getOpennessState
  36410. */
  36411. void restoreOpennessState (const XmlElement& newState);
  36412. /** Sets a message to be displayed when there are no properties in the panel.
  36413. The default message is "nothing selected".
  36414. */
  36415. void setMessageWhenEmpty (const String& newMessage);
  36416. /** Returns the message that is displayed when there are no properties.
  36417. @see setMessageWhenEmpty
  36418. */
  36419. const String& getMessageWhenEmpty() const;
  36420. /** @internal */
  36421. void paint (Graphics& g);
  36422. /** @internal */
  36423. void resized();
  36424. private:
  36425. Viewport viewport;
  36426. class PropertyHolderComponent;
  36427. PropertyHolderComponent* propertyHolderComponent;
  36428. String messageWhenEmpty;
  36429. void updatePropHolderLayout() const;
  36430. void updatePropHolderLayout (int width) const;
  36431. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyPanel);
  36432. };
  36433. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  36434. /*** End of inlined file: juce_PropertyPanel.h ***/
  36435. /**
  36436. A type of UI component that displays the parameters of an AudioProcessor as
  36437. a simple list of sliders.
  36438. This can be used for showing an editor for a processor that doesn't supply
  36439. its own custom editor.
  36440. @see AudioProcessor
  36441. */
  36442. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  36443. {
  36444. public:
  36445. GenericAudioProcessorEditor (AudioProcessor* owner);
  36446. ~GenericAudioProcessorEditor();
  36447. void paint (Graphics& g);
  36448. void resized();
  36449. private:
  36450. PropertyPanel panel;
  36451. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GenericAudioProcessorEditor);
  36452. };
  36453. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  36454. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  36455. #endif
  36456. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  36457. /*** Start of inlined file: juce_Sampler.h ***/
  36458. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  36459. #define __JUCE_SAMPLER_JUCEHEADER__
  36460. /*** Start of inlined file: juce_Synthesiser.h ***/
  36461. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  36462. #define __JUCE_SYNTHESISER_JUCEHEADER__
  36463. /**
  36464. Describes one of the sounds that a Synthesiser can play.
  36465. A synthesiser can contain one or more sounds, and a sound can choose which
  36466. midi notes and channels can trigger it.
  36467. The SynthesiserSound is a passive class that just describes what the sound is -
  36468. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  36469. more than one SynthesiserVoice to play the same sound at the same time.
  36470. @see Synthesiser, SynthesiserVoice
  36471. */
  36472. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  36473. {
  36474. protected:
  36475. SynthesiserSound();
  36476. public:
  36477. /** Destructor. */
  36478. virtual ~SynthesiserSound();
  36479. /** Returns true if this sound should be played when a given midi note is pressed.
  36480. The Synthesiser will use this information when deciding which sounds to trigger
  36481. for a given note.
  36482. */
  36483. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  36484. /** Returns true if the sound should be triggered by midi events on a given channel.
  36485. The Synthesiser will use this information when deciding which sounds to trigger
  36486. for a given note.
  36487. */
  36488. virtual bool appliesToChannel (const int midiChannel) = 0;
  36489. /**
  36490. */
  36491. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  36492. private:
  36493. JUCE_LEAK_DETECTOR (SynthesiserSound);
  36494. };
  36495. /**
  36496. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  36497. A voice plays a single sound at a time, and a synthesiser holds an array of
  36498. voices so that it can play polyphonically.
  36499. @see Synthesiser, SynthesiserSound
  36500. */
  36501. class JUCE_API SynthesiserVoice
  36502. {
  36503. public:
  36504. /** Creates a voice. */
  36505. SynthesiserVoice();
  36506. /** Destructor. */
  36507. virtual ~SynthesiserVoice();
  36508. /** Returns the midi note that this voice is currently playing.
  36509. Returns a value less than 0 if no note is playing.
  36510. */
  36511. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  36512. /** Returns the sound that this voice is currently playing.
  36513. Returns 0 if it's not playing.
  36514. */
  36515. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  36516. /** Must return true if this voice object is capable of playing the given sound.
  36517. If there are different classes of sound, and different classes of voice, a voice can
  36518. choose which ones it wants to take on.
  36519. A typical implementation of this method may just return true if there's only one type
  36520. of voice and sound, or it might check the type of the sound object passed-in and
  36521. see if it's one that it understands.
  36522. */
  36523. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  36524. /** Called to start a new note.
  36525. This will be called during the rendering callback, so must be fast and thread-safe.
  36526. */
  36527. virtual void startNote (const int midiNoteNumber,
  36528. const float velocity,
  36529. SynthesiserSound* sound,
  36530. const int currentPitchWheelPosition) = 0;
  36531. /** Called to stop a note.
  36532. This will be called during the rendering callback, so must be fast and thread-safe.
  36533. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  36534. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  36535. and allow the synth to reassign it another sound.
  36536. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  36537. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  36538. finishes playing (during the rendering callback), it must make sure that it calls
  36539. clearCurrentNote().
  36540. */
  36541. virtual void stopNote (const bool allowTailOff) = 0;
  36542. /** Called to let the voice know that the pitch wheel has been moved.
  36543. This will be called during the rendering callback, so must be fast and thread-safe.
  36544. */
  36545. virtual void pitchWheelMoved (const int newValue) = 0;
  36546. /** Called to let the voice know that a midi controller has been moved.
  36547. This will be called during the rendering callback, so must be fast and thread-safe.
  36548. */
  36549. virtual void controllerMoved (const int controllerNumber,
  36550. const int newValue) = 0;
  36551. /** Renders the next block of data for this voice.
  36552. The output audio data must be added to the current contents of the buffer provided.
  36553. Only the region of the buffer between startSample and (startSample + numSamples)
  36554. should be altered by this method.
  36555. If the voice is currently silent, it should just return without doing anything.
  36556. If the sound that the voice is playing finishes during the course of this rendered
  36557. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  36558. The size of the blocks that are rendered can change each time it is called, and may
  36559. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  36560. the voice's methods will be called to tell it about note and controller events.
  36561. */
  36562. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  36563. int startSample,
  36564. int numSamples) = 0;
  36565. /** Returns true if the voice is currently playing a sound which is mapped to the given
  36566. midi channel.
  36567. If it's not currently playing, this will return false.
  36568. */
  36569. bool isPlayingChannel (int midiChannel) const;
  36570. /** Changes the voice's reference sample rate.
  36571. The rate is set so that subclasses know the output rate and can set their pitch
  36572. accordingly.
  36573. This method is called by the synth, and subclasses can access the current rate with
  36574. the currentSampleRate member.
  36575. */
  36576. void setCurrentPlaybackSampleRate (double newRate);
  36577. protected:
  36578. /** Returns the current target sample rate at which rendering is being done.
  36579. This is available for subclasses so they can pitch things correctly.
  36580. */
  36581. double getSampleRate() const { return currentSampleRate; }
  36582. /** Resets the state of this voice after a sound has finished playing.
  36583. The subclass must call this when it finishes playing a note and becomes available
  36584. to play new ones.
  36585. It must either call it in the stopNote() method, or if the voice is tailing off,
  36586. then it should call it later during the renderNextBlock method, as soon as it
  36587. finishes its tail-off.
  36588. It can also be called at any time during the render callback if the sound happens
  36589. to have finished, e.g. if it's playing a sample and the sample finishes.
  36590. */
  36591. void clearCurrentNote();
  36592. private:
  36593. friend class Synthesiser;
  36594. double currentSampleRate;
  36595. int currentlyPlayingNote;
  36596. uint32 noteOnTime;
  36597. SynthesiserSound::Ptr currentlyPlayingSound;
  36598. JUCE_LEAK_DETECTOR (SynthesiserVoice);
  36599. };
  36600. /**
  36601. Base class for a musical device that can play sounds.
  36602. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  36603. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  36604. which can play back one of these sounds.
  36605. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  36606. set of sounds, and a set of voices it can use to play them. If you only give it
  36607. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  36608. have available.
  36609. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  36610. events that go in will be scanned for note on/off messages, and these are used to
  36611. start and stop the voices playing the appropriate sounds.
  36612. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  36613. noteOff() and other controller methods.
  36614. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  36615. what the target playback rate is. This value is passed on to the voices so that
  36616. they can pitch their output correctly.
  36617. */
  36618. class JUCE_API Synthesiser
  36619. {
  36620. public:
  36621. /** Creates a new synthesiser.
  36622. You'll need to add some sounds and voices before it'll make any sound..
  36623. */
  36624. Synthesiser();
  36625. /** Destructor. */
  36626. virtual ~Synthesiser();
  36627. /** Deletes all voices. */
  36628. void clearVoices();
  36629. /** Returns the number of voices that have been added. */
  36630. int getNumVoices() const { return voices.size(); }
  36631. /** Returns one of the voices that have been added. */
  36632. SynthesiserVoice* getVoice (int index) const;
  36633. /** Adds a new voice to the synth.
  36634. All the voices should be the same class of object and are treated equally.
  36635. The object passed in will be managed by the synthesiser, which will delete
  36636. it later on when no longer needed. The caller should not retain a pointer to the
  36637. voice.
  36638. */
  36639. void addVoice (SynthesiserVoice* newVoice);
  36640. /** Deletes one of the voices. */
  36641. void removeVoice (int index);
  36642. /** Deletes all sounds. */
  36643. void clearSounds();
  36644. /** Returns the number of sounds that have been added to the synth. */
  36645. int getNumSounds() const { return sounds.size(); }
  36646. /** Returns one of the sounds. */
  36647. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  36648. /** Adds a new sound to the synthesiser.
  36649. The object passed in is reference counted, so will be deleted when it is removed
  36650. from the synthesiser, and when no voices are still using it.
  36651. */
  36652. void addSound (const SynthesiserSound::Ptr& newSound);
  36653. /** Removes and deletes one of the sounds. */
  36654. void removeSound (int index);
  36655. /** If set to true, then the synth will try to take over an existing voice if
  36656. it runs out and needs to play another note.
  36657. The value of this boolean is passed into findFreeVoice(), so the result will
  36658. depend on the implementation of this method.
  36659. */
  36660. void setNoteStealingEnabled (bool shouldStealNotes);
  36661. /** Returns true if note-stealing is enabled.
  36662. @see setNoteStealingEnabled
  36663. */
  36664. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  36665. /** Triggers a note-on event.
  36666. The default method here will find all the sounds that want to be triggered by
  36667. this note/channel. For each sound, it'll try to find a free voice, and use the
  36668. voice to start playing the sound.
  36669. Subclasses might want to override this if they need a more complex algorithm.
  36670. This method will be called automatically according to the midi data passed into
  36671. renderNextBlock(), but may be called explicitly too.
  36672. */
  36673. virtual void noteOn (int midiChannel,
  36674. int midiNoteNumber,
  36675. float velocity);
  36676. /** Triggers a note-off event.
  36677. This will turn off any voices that are playing a sound for the given note/channel.
  36678. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  36679. (if they can do). If this is false, the notes will all be cut off immediately.
  36680. This method will be called automatically according to the midi data passed into
  36681. renderNextBlock(), but may be called explicitly too.
  36682. */
  36683. virtual void noteOff (int midiChannel,
  36684. int midiNoteNumber,
  36685. bool allowTailOff);
  36686. /** Turns off all notes.
  36687. This will turn off any voices that are playing a sound on the given midi channel.
  36688. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  36689. which channel they're playing.
  36690. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  36691. (if they can do). If this is false, the notes will all be cut off immediately.
  36692. This method will be called automatically according to the midi data passed into
  36693. renderNextBlock(), but may be called explicitly too.
  36694. */
  36695. virtual void allNotesOff (int midiChannel,
  36696. bool allowTailOff);
  36697. /** Sends a pitch-wheel message.
  36698. This will send a pitch-wheel message to any voices that are playing sounds on
  36699. the given midi channel.
  36700. This method will be called automatically according to the midi data passed into
  36701. renderNextBlock(), but may be called explicitly too.
  36702. @param midiChannel the midi channel for the event
  36703. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  36704. */
  36705. virtual void handlePitchWheel (int midiChannel,
  36706. int wheelValue);
  36707. /** Sends a midi controller message.
  36708. This will send a midi controller message to any voices that are playing sounds on
  36709. the given midi channel.
  36710. This method will be called automatically according to the midi data passed into
  36711. renderNextBlock(), but may be called explicitly too.
  36712. @param midiChannel the midi channel for the event
  36713. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  36714. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  36715. */
  36716. virtual void handleController (int midiChannel,
  36717. int controllerNumber,
  36718. int controllerValue);
  36719. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  36720. render.
  36721. This value is propagated to the voices so that they can use it to render the correct
  36722. pitches.
  36723. */
  36724. void setCurrentPlaybackSampleRate (double sampleRate);
  36725. /** Creates the next block of audio output.
  36726. This will process the next numSamples of data from all the voices, and add that output
  36727. to the audio block supplied, starting from the offset specified. Note that the
  36728. data will be added to the current contents of the buffer, so you should clear it
  36729. before calling this method if necessary.
  36730. The midi events in the inputMidi buffer are parsed for note and controller events,
  36731. and these are used to trigger the voices. Note that the startSample offset applies
  36732. both to the audio output buffer and the midi input buffer, so any midi events
  36733. with timestamps outside the specified region will be ignored.
  36734. */
  36735. void renderNextBlock (AudioSampleBuffer& outputAudio,
  36736. const MidiBuffer& inputMidi,
  36737. int startSample,
  36738. int numSamples);
  36739. protected:
  36740. /** This is used to control access to the rendering callback and the note trigger methods. */
  36741. CriticalSection lock;
  36742. OwnedArray <SynthesiserVoice> voices;
  36743. ReferenceCountedArray <SynthesiserSound> sounds;
  36744. /** The last pitch-wheel values for each midi channel. */
  36745. int lastPitchWheelValues [16];
  36746. /** Searches through the voices to find one that's not currently playing, and which
  36747. can play the given sound.
  36748. Returns 0 if all voices are busy and stealing isn't enabled.
  36749. This can be overridden to implement custom voice-stealing algorithms.
  36750. */
  36751. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  36752. const bool stealIfNoneAvailable) const;
  36753. /** Starts a specified voice playing a particular sound.
  36754. You'll probably never need to call this, it's used internally by noteOn(), but
  36755. may be needed by subclasses for custom behaviours.
  36756. */
  36757. void startVoice (SynthesiserVoice* voice,
  36758. SynthesiserSound* sound,
  36759. int midiChannel,
  36760. int midiNoteNumber,
  36761. float velocity);
  36762. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  36763. // Temporary method here to cause a compiler error - note the new parameters for this method.
  36764. int findFreeVoice (const bool) const { return 0; }
  36765. #endif
  36766. private:
  36767. double sampleRate;
  36768. uint32 lastNoteOnCounter;
  36769. bool shouldStealNotes;
  36770. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser);
  36771. };
  36772. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  36773. /*** End of inlined file: juce_Synthesiser.h ***/
  36774. /**
  36775. A subclass of SynthesiserSound that represents a sampled audio clip.
  36776. This is a pretty basic sampler, and just attempts to load the whole audio stream
  36777. into memory.
  36778. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36779. give it some SampledSound objects to play.
  36780. @see SamplerVoice, Synthesiser, SynthesiserSound
  36781. */
  36782. class JUCE_API SamplerSound : public SynthesiserSound
  36783. {
  36784. public:
  36785. /** Creates a sampled sound from an audio reader.
  36786. This will attempt to load the audio from the source into memory and store
  36787. it in this object.
  36788. @param name a name for the sample
  36789. @param source the audio to load. This object can be safely deleted by the
  36790. caller after this constructor returns
  36791. @param midiNotes the set of midi keys that this sound should be played on. This
  36792. is used by the SynthesiserSound::appliesToNote() method
  36793. @param midiNoteForNormalPitch the midi note at which the sample should be played
  36794. with its natural rate. All other notes will be pitched
  36795. up or down relative to this one
  36796. @param attackTimeSecs the attack (fade-in) time, in seconds
  36797. @param releaseTimeSecs the decay (fade-out) time, in seconds
  36798. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  36799. source, in seconds
  36800. */
  36801. SamplerSound (const String& name,
  36802. AudioFormatReader& source,
  36803. const BigInteger& midiNotes,
  36804. int midiNoteForNormalPitch,
  36805. double attackTimeSecs,
  36806. double releaseTimeSecs,
  36807. double maxSampleLengthSeconds);
  36808. /** Destructor. */
  36809. ~SamplerSound();
  36810. /** Returns the sample's name */
  36811. const String& getName() const { return name; }
  36812. /** Returns the audio sample data.
  36813. This could be 0 if there was a problem loading it.
  36814. */
  36815. AudioSampleBuffer* getAudioData() const { return data; }
  36816. bool appliesToNote (const int midiNoteNumber);
  36817. bool appliesToChannel (const int midiChannel);
  36818. private:
  36819. friend class SamplerVoice;
  36820. String name;
  36821. ScopedPointer <AudioSampleBuffer> data;
  36822. double sourceSampleRate;
  36823. BigInteger midiNotes;
  36824. int length, attackSamples, releaseSamples;
  36825. int midiRootNote;
  36826. JUCE_LEAK_DETECTOR (SamplerSound);
  36827. };
  36828. /**
  36829. A subclass of SynthesiserVoice that can play a SamplerSound.
  36830. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36831. give it some SampledSound objects to play.
  36832. @see SamplerSound, Synthesiser, SynthesiserVoice
  36833. */
  36834. class JUCE_API SamplerVoice : public SynthesiserVoice
  36835. {
  36836. public:
  36837. /** Creates a SamplerVoice.
  36838. */
  36839. SamplerVoice();
  36840. /** Destructor. */
  36841. ~SamplerVoice();
  36842. bool canPlaySound (SynthesiserSound* sound);
  36843. void startNote (const int midiNoteNumber,
  36844. const float velocity,
  36845. SynthesiserSound* sound,
  36846. const int currentPitchWheelPosition);
  36847. void stopNote (const bool allowTailOff);
  36848. void pitchWheelMoved (const int newValue);
  36849. void controllerMoved (const int controllerNumber,
  36850. const int newValue);
  36851. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  36852. private:
  36853. double pitchRatio;
  36854. double sourceSamplePosition;
  36855. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  36856. bool isInAttack, isInRelease;
  36857. JUCE_LEAK_DETECTOR (SamplerVoice);
  36858. };
  36859. #endif // __JUCE_SAMPLER_JUCEHEADER__
  36860. /*** End of inlined file: juce_Sampler.h ***/
  36861. #endif
  36862. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  36863. #endif
  36864. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36865. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  36866. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36867. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36868. /** Manages a list of ActionListeners, and can send them messages.
  36869. To quickly add methods to your class that can add/remove action
  36870. listeners and broadcast to them, you can derive from this.
  36871. @see ActionListener, ChangeListener
  36872. */
  36873. class JUCE_API ActionBroadcaster
  36874. {
  36875. public:
  36876. /** Creates an ActionBroadcaster. */
  36877. ActionBroadcaster();
  36878. /** Destructor. */
  36879. virtual ~ActionBroadcaster();
  36880. /** Adds a listener to the list.
  36881. Trying to add a listener that's already on the list will have no effect.
  36882. */
  36883. void addActionListener (ActionListener* listener);
  36884. /** Removes a listener from the list.
  36885. If the listener isn't on the list, this won't have any effect.
  36886. */
  36887. void removeActionListener (ActionListener* listener);
  36888. /** Removes all listeners from the list. */
  36889. void removeAllActionListeners();
  36890. /** Broadcasts a message to all the registered listeners.
  36891. @see ActionListener::actionListenerCallback
  36892. */
  36893. void sendActionMessage (const String& message) const;
  36894. private:
  36895. class CallbackReceiver : public MessageListener
  36896. {
  36897. public:
  36898. CallbackReceiver();
  36899. void handleMessage (const Message&);
  36900. ActionBroadcaster* owner;
  36901. };
  36902. friend class CallbackReceiver;
  36903. CallbackReceiver callback;
  36904. SortedSet <ActionListener*> actionListeners;
  36905. CriticalSection actionListenerLock;
  36906. JUCE_DECLARE_NON_COPYABLE (ActionBroadcaster);
  36907. };
  36908. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36909. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  36910. #endif
  36911. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  36912. #endif
  36913. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  36914. #endif
  36915. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  36916. #endif
  36917. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  36918. #endif
  36919. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  36920. #endif
  36921. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36922. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  36923. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36924. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36925. class InterprocessConnectionServer;
  36926. /**
  36927. Manages a simple two-way messaging connection to another process, using either
  36928. a socket or a named pipe as the transport medium.
  36929. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  36930. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  36931. and incoming messages will result in a callback via the messageReceived()
  36932. method.
  36933. To open a pipe and wait for another client to connect to it, use the createPipe()
  36934. method.
  36935. To act as a socket server and create connections for one or more client, see the
  36936. InterprocessConnectionServer class.
  36937. @see InterprocessConnectionServer, Socket, NamedPipe
  36938. */
  36939. class JUCE_API InterprocessConnection : public Thread,
  36940. private MessageListener
  36941. {
  36942. public:
  36943. /** Creates a connection.
  36944. Connections are created manually, connecting them with the connectToSocket()
  36945. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  36946. when a client wants to connect.
  36947. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  36948. connectionLost() and messageReceived() methods will
  36949. always be made using the message thread; if false,
  36950. these will be called immediately on the connection's
  36951. own thread.
  36952. @param magicMessageHeaderNumber a magic number to use in the header to check the
  36953. validity of the data blocks being sent and received. This
  36954. can be any number, but the sender and receiver must obviously
  36955. use matching values or they won't recognise each other.
  36956. */
  36957. InterprocessConnection (bool callbacksOnMessageThread = true,
  36958. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  36959. /** Destructor. */
  36960. ~InterprocessConnection();
  36961. /** Tries to connect this object to a socket.
  36962. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  36963. object waiting to receive client connections on this port number.
  36964. @param hostName the host computer, either a network address or name
  36965. @param portNumber the socket port number to try to connect to
  36966. @param timeOutMillisecs how long to keep trying before giving up
  36967. @returns true if the connection is established successfully
  36968. @see Socket
  36969. */
  36970. bool connectToSocket (const String& hostName,
  36971. int portNumber,
  36972. int timeOutMillisecs);
  36973. /** Tries to connect the object to an existing named pipe.
  36974. For this to work, another process on the same computer must already have opened
  36975. an InterprocessConnection object and used createPipe() to create a pipe for this
  36976. to connect to.
  36977. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36978. @returns true if it connects successfully.
  36979. @see createPipe, NamedPipe
  36980. */
  36981. bool connectToPipe (const String& pipeName,
  36982. int pipeReceiveMessageTimeoutMs = -1);
  36983. /** Tries to create a new pipe for other processes to connect to.
  36984. This creates a pipe with the given name, so that other processes can use
  36985. connectToPipe() to connect to the other end.
  36986. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36987. If another process is already using this pipe, this will fail and return false.
  36988. */
  36989. bool createPipe (const String& pipeName,
  36990. int pipeReceiveMessageTimeoutMs = -1);
  36991. /** Disconnects and closes any currently-open sockets or pipes. */
  36992. void disconnect();
  36993. /** True if a socket or pipe is currently active. */
  36994. bool isConnected() const;
  36995. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  36996. StreamingSocket* getSocket() const noexcept { return socket; }
  36997. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  36998. NamedPipe* getPipe() const noexcept { return pipe; }
  36999. /** Returns the name of the machine at the other end of this connection.
  37000. This will return an empty string if the other machine isn't known for
  37001. some reason.
  37002. */
  37003. const String getConnectedHostName() const;
  37004. /** Tries to send a message to the other end of this connection.
  37005. This will fail if it's not connected, or if there's some kind of write error. If
  37006. it succeeds, the connection object at the other end will receive the message by
  37007. a callback to its messageReceived() method.
  37008. @see messageReceived
  37009. */
  37010. bool sendMessage (const MemoryBlock& message);
  37011. /** Called when the connection is first connected.
  37012. If the connection was created with the callbacksOnMessageThread flag set, then
  37013. this will be called on the message thread; otherwise it will be called on a server
  37014. thread.
  37015. */
  37016. virtual void connectionMade() = 0;
  37017. /** Called when the connection is broken.
  37018. If the connection was created with the callbacksOnMessageThread flag set, then
  37019. this will be called on the message thread; otherwise it will be called on a server
  37020. thread.
  37021. */
  37022. virtual void connectionLost() = 0;
  37023. /** Called when a message arrives.
  37024. When the object at the other end of this connection sends us a message with sendMessage(),
  37025. this callback is used to deliver it to us.
  37026. If the connection was created with the callbacksOnMessageThread flag set, then
  37027. this will be called on the message thread; otherwise it will be called on a server
  37028. thread.
  37029. @see sendMessage
  37030. */
  37031. virtual void messageReceived (const MemoryBlock& message) = 0;
  37032. private:
  37033. CriticalSection pipeAndSocketLock;
  37034. ScopedPointer <StreamingSocket> socket;
  37035. ScopedPointer <NamedPipe> pipe;
  37036. bool callbackConnectionState;
  37037. const bool useMessageThread;
  37038. const uint32 magicMessageHeader;
  37039. int pipeReceiveMessageTimeout;
  37040. friend class InterprocessConnectionServer;
  37041. void initialiseWithSocket (StreamingSocket* socket_);
  37042. void initialiseWithPipe (NamedPipe* pipe_);
  37043. void handleMessage (const Message& message);
  37044. void connectionMadeInt();
  37045. void connectionLostInt();
  37046. void deliverDataInt (const MemoryBlock& data);
  37047. bool readNextMessageInt();
  37048. void run();
  37049. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnection);
  37050. };
  37051. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  37052. /*** End of inlined file: juce_InterprocessConnection.h ***/
  37053. #endif
  37054. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  37055. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  37056. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  37057. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  37058. /**
  37059. An object that waits for client sockets to connect to a port on this host, and
  37060. creates InterprocessConnection objects for each one.
  37061. To use this, create a class derived from it which implements the createConnectionObject()
  37062. method, so that it creates suitable connection objects for each client that tries
  37063. to connect.
  37064. @see InterprocessConnection
  37065. */
  37066. class JUCE_API InterprocessConnectionServer : private Thread
  37067. {
  37068. public:
  37069. /** Creates an uninitialised server object.
  37070. */
  37071. InterprocessConnectionServer();
  37072. /** Destructor. */
  37073. ~InterprocessConnectionServer();
  37074. /** Starts an internal thread which listens on the given port number.
  37075. While this is running, in another process tries to connect with the
  37076. InterprocessConnection::connectToSocket() method, this object will call
  37077. createConnectionObject() to create a connection to that client.
  37078. Use stop() to stop the thread running.
  37079. @see createConnectionObject, stop
  37080. */
  37081. bool beginWaitingForSocket (int portNumber);
  37082. /** Terminates the listener thread, if it's active.
  37083. @see beginWaitingForSocket
  37084. */
  37085. void stop();
  37086. protected:
  37087. /** Creates a suitable connection object for a client process that wants to
  37088. connect to this one.
  37089. This will be called by the listener thread when a client process tries
  37090. to connect, and must return a new InterprocessConnection object that will
  37091. then run as this end of the connection.
  37092. @see InterprocessConnection
  37093. */
  37094. virtual InterprocessConnection* createConnectionObject() = 0;
  37095. private:
  37096. ScopedPointer <StreamingSocket> socket;
  37097. void run();
  37098. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnectionServer);
  37099. };
  37100. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  37101. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  37102. #endif
  37103. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  37104. #endif
  37105. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  37106. #endif
  37107. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  37108. #endif
  37109. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  37110. /*** Start of inlined file: juce_MessageManager.h ***/
  37111. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  37112. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  37113. class Component;
  37114. class MessageManagerLock;
  37115. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  37116. */
  37117. typedef void* (MessageCallbackFunction) (void* userData);
  37118. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  37119. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  37120. */
  37121. class JUCE_API MessageManager
  37122. {
  37123. public:
  37124. /** Returns the global instance of the MessageManager. */
  37125. static MessageManager* getInstance() noexcept;
  37126. /** Runs the event dispatch loop until a stop message is posted.
  37127. This method is only intended to be run by the application's startup routine,
  37128. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  37129. @see stopDispatchLoop
  37130. */
  37131. void runDispatchLoop();
  37132. /** Sends a signal that the dispatch loop should terminate.
  37133. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  37134. will be interrupted and will return.
  37135. @see runDispatchLoop
  37136. */
  37137. void stopDispatchLoop();
  37138. /** Returns true if the stopDispatchLoop() method has been called.
  37139. */
  37140. bool hasStopMessageBeenSent() const noexcept { return quitMessagePosted; }
  37141. #if JUCE_MODAL_LOOPS_PERMITTED
  37142. /** Synchronously dispatches messages until a given time has elapsed.
  37143. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  37144. otherwise returns true.
  37145. */
  37146. bool runDispatchLoopUntil (int millisecondsToRunFor);
  37147. #endif
  37148. /** Calls a function using the message-thread.
  37149. This can be used by any thread to cause this function to be called-back
  37150. by the message thread. If it's the message-thread that's calling this method,
  37151. then the function will just be called; if another thread is calling, a message
  37152. will be posted to the queue, and this method will block until that message
  37153. is delivered, the function is called, and the result is returned.
  37154. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  37155. thread has a critical section locked, which an unrelated message callback then tries to lock
  37156. before the message thread gets round to processing this callback.
  37157. @param callback the function to call - its signature must be @code
  37158. void* myCallbackFunction (void*) @endcode
  37159. @param userData a user-defined pointer that will be passed to the function that gets called
  37160. @returns the value that the callback function returns.
  37161. @see MessageManagerLock
  37162. */
  37163. void* callFunctionOnMessageThread (MessageCallbackFunction* callback, void* userData);
  37164. /** Returns true if the caller-thread is the message thread. */
  37165. bool isThisTheMessageThread() const noexcept;
  37166. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  37167. (Best to ignore this method unless you really know what you're doing..)
  37168. @see getCurrentMessageThread
  37169. */
  37170. void setCurrentThreadAsMessageThread();
  37171. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  37172. (Best to ignore this method unless you really know what you're doing..)
  37173. @see setCurrentMessageThread
  37174. */
  37175. Thread::ThreadID getCurrentMessageThread() const noexcept { return messageThreadId; }
  37176. /** Returns true if the caller thread has currenltly got the message manager locked.
  37177. see the MessageManagerLock class for more info about this.
  37178. This will be true if the caller is the message thread, because that automatically
  37179. gains a lock while a message is being dispatched.
  37180. */
  37181. bool currentThreadHasLockedMessageManager() const noexcept;
  37182. /** Sends a message to all other JUCE applications that are running.
  37183. @param messageText the string that will be passed to the actionListenerCallback()
  37184. method of the broadcast listeners in the other app.
  37185. @see registerBroadcastListener, ActionListener
  37186. */
  37187. static void broadcastMessage (const String& messageText);
  37188. /** Registers a listener to get told about broadcast messages.
  37189. The actionListenerCallback() callback's string parameter
  37190. is the message passed into broadcastMessage().
  37191. @see broadcastMessage
  37192. */
  37193. void registerBroadcastListener (ActionListener* listener);
  37194. /** Deregisters a broadcast listener. */
  37195. void deregisterBroadcastListener (ActionListener* listener);
  37196. #ifndef DOXYGEN
  37197. // Internal methods - do not use!
  37198. void deliverMessage (Message*);
  37199. void deliverBroadcastMessage (const String&);
  37200. ~MessageManager() noexcept;
  37201. #endif
  37202. private:
  37203. MessageManager() noexcept;
  37204. friend class MessageListener;
  37205. friend class ChangeBroadcaster;
  37206. friend class ActionBroadcaster;
  37207. friend class CallbackMessage;
  37208. static MessageManager* instance;
  37209. SortedSet <const MessageListener*> messageListeners;
  37210. ScopedPointer <ActionBroadcaster> broadcaster;
  37211. friend class JUCEApplication;
  37212. bool quitMessagePosted, quitMessageReceived;
  37213. Thread::ThreadID messageThreadId;
  37214. friend class MessageManagerLock;
  37215. Thread::ThreadID volatile threadWithLock;
  37216. CriticalSection lockingLock;
  37217. void postMessageToQueue (Message* message);
  37218. static bool postMessageToSystemQueue (Message*);
  37219. static void* exitModalLoopCallback (void*);
  37220. static void doPlatformSpecificInitialisation();
  37221. static void doPlatformSpecificShutdown();
  37222. static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  37223. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager);
  37224. };
  37225. /** Used to make sure that the calling thread has exclusive access to the message loop.
  37226. Because it's not thread-safe to call any of the Component or other UI classes
  37227. from threads other than the message thread, one of these objects can be used to
  37228. lock the message loop and allow this to be done. The message thread will be
  37229. suspended for the lifetime of the MessageManagerLock object, so create one on
  37230. the stack like this: @code
  37231. void MyThread::run()
  37232. {
  37233. someData = 1234;
  37234. const MessageManagerLock mmLock;
  37235. // the event loop will now be locked so it's safe to make a few calls..
  37236. myComponent->setBounds (newBounds);
  37237. myComponent->repaint();
  37238. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  37239. }
  37240. @endcode
  37241. Obviously be careful not to create one of these and leave it lying around, or
  37242. your app will grind to a halt!
  37243. Another caveat is that using this in conjunction with other CriticalSections
  37244. can create lots of interesting ways of producing a deadlock! In particular, if
  37245. your message thread calls stopThread() for a thread that uses these locks,
  37246. you'll get an (occasional) deadlock..
  37247. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  37248. */
  37249. class JUCE_API MessageManagerLock
  37250. {
  37251. public:
  37252. /** Tries to acquire a lock on the message manager.
  37253. The constructor attempts to gain a lock on the message loop, and the lock will be
  37254. kept for the lifetime of this object.
  37255. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  37256. this method will keep checking whether the thread has been given the
  37257. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  37258. without gaining the lock. If you pass a thread, you must check whether the lock was
  37259. successful by calling lockWasGained(). If this is false, your thread is being told to
  37260. die, so you should take evasive action.
  37261. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  37262. careful when doing this, because it's very easy to deadlock if your message thread
  37263. attempts to call stopThread() on a thread just as that thread attempts to get the
  37264. message lock.
  37265. If the calling thread already has the lock, nothing will be done, so it's safe and
  37266. quick to use these locks recursively.
  37267. E.g.
  37268. @code
  37269. void run()
  37270. {
  37271. ...
  37272. while (! threadShouldExit())
  37273. {
  37274. MessageManagerLock mml (Thread::getCurrentThread());
  37275. if (! mml.lockWasGained())
  37276. return; // another thread is trying to kill us!
  37277. ..do some locked stuff here..
  37278. }
  37279. ..and now the MM is now unlocked..
  37280. }
  37281. @endcode
  37282. */
  37283. MessageManagerLock (Thread* threadToCheckForExitSignal = 0);
  37284. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  37285. instead of a thread.
  37286. See the MessageManagerLock (Thread*) constructor for details on how this works.
  37287. */
  37288. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  37289. /** Releases the current thread's lock on the message manager.
  37290. Make sure this object is created and deleted by the same thread,
  37291. otherwise there are no guarantees what will happen!
  37292. */
  37293. ~MessageManagerLock() noexcept;
  37294. /** Returns true if the lock was successfully acquired.
  37295. (See the constructor that takes a Thread for more info).
  37296. */
  37297. bool lockWasGained() const noexcept { return locked; }
  37298. private:
  37299. class BlockingMessage;
  37300. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  37301. ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  37302. bool locked;
  37303. void init (Thread* thread, ThreadPoolJob* job);
  37304. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock);
  37305. };
  37306. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  37307. /*** End of inlined file: juce_MessageManager.h ***/
  37308. #endif
  37309. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  37310. /*** Start of inlined file: juce_MultiTimer.h ***/
  37311. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  37312. #define __JUCE_MULTITIMER_JUCEHEADER__
  37313. /**
  37314. A type of timer class that can run multiple timers with different frequencies,
  37315. all of which share a single callback.
  37316. This class is very similar to the Timer class, but allows you run multiple
  37317. separate timers, where each one has a unique ID number. The methods in this
  37318. class are exactly equivalent to those in Timer, but with the addition of
  37319. this ID number.
  37320. To use it, you need to create a subclass of MultiTimer, implementing the
  37321. timerCallback() method. Then you can start timers with startTimer(), and
  37322. each time the callback is triggered, it passes in the ID of the timer that
  37323. caused it.
  37324. @see Timer
  37325. */
  37326. class JUCE_API MultiTimer
  37327. {
  37328. protected:
  37329. /** Creates a MultiTimer.
  37330. When created, no timers are running, so use startTimer() to start things off.
  37331. */
  37332. MultiTimer() noexcept;
  37333. /** Creates a copy of another timer.
  37334. Note that this timer will not contain any running timers, even if the one you're
  37335. copying from was running.
  37336. */
  37337. MultiTimer (const MultiTimer& other) noexcept;
  37338. public:
  37339. /** Destructor. */
  37340. virtual ~MultiTimer();
  37341. /** The user-defined callback routine that actually gets called by each of the
  37342. timers that are running.
  37343. It's perfectly ok to call startTimer() or stopTimer() from within this
  37344. callback to change the subsequent intervals.
  37345. */
  37346. virtual void timerCallback (int timerId) = 0;
  37347. /** Starts a timer and sets the length of interval required.
  37348. If the timer is already started, this will reset it, so the
  37349. time between calling this method and the next timer callback
  37350. will not be less than the interval length passed in.
  37351. @param timerId a unique Id number that identifies the timer to
  37352. start. This is the id that will be passed back
  37353. to the timerCallback() method when this timer is
  37354. triggered
  37355. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  37356. rounded up to 1)
  37357. */
  37358. void startTimer (int timerId, int intervalInMilliseconds) noexcept;
  37359. /** Stops a timer.
  37360. If a timer has been started with the given ID number, it will be cancelled.
  37361. No more callbacks will be made for the specified timer after this method returns.
  37362. If this is called from a different thread, any callbacks that may
  37363. be currently executing may be allowed to finish before the method
  37364. returns.
  37365. */
  37366. void stopTimer (int timerId) noexcept;
  37367. /** Checks whether a timer has been started for a specified ID.
  37368. @returns true if a timer with the given ID is running.
  37369. */
  37370. bool isTimerRunning (int timerId) const noexcept;
  37371. /** Returns the interval for a specified timer ID.
  37372. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  37373. is running for the ID number specified.
  37374. */
  37375. int getTimerInterval (int timerId) const noexcept;
  37376. private:
  37377. class MultiTimerCallback;
  37378. SpinLock timerListLock;
  37379. OwnedArray <MultiTimerCallback> timers;
  37380. MultiTimer& operator= (const MultiTimer&);
  37381. };
  37382. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  37383. /*** End of inlined file: juce_MultiTimer.h ***/
  37384. #endif
  37385. #ifndef __JUCE_TIMER_JUCEHEADER__
  37386. #endif
  37387. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  37388. /*** Start of inlined file: juce_ArrowButton.h ***/
  37389. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  37390. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  37391. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  37392. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  37393. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  37394. /**
  37395. An effect filter that adds a drop-shadow behind the image's content.
  37396. (This will only work on images/components that aren't opaque, of course).
  37397. When added to a component, this effect will draw a soft-edged
  37398. shadow based on what gets drawn inside it. The shadow will also
  37399. be applied to the component's children.
  37400. For speed, this doesn't use a proper gaussian blur, but cheats by
  37401. using a simple bilinear filter. If you need a really high-quality
  37402. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  37403. @see Component::setComponentEffect
  37404. */
  37405. class JUCE_API DropShadowEffect : public ImageEffectFilter
  37406. {
  37407. public:
  37408. /** Creates a default drop-shadow effect.
  37409. To customise the shadow's appearance, use the setShadowProperties()
  37410. method.
  37411. */
  37412. DropShadowEffect();
  37413. /** Destructor. */
  37414. ~DropShadowEffect();
  37415. /** Sets up parameters affecting the shadow's appearance.
  37416. @param newRadius the (approximate) radius of the blur used
  37417. @param newOpacity the opacity with which the shadow is rendered
  37418. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  37419. component's contents
  37420. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  37421. component's contents
  37422. */
  37423. void setShadowProperties (float newRadius,
  37424. float newOpacity,
  37425. int newShadowOffsetX,
  37426. int newShadowOffsetY);
  37427. /** @internal */
  37428. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  37429. private:
  37430. int offsetX, offsetY;
  37431. float radius, opacity;
  37432. JUCE_LEAK_DETECTOR (DropShadowEffect);
  37433. };
  37434. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  37435. /*** End of inlined file: juce_DropShadowEffect.h ***/
  37436. /**
  37437. A button with an arrow in it.
  37438. @see Button
  37439. */
  37440. class JUCE_API ArrowButton : public Button
  37441. {
  37442. public:
  37443. /** Creates an ArrowButton.
  37444. @param buttonName the name to give the button
  37445. @param arrowDirection the direction the arrow should point in, where 0.0 is
  37446. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  37447. @param arrowColour the colour to use for the arrow
  37448. */
  37449. ArrowButton (const String& buttonName,
  37450. float arrowDirection,
  37451. const Colour& arrowColour);
  37452. /** Destructor. */
  37453. ~ArrowButton();
  37454. protected:
  37455. /** @internal */
  37456. void paintButton (Graphics& g,
  37457. bool isMouseOverButton,
  37458. bool isButtonDown);
  37459. /** @internal */
  37460. void buttonStateChanged();
  37461. private:
  37462. Colour colour;
  37463. DropShadowEffect shadow;
  37464. Path path;
  37465. int offset;
  37466. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ArrowButton);
  37467. };
  37468. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  37469. /*** End of inlined file: juce_ArrowButton.h ***/
  37470. #endif
  37471. #ifndef __JUCE_BUTTON_JUCEHEADER__
  37472. #endif
  37473. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  37474. /*** Start of inlined file: juce_DrawableButton.h ***/
  37475. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  37476. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  37477. /*** Start of inlined file: juce_Drawable.h ***/
  37478. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  37479. #define __JUCE_DRAWABLE_JUCEHEADER__
  37480. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  37481. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  37482. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  37483. /**
  37484. Expresses a coordinate as a dynamically evaluated expression.
  37485. @see RelativePoint, RelativeRectangle
  37486. */
  37487. class JUCE_API RelativeCoordinate
  37488. {
  37489. public:
  37490. /** Creates a zero coordinate. */
  37491. RelativeCoordinate();
  37492. RelativeCoordinate (const Expression& expression);
  37493. RelativeCoordinate (const RelativeCoordinate& other);
  37494. RelativeCoordinate& operator= (const RelativeCoordinate& other);
  37495. /** Creates an absolute position from the parent origin on either the X or Y axis.
  37496. @param absoluteDistanceFromOrigin the distance from the origin
  37497. */
  37498. RelativeCoordinate (double absoluteDistanceFromOrigin);
  37499. /** Recreates a coordinate from a string description.
  37500. The string will be parsed by ExpressionParser::parse().
  37501. @param stringVersion the expression to use
  37502. @see toString
  37503. */
  37504. RelativeCoordinate (const String& stringVersion);
  37505. /** Destructor. */
  37506. ~RelativeCoordinate();
  37507. bool operator== (const RelativeCoordinate& other) const noexcept;
  37508. bool operator!= (const RelativeCoordinate& other) const noexcept;
  37509. /** Calculates the absolute position of this coordinate.
  37510. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  37511. be needed to calculate the result.
  37512. */
  37513. double resolve (const Expression::Scope* evaluationScope) const;
  37514. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  37515. This will recursively check any coordinates upon which this one depends.
  37516. */
  37517. bool references (const String& coordName, const Expression::Scope* evaluationScope) const;
  37518. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  37519. bool isRecursive (const Expression::Scope* evaluationScope) const;
  37520. /** Returns true if this coordinate depends on any other coordinates for its position. */
  37521. bool isDynamic() const;
  37522. /** Changes the value of this coord to make it resolve to the specified position.
  37523. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  37524. or relative position to whatever value is necessary to make its resultant position
  37525. match the position that is provided.
  37526. */
  37527. void moveToAbsolute (double absoluteTargetPosition, const Expression::Scope* evaluationScope);
  37528. /** Returns the expression that defines this coordinate. */
  37529. const Expression& getExpression() const { return term; }
  37530. /** Returns a string which represents this coordinate.
  37531. For details of the string syntax, see the constructor notes.
  37532. */
  37533. const String toString() const;
  37534. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  37535. As well as avoiding using string literals in your code, using these preset values
  37536. has the advantage that all instances of the same string will share the same, reference-counted
  37537. String object, so if you have thousands of points which all refer to the same
  37538. anchor points, this can save a significant amount of memory allocation.
  37539. */
  37540. struct Strings
  37541. {
  37542. static const String parent; /**< "parent" */
  37543. static const String left; /**< "left" */
  37544. static const String right; /**< "right" */
  37545. static const String top; /**< "top" */
  37546. static const String bottom; /**< "bottom" */
  37547. static const String x; /**< "x" */
  37548. static const String y; /**< "y" */
  37549. static const String width; /**< "width" */
  37550. static const String height; /**< "height" */
  37551. };
  37552. struct StandardStrings
  37553. {
  37554. enum Type
  37555. {
  37556. left, right, top, bottom,
  37557. x, y, width, height,
  37558. parent,
  37559. unknown
  37560. };
  37561. static Type getTypeOf (const String& s) noexcept;
  37562. };
  37563. private:
  37564. Expression term;
  37565. };
  37566. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  37567. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  37568. /*** Start of inlined file: juce_RelativeCoordinatePositioner.h ***/
  37569. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37570. #define __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37571. /*** Start of inlined file: juce_RelativePoint.h ***/
  37572. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  37573. #define __JUCE_RELATIVEPOINT_JUCEHEADER__
  37574. /**
  37575. An X-Y position stored as a pair of RelativeCoordinate values.
  37576. @see RelativeCoordinate, RelativeRectangle
  37577. */
  37578. class JUCE_API RelativePoint
  37579. {
  37580. public:
  37581. /** Creates a point at the origin. */
  37582. RelativePoint();
  37583. /** Creates an absolute point, relative to the origin. */
  37584. RelativePoint (const Point<float>& absolutePoint);
  37585. /** Creates an absolute point, relative to the origin. */
  37586. RelativePoint (float absoluteX, float absoluteY);
  37587. /** Creates an absolute point from two coordinates. */
  37588. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  37589. /** Creates a point from a stringified representation.
  37590. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  37591. strings is explained in the RelativeCoordinate class.
  37592. @see toString
  37593. */
  37594. RelativePoint (const String& stringVersion);
  37595. bool operator== (const RelativePoint& other) const noexcept;
  37596. bool operator!= (const RelativePoint& other) const noexcept;
  37597. /** Calculates the absolute position of this point.
  37598. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  37599. be needed to calculate the result.
  37600. */
  37601. const Point<float> resolve (const Expression::Scope* evaluationContext) const;
  37602. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  37603. Calling this will leave any anchor points unchanged, but will set any absolute
  37604. or relative positions to whatever values are necessary to make the resultant position
  37605. match the position that is provided.
  37606. */
  37607. void moveToAbsolute (const Point<float>& newPos, const Expression::Scope* evaluationContext);
  37608. /** Returns a string which represents this point.
  37609. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  37610. coordinates, see the RelativeCoordinate constructor notes.
  37611. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  37612. */
  37613. const String toString() const;
  37614. /** Returns true if this point depends on any other coordinates for its position. */
  37615. bool isDynamic() const;
  37616. // The actual X and Y coords...
  37617. RelativeCoordinate x, y;
  37618. };
  37619. #endif // __JUCE_RELATIVEPOINT_JUCEHEADER__
  37620. /*** End of inlined file: juce_RelativePoint.h ***/
  37621. /*** Start of inlined file: juce_MarkerList.h ***/
  37622. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  37623. #define __JUCE_MARKERLIST_JUCEHEADER__
  37624. class Component;
  37625. /**
  37626. Holds a set of named marker points along a one-dimensional axis.
  37627. This class is used to store sets of X and Y marker points in components.
  37628. @see Component::getMarkers().
  37629. */
  37630. class JUCE_API MarkerList
  37631. {
  37632. public:
  37633. /** Creates an empty marker list. */
  37634. MarkerList();
  37635. /** Creates a copy of another marker list. */
  37636. MarkerList (const MarkerList& other);
  37637. /** Copies another marker list to this one. */
  37638. MarkerList& operator= (const MarkerList& other);
  37639. /** Destructor. */
  37640. ~MarkerList();
  37641. /** Represents a marker in a MarkerList. */
  37642. class JUCE_API Marker
  37643. {
  37644. public:
  37645. /** Creates a copy of another Marker. */
  37646. Marker (const Marker& other);
  37647. /** Creates a Marker with a given name and position. */
  37648. Marker (const String& name, const RelativeCoordinate& position);
  37649. /** The marker's name. */
  37650. String name;
  37651. /** The marker's position.
  37652. The expression used to define the coordinate may use the names of other
  37653. markers, so that markers can be linked in arbitrary ways, but be careful
  37654. not to create recursive loops of markers whose positions are based on each
  37655. other! It can also refer to "parent.right" and "parent.bottom" so that you
  37656. can set markers which are relative to the size of the component that contains
  37657. them.
  37658. To resolve the coordinate, you can use the MarkerList::getMarkerPosition() method.
  37659. */
  37660. RelativeCoordinate position;
  37661. /** Returns true if both the names and positions of these two markers match. */
  37662. bool operator== (const Marker&) const noexcept;
  37663. /** Returns true if either the name or position of these two markers differ. */
  37664. bool operator!= (const Marker&) const noexcept;
  37665. };
  37666. /** Returns the number of markers in the list. */
  37667. int getNumMarkers() const noexcept;
  37668. /** Returns one of the markers in the list, by its index. */
  37669. const Marker* getMarker (int index) const noexcept;
  37670. /** Returns a named marker, or 0 if no such name is found.
  37671. Note that name comparisons are case-sensitive.
  37672. */
  37673. const Marker* getMarker (const String& name) const noexcept;
  37674. /** Evaluates the given marker and returns its absolute position.
  37675. The parent component must be supplied in case the marker's expression refers to
  37676. the size of its parent component.
  37677. */
  37678. double getMarkerPosition (const Marker& marker, Component* parentComponent) const;
  37679. /** Sets the position of a marker.
  37680. If the name already exists, then the existing marker is moved; if it doesn't exist, then a
  37681. new marker is added.
  37682. */
  37683. void setMarker (const String& name, const RelativeCoordinate& position);
  37684. /** Deletes the marker at the given list index. */
  37685. void removeMarker (int index);
  37686. /** Deletes the marker with the given name. */
  37687. void removeMarker (const String& name);
  37688. /** Returns true if all the markers in these two lists match exactly. */
  37689. bool operator== (const MarkerList& other) const noexcept;
  37690. /** Returns true if not all the markers in these two lists match exactly. */
  37691. bool operator!= (const MarkerList& other) const noexcept;
  37692. /**
  37693. A class for receiving events when changes are made to a MarkerList.
  37694. You can register a MarkerList::Listener with a MarkerList using the MarkerList::addListener()
  37695. method, and it will be called when markers are moved, added, or deleted.
  37696. @see MarkerList::addListener, MarkerList::removeListener
  37697. */
  37698. class JUCE_API Listener
  37699. {
  37700. public:
  37701. /** Destructor. */
  37702. virtual ~Listener() {}
  37703. /** Called when something in the given marker list changes. */
  37704. virtual void markersChanged (MarkerList* markerList) = 0;
  37705. /** Called when the given marker list is being deleted. */
  37706. virtual void markerListBeingDeleted (MarkerList* markerList);
  37707. };
  37708. /** Registers a listener that will be called when the markers are changed. */
  37709. void addListener (Listener* listener);
  37710. /** Deregisters a previously-registered listener. */
  37711. void removeListener (Listener* listener);
  37712. /** Synchronously calls markersChanged() on all the registered listeners. */
  37713. void markersHaveChanged();
  37714. /** Forms a wrapper around a ValueTree that can be used for storing a MarkerList. */
  37715. class ValueTreeWrapper
  37716. {
  37717. public:
  37718. ValueTreeWrapper (const ValueTree& state);
  37719. ValueTree& getState() noexcept { return state; }
  37720. int getNumMarkers() const;
  37721. const ValueTree getMarkerState (int index) const;
  37722. const ValueTree getMarkerState (const String& name) const;
  37723. bool containsMarker (const ValueTree& state) const;
  37724. const MarkerList::Marker getMarker (const ValueTree& state) const;
  37725. void setMarker (const MarkerList::Marker& marker, UndoManager* undoManager);
  37726. void removeMarker (const ValueTree& state, UndoManager* undoManager);
  37727. void applyTo (MarkerList& markerList);
  37728. void readFrom (const MarkerList& markerList, UndoManager* undoManager);
  37729. static const Identifier markerTag, nameProperty, posProperty;
  37730. private:
  37731. ValueTree state;
  37732. };
  37733. private:
  37734. OwnedArray<Marker> markers;
  37735. ListenerList<Listener> listeners;
  37736. JUCE_LEAK_DETECTOR (MarkerList);
  37737. };
  37738. #endif // __JUCE_MARKERLIST_JUCEHEADER__
  37739. /*** End of inlined file: juce_MarkerList.h ***/
  37740. /**
  37741. Base class for Component::Positioners that are based upon relative coordinates.
  37742. */
  37743. class JUCE_API RelativeCoordinatePositionerBase : public Component::Positioner,
  37744. public ComponentListener,
  37745. public MarkerList::Listener
  37746. {
  37747. public:
  37748. RelativeCoordinatePositionerBase (Component& component_);
  37749. ~RelativeCoordinatePositionerBase();
  37750. void componentMovedOrResized (Component&, bool, bool);
  37751. void componentParentHierarchyChanged (Component&);
  37752. void componentChildrenChanged (Component& component);
  37753. void componentBeingDeleted (Component& component);
  37754. void markersChanged (MarkerList*);
  37755. void markerListBeingDeleted (MarkerList* markerList);
  37756. void apply();
  37757. bool addCoordinate (const RelativeCoordinate& coord);
  37758. bool addPoint (const RelativePoint& point);
  37759. /** Used for resolving a RelativeCoordinate expression in the context of a component. */
  37760. class ComponentScope : public Expression::Scope
  37761. {
  37762. public:
  37763. ComponentScope (Component& component_);
  37764. const Expression getSymbolValue (const String& symbol) const;
  37765. void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  37766. const String getScopeUID() const;
  37767. protected:
  37768. Component& component;
  37769. Component* findSiblingComponent (const String& componentID) const;
  37770. const MarkerList::Marker* findMarker (const String& name, MarkerList*& list) const;
  37771. private:
  37772. JUCE_DECLARE_NON_COPYABLE (ComponentScope);
  37773. };
  37774. protected:
  37775. virtual bool registerCoordinates() = 0;
  37776. virtual void applyToComponentBounds() = 0;
  37777. private:
  37778. class DependencyFinderScope;
  37779. friend class DependencyFinderScope;
  37780. Array <Component*> sourceComponents;
  37781. Array <MarkerList*> sourceMarkerLists;
  37782. bool registeredOk;
  37783. void registerComponentListener (Component& comp);
  37784. void registerMarkerListListener (MarkerList* const list);
  37785. void unregisterListeners();
  37786. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeCoordinatePositionerBase);
  37787. };
  37788. #endif // __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37789. /*** End of inlined file: juce_RelativeCoordinatePositioner.h ***/
  37790. /*** Start of inlined file: juce_ComponentBuilder.h ***/
  37791. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37792. #define __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37793. /**
  37794. Loads and maintains a tree of Components from a ValueTree that represents them.
  37795. To allow the state of a tree of components to be saved as a ValueTree and re-loaded,
  37796. this class lets you register a set of type-handlers for the different components that
  37797. are involved, and then uses these types to re-create a set of components from its
  37798. stored state.
  37799. Essentially, to use this, you need to create a ComponentBuilder with your ValueTree,
  37800. then use registerTypeHandler() to give it a set of type handlers that can cope with
  37801. all the items in your tree. Then you can call getComponent() to build the component.
  37802. Once you've got the component you can either take it and delete the ComponentBuilder
  37803. object, or if you keep the ComponentBuilder around, it'll monitor any changes in the
  37804. ValueTree and automatically update the component to reflect these changes.
  37805. */
  37806. class JUCE_API ComponentBuilder : public ValueTree::Listener
  37807. {
  37808. public:
  37809. /** Creates a ComponentBuilder that will use the given state.
  37810. Once you've created your builder, you should use registerTypeHandler() to register some
  37811. type handlers for it, and then you can call createComponent() or getManagedComponent()
  37812. to get the actual component.
  37813. */
  37814. explicit ComponentBuilder (const ValueTree& state);
  37815. /** Destructor. */
  37816. ~ComponentBuilder();
  37817. /** Returns the ValueTree that this builder is working with. */
  37818. ValueTree& getState() noexcept { return state; }
  37819. /** Returns the ValueTree that this builder is working with. */
  37820. const ValueTree& getState() const noexcept { return state; }
  37821. /** Returns the builder's component (creating it if necessary).
  37822. The first time that this method is called, the builder will attempt to create a component
  37823. from the ValueTree, so you must have registered some suitable type handlers before calling
  37824. this. If there's a problem and the component can't be created, this method returns 0.
  37825. The component that is returned is owned by this ComponentBuilder, so you can put it inside
  37826. your own parent components, but don't delete it! The ComponentBuilder will delete it automatically
  37827. when the builder is destroyed. If you want to get a component that you can delete yourself,
  37828. call createComponent() instead.
  37829. The ComponentBuilder will update this component if any changes are made to the ValueTree, so if
  37830. there's a chance that the tree might change, be careful not to keep any pointers to sub-components,
  37831. as they may be changed or removed.
  37832. */
  37833. Component* getManagedComponent();
  37834. /** Creates and returns a new instance of the component that the ValueTree represents.
  37835. The caller is responsible for using and deleting the object that is returned. Unlike
  37836. getManagedComponent(), the component that is returned will not be updated by the builder.
  37837. */
  37838. Component* createComponent();
  37839. /**
  37840. The class is a base class for objects that manage the loading of a type of component
  37841. from a ValueTree.
  37842. To store and re-load a tree of components as a ValueTree, each component type must have
  37843. a TypeHandler to represent it.
  37844. @see ComponentBuilder::registerTypeHandler(), Drawable::registerDrawableTypeHandlers()
  37845. */
  37846. class JUCE_API TypeHandler
  37847. {
  37848. public:
  37849. /** Creates a TypeHandler.
  37850. The valueTreeType must be the type name of the ValueTrees that this handler can parse.
  37851. */
  37852. explicit TypeHandler (const Identifier& valueTreeType);
  37853. /** Destructor. */
  37854. virtual ~TypeHandler();
  37855. /** Returns the type of the ValueTrees that this handler can parse. */
  37856. const Identifier& getType() const noexcept { return valueTreeType; }
  37857. /** Returns the builder that this type is registered with. */
  37858. ComponentBuilder* getBuilder() const noexcept;
  37859. /** This method must create a new component from the given state, add it to the specified
  37860. parent component (which may be null), and return it.
  37861. The ValueTree will have been pre-checked to make sure that its type matches the type
  37862. that this handler supports.
  37863. There's no need to set the new Component's ID to match that of the state - the builder
  37864. will take care of that itself.
  37865. */
  37866. virtual Component* addNewComponentFromState (const ValueTree& state, Component* parent) = 0;
  37867. /** This method must update an existing component from a new ValueTree state.
  37868. A component that has been created with addNewComponentFromState() may need to be updated
  37869. if the ValueTree changes, so this method is used to do that. Your implementation must do
  37870. whatever's necessary to update the component from the new state provided.
  37871. The ValueTree will have been pre-checked to make sure that its type matches the type
  37872. that this handler supports, and the component will have been created by this type's
  37873. addNewComponentFromState() method.
  37874. */
  37875. virtual void updateComponentFromState (Component* component, const ValueTree& state) = 0;
  37876. private:
  37877. friend class ComponentBuilder;
  37878. ComponentBuilder* builder;
  37879. const Identifier valueTreeType;
  37880. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypeHandler);
  37881. };
  37882. /** Adds a type handler that the builder can use when trying to load components.
  37883. @see Drawable::registerDrawableTypeHandlers()
  37884. */
  37885. void registerTypeHandler (TypeHandler* type);
  37886. /** Tries to find a registered type handler that can load a component from the given ValueTree. */
  37887. TypeHandler* getHandlerForState (const ValueTree& state) const;
  37888. /** Returns the number of registered type handlers.
  37889. @see getHandler, registerTypeHandler
  37890. */
  37891. int getNumHandlers() const noexcept;
  37892. /** Returns one of the registered type handlers.
  37893. @see getNumHandlers, registerTypeHandler
  37894. */
  37895. TypeHandler* getHandler (int index) const noexcept;
  37896. /** This class is used when references to images need to be stored in ValueTrees.
  37897. An instance of an ImageProvider provides a mechanism for converting an Image to/from
  37898. a reference, which may be a file, URL, ID string, or whatever system is appropriate in
  37899. your app.
  37900. When you're loading components from a ValueTree that may need a way of loading images, you
  37901. should call ComponentBuilder::setImageProvider() to supply a suitable provider before
  37902. trying to load the component.
  37903. @see ComponentBuilder::setImageProvider()
  37904. */
  37905. class JUCE_API ImageProvider
  37906. {
  37907. public:
  37908. ImageProvider() {}
  37909. virtual ~ImageProvider() {}
  37910. /** Retrieves the image associated with this identifier, which could be any
  37911. kind of string, number, filename, etc.
  37912. The image that is returned will be owned by the caller, but it may come
  37913. from the ImageCache.
  37914. */
  37915. virtual const Image getImageForIdentifier (const var& imageIdentifier) = 0;
  37916. /** Returns an identifier to be used to refer to a given image.
  37917. This is used when a reference to an image is stored in a ValueTree.
  37918. */
  37919. virtual const var getIdentifierForImage (const Image& image) = 0;
  37920. };
  37921. /** Gives the builder an ImageProvider object that the type handlers can use when
  37922. loading images from stored references.
  37923. The object that is passed in is not owned by the builder, so the caller must delete
  37924. it when it is no longer needed, but not while the builder may still be using it. To
  37925. clear the image provider, just call setImageProvider (nullptr).
  37926. */
  37927. void setImageProvider (ImageProvider* newImageProvider) noexcept;
  37928. /** Returns the current image provider that this builder is using, or 0 if none has been set. */
  37929. ImageProvider* getImageProvider() const noexcept;
  37930. /** Updates the children of a parent component by updating them from the children of
  37931. a given ValueTree.
  37932. */
  37933. void updateChildComponents (Component& parent, const ValueTree& children);
  37934. /** An identifier for the property of the ValueTrees that is used to store a unique ID
  37935. for that component.
  37936. */
  37937. static const Identifier idProperty;
  37938. /** @internal */
  37939. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& property);
  37940. /** @internal */
  37941. void valueTreeChildAdded (ValueTree& parentTree, ValueTree& childWhichHasBeenAdded);
  37942. /** @internal */
  37943. void valueTreeChildRemoved (ValueTree& parentTree, ValueTree& childWhichHasBeenRemoved);
  37944. /** @internal */
  37945. void valueTreeChildOrderChanged (ValueTree& parentTree);
  37946. /** @internal */
  37947. void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged);
  37948. private:
  37949. ValueTree state;
  37950. OwnedArray <TypeHandler> types;
  37951. ScopedPointer<Component> component;
  37952. ImageProvider* imageProvider;
  37953. #if JUCE_DEBUG
  37954. WeakReference<Component> componentRef;
  37955. #endif
  37956. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBuilder);
  37957. };
  37958. #endif // __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37959. /*** End of inlined file: juce_ComponentBuilder.h ***/
  37960. class DrawableComposite;
  37961. /**
  37962. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  37963. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37964. */
  37965. class JUCE_API Drawable : public Component
  37966. {
  37967. protected:
  37968. /** The base class can't be instantiated directly.
  37969. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37970. */
  37971. Drawable();
  37972. public:
  37973. /** Destructor. */
  37974. virtual ~Drawable();
  37975. /** Creates a deep copy of this Drawable object.
  37976. Use this to create a new copy of this and any sub-objects in the tree.
  37977. */
  37978. virtual Drawable* createCopy() const = 0;
  37979. /** Renders this Drawable object.
  37980. Note that the preferred way to render a drawable in future is by using it
  37981. as a component and adding it to a parent, so you might want to consider that
  37982. before using this method.
  37983. @see drawWithin
  37984. */
  37985. void draw (Graphics& g, float opacity,
  37986. const AffineTransform& transform = AffineTransform::identity) const;
  37987. /** Renders the Drawable at a given offset within the Graphics context.
  37988. The co-ordinates passed-in are used to translate the object relative to its own
  37989. origin before drawing it - this is basically a quick way of saying:
  37990. @code
  37991. draw (g, AffineTransform::translation (x, y)).
  37992. @endcode
  37993. Note that the preferred way to render a drawable in future is by using it
  37994. as a component and adding it to a parent, so you might want to consider that
  37995. before using this method.
  37996. */
  37997. void drawAt (Graphics& g, float x, float y, float opacity) const;
  37998. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  37999. changing its aspect-ratio.
  38000. The object can placed arbitrarily within the rectangle based on a Justification type,
  38001. and can either be made as big as possible, or just reduced to fit.
  38002. Note that the preferred way to render a drawable in future is by using it
  38003. as a component and adding it to a parent, so you might want to consider that
  38004. before using this method.
  38005. @param g the graphics context to render onto
  38006. @param destArea the target rectangle to fit the drawable into
  38007. @param placement defines the alignment and rescaling to use to fit
  38008. this object within the target rectangle.
  38009. @param opacity the opacity to use, in the range 0 to 1.0
  38010. */
  38011. void drawWithin (Graphics& g,
  38012. const Rectangle<float>& destArea,
  38013. const RectanglePlacement& placement,
  38014. float opacity) const;
  38015. /** Resets any transformations on this drawable, and positions its origin within
  38016. its parent component.
  38017. */
  38018. void setOriginWithOriginalSize (const Point<float>& originWithinParent);
  38019. /** Sets a transform for this drawable that will position it within the specified
  38020. area of its parent component.
  38021. */
  38022. void setTransformToFit (const Rectangle<float>& areaInParent, const RectanglePlacement& placement);
  38023. /** Returns the DrawableComposite that contains this object, if there is one. */
  38024. DrawableComposite* getParent() const;
  38025. /** Tries to turn some kind of image file into a drawable.
  38026. The data could be an image that the ImageFileFormat class understands, or it
  38027. could be SVG.
  38028. */
  38029. static Drawable* createFromImageData (const void* data, size_t numBytes);
  38030. /** Tries to turn a stream containing some kind of image data into a drawable.
  38031. The data could be an image that the ImageFileFormat class understands, or it
  38032. could be SVG.
  38033. */
  38034. static Drawable* createFromImageDataStream (InputStream& dataSource);
  38035. /** Tries to turn a file containing some kind of image data into a drawable.
  38036. The data could be an image that the ImageFileFormat class understands, or it
  38037. could be SVG.
  38038. */
  38039. static Drawable* createFromImageFile (const File& file);
  38040. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  38041. into a Drawable tree.
  38042. The object returned must be deleted by the caller. If something goes wrong
  38043. while parsing, it may return 0.
  38044. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  38045. implementation, but it can return the basic vector objects.
  38046. */
  38047. static Drawable* createFromSVG (const XmlElement& svgDocument);
  38048. /** Tries to create a Drawable from a previously-saved ValueTree.
  38049. The ValueTree must have been created by the createValueTree() method.
  38050. If there are any images used within the drawable, you'll need to provide a valid
  38051. ImageProvider object that can be used to retrieve these images from whatever type
  38052. of identifier is used to represent them.
  38053. Internally, this uses a ComponentBuilder, and registerDrawableTypeHandlers().
  38054. */
  38055. static Drawable* createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider);
  38056. /** Creates a ValueTree to represent this Drawable.
  38057. The ValueTree that is returned can be turned back into a Drawable with createFromValueTree().
  38058. If there are any images used in this drawable, you'll need to provide a valid ImageProvider
  38059. object that can be used to create storable representations of them.
  38060. */
  38061. virtual const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const = 0;
  38062. /** Returns the area that this drawble covers.
  38063. The result is expressed in this drawable's own coordinate space, and does not take
  38064. into account any transforms that may be applied to the component.
  38065. */
  38066. virtual const Rectangle<float> getDrawableBounds() const = 0;
  38067. /** Internal class used to manage ValueTrees that represent Drawables. */
  38068. class ValueTreeWrapperBase
  38069. {
  38070. public:
  38071. ValueTreeWrapperBase (const ValueTree& state);
  38072. ValueTree& getState() noexcept { return state; }
  38073. const String getID() const;
  38074. void setID (const String& newID);
  38075. ValueTree state;
  38076. };
  38077. /** Registers a set of ComponentBuilder::TypeHandler objects that can be used to
  38078. load all the different Drawable types from a saved state.
  38079. @see ComponentBuilder::registerTypeHandler()
  38080. */
  38081. static void registerDrawableTypeHandlers (ComponentBuilder& componentBuilder);
  38082. protected:
  38083. friend class DrawableComposite;
  38084. friend class DrawableShape;
  38085. /** @internal */
  38086. void transformContextToCorrectOrigin (Graphics& g);
  38087. /** @internal */
  38088. void parentHierarchyChanged();
  38089. /** @internal */
  38090. void setBoundsToEnclose (const Rectangle<float>& area);
  38091. Point<int> originRelativeToComponent;
  38092. #ifndef DOXYGEN
  38093. /** Internal utility class used by Drawables. */
  38094. template <class DrawableType>
  38095. class Positioner : public RelativeCoordinatePositionerBase
  38096. {
  38097. public:
  38098. Positioner (DrawableType& component_)
  38099. : RelativeCoordinatePositionerBase (component_),
  38100. owner (component_)
  38101. {}
  38102. bool registerCoordinates() { return owner.registerCoordinates (*this); }
  38103. void applyToComponentBounds()
  38104. {
  38105. ComponentScope scope (getComponent());
  38106. owner.recalculateCoordinates (&scope);
  38107. }
  38108. void applyNewBounds (const Rectangle<int>&)
  38109. {
  38110. jassertfalse; // drawables can't be resized directly!
  38111. }
  38112. private:
  38113. DrawableType& owner;
  38114. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  38115. };
  38116. #endif
  38117. private:
  38118. void nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform);
  38119. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Drawable);
  38120. };
  38121. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  38122. /*** End of inlined file: juce_Drawable.h ***/
  38123. /**
  38124. A button that displays a Drawable.
  38125. Up to three Drawable objects can be given to this button, to represent the
  38126. 'normal', 'over' and 'down' states.
  38127. @see Button
  38128. */
  38129. class JUCE_API DrawableButton : public Button
  38130. {
  38131. public:
  38132. enum ButtonStyle
  38133. {
  38134. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  38135. ImageRaw, /**< The button will just display the images in their normal size and position.
  38136. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  38137. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  38138. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  38139. };
  38140. /** Creates a DrawableButton.
  38141. After creating one of these, use setImages() to specify the drawables to use.
  38142. @param buttonName the name to give the component
  38143. @param buttonStyle the layout to use
  38144. @see ButtonStyle, setButtonStyle, setImages
  38145. */
  38146. DrawableButton (const String& buttonName,
  38147. ButtonStyle buttonStyle);
  38148. /** Destructor. */
  38149. ~DrawableButton();
  38150. /** Sets up the images to draw for the various button states.
  38151. The button will keep its own internal copies of these drawables.
  38152. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  38153. will be made of the object passed-in if it is non-zero.
  38154. @param overImage the thing to draw for the button's 'over' state - if this is
  38155. zero, the button's normal image will be used when the mouse is
  38156. over it. An internal copy will be made of the object passed-in
  38157. if it is non-zero.
  38158. @param downImage the thing to draw for the button's 'down' state - if this is
  38159. zero, the 'over' image will be used instead (or the normal image
  38160. as a last resort). An internal copy will be made of the object
  38161. passed-in if it is non-zero.
  38162. @param disabledImage an image to draw when the button is disabled. If this is zero,
  38163. the normal image will be drawn with a reduced opacity instead.
  38164. An internal copy will be made of the object passed-in if it is
  38165. non-zero.
  38166. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  38167. state is 'on'. If this is 0, the normal image is used instead
  38168. @param overImageOn same as the overImage, but this is used when the button's toggle
  38169. state is 'on'. If this is 0, the normalImageOn is drawn instead
  38170. @param downImageOn same as the downImage, but this is used when the button's toggle
  38171. state is 'on'. If this is 0, the overImageOn is drawn instead
  38172. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  38173. state is 'on'. If this is 0, the normal image will be drawn instead
  38174. with a reduced opacity
  38175. */
  38176. void setImages (const Drawable* normalImage,
  38177. const Drawable* overImage = nullptr,
  38178. const Drawable* downImage = nullptr,
  38179. const Drawable* disabledImage = nullptr,
  38180. const Drawable* normalImageOn = nullptr,
  38181. const Drawable* overImageOn = nullptr,
  38182. const Drawable* downImageOn = nullptr,
  38183. const Drawable* disabledImageOn = nullptr);
  38184. /** Changes the button's style.
  38185. @see ButtonStyle
  38186. */
  38187. void setButtonStyle (ButtonStyle newStyle);
  38188. /** Changes the button's background colours.
  38189. The toggledOffColour is the colour to use when the button's toggle state
  38190. is off, and toggledOnColour when it's on.
  38191. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  38192. used to fill the background of the component.
  38193. For an ImageOnButtonBackground style, the colour is used to draw the
  38194. button's lozenge shape and exactly how the colour's used will depend
  38195. on the LookAndFeel.
  38196. */
  38197. void setBackgroundColours (const Colour& toggledOffColour,
  38198. const Colour& toggledOnColour);
  38199. /** Returns the current background colour being used.
  38200. @see setBackgroundColour
  38201. */
  38202. const Colour& getBackgroundColour() const noexcept;
  38203. /** Gives the button an optional amount of space around the edge of the drawable.
  38204. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  38205. ones on a button background. If the button is too small for the given gap, a
  38206. smaller gap will be used.
  38207. By default there's a gap of about 3 pixels.
  38208. */
  38209. void setEdgeIndent (int numPixelsIndent);
  38210. /** Returns the image that the button is currently displaying. */
  38211. Drawable* getCurrentImage() const noexcept;
  38212. Drawable* getNormalImage() const noexcept;
  38213. Drawable* getOverImage() const noexcept;
  38214. Drawable* getDownImage() const noexcept;
  38215. /** A set of colour IDs to use to change the colour of various aspects of the link.
  38216. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38217. methods.
  38218. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38219. */
  38220. enum ColourIds
  38221. {
  38222. textColourId = 0x1004010, /**< The colour to use for the URL text. */
  38223. };
  38224. protected:
  38225. /** @internal */
  38226. void paintButton (Graphics& g,
  38227. bool isMouseOverButton,
  38228. bool isButtonDown);
  38229. /** @internal */
  38230. void buttonStateChanged();
  38231. /** @internal */
  38232. void resized();
  38233. private:
  38234. ButtonStyle style;
  38235. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  38236. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  38237. Drawable* currentImage;
  38238. Colour backgroundOff, backgroundOn;
  38239. int edgeIndent;
  38240. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DrawableButton);
  38241. };
  38242. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  38243. /*** End of inlined file: juce_DrawableButton.h ***/
  38244. #endif
  38245. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  38246. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  38247. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  38248. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  38249. /**
  38250. A button showing an underlined weblink, that will launch the link
  38251. when it's clicked.
  38252. @see Button
  38253. */
  38254. class JUCE_API HyperlinkButton : public Button
  38255. {
  38256. public:
  38257. /** Creates a HyperlinkButton.
  38258. @param linkText the text that will be displayed in the button - this is
  38259. also set as the Component's name, but the text can be
  38260. changed later with the Button::getButtonText() method
  38261. @param linkURL the URL to launch when the user clicks the button
  38262. */
  38263. HyperlinkButton (const String& linkText,
  38264. const URL& linkURL);
  38265. /** Destructor. */
  38266. ~HyperlinkButton();
  38267. /** Changes the font to use for the text.
  38268. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  38269. to match the size of the component.
  38270. */
  38271. void setFont (const Font& newFont,
  38272. bool resizeToMatchComponentHeight,
  38273. const Justification& justificationType = Justification::horizontallyCentred);
  38274. /** A set of colour IDs to use to change the colour of various aspects of the link.
  38275. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38276. methods.
  38277. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38278. */
  38279. enum ColourIds
  38280. {
  38281. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  38282. };
  38283. /** Changes the URL that the button will trigger. */
  38284. void setURL (const URL& newURL) noexcept;
  38285. /** Returns the URL that the button will trigger. */
  38286. const URL& getURL() const noexcept { return url; }
  38287. /** Resizes the button horizontally to fit snugly around the text.
  38288. This won't affect the button's height.
  38289. */
  38290. void changeWidthToFitText();
  38291. protected:
  38292. /** @internal */
  38293. void clicked();
  38294. /** @internal */
  38295. void colourChanged();
  38296. /** @internal */
  38297. void paintButton (Graphics& g,
  38298. bool isMouseOverButton,
  38299. bool isButtonDown);
  38300. private:
  38301. URL url;
  38302. Font font;
  38303. bool resizeFont;
  38304. Justification justification;
  38305. const Font getFontToUse() const;
  38306. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HyperlinkButton);
  38307. };
  38308. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  38309. /*** End of inlined file: juce_HyperlinkButton.h ***/
  38310. #endif
  38311. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  38312. /*** Start of inlined file: juce_ImageButton.h ***/
  38313. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  38314. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  38315. /**
  38316. As the title suggests, this is a button containing an image.
  38317. The colour and transparency of the image can be set to vary when the
  38318. button state changes.
  38319. @see Button, ShapeButton, TextButton
  38320. */
  38321. class JUCE_API ImageButton : public Button
  38322. {
  38323. public:
  38324. /** Creates an ImageButton.
  38325. Use setImage() to specify the image to use. The colours and opacities that
  38326. are specified here can be changed later using setDrawingOptions().
  38327. @param name the name to give the component
  38328. */
  38329. explicit ImageButton (const String& name);
  38330. /** Destructor. */
  38331. ~ImageButton();
  38332. /** Sets up the images to draw in various states.
  38333. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  38334. resized to the same dimensions as the normal image
  38335. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  38336. button when the button's size changes
  38337. @param preserveImageProportions if true then any rescaling of the image to fit
  38338. the button will keep the image's x and y proportions
  38339. correct - i.e. it won't distort its shape, although
  38340. this might create gaps around the edges
  38341. @param normalImage the image to use when the button is in its normal state.
  38342. button no longer needs it.
  38343. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  38344. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  38345. normal image - if this colour is transparent, no overlay
  38346. will be drawn. The overlay will be drawn over the top of the
  38347. image, so you can basically add a solid or semi-transparent
  38348. colour to the image to brighten or darken it
  38349. @param overImage the image to use when the mouse is over the button. If
  38350. you want to use the same image as was set in the normalImage
  38351. parameter, this value can be a null image.
  38352. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  38353. is over the button
  38354. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  38355. image when the mouse is over - if this colour is transparent,
  38356. no overlay will be drawn
  38357. @param downImage an image to use when the button is pressed down. If set
  38358. to a null image, the 'over' image will be drawn instead (or the
  38359. normal image if there isn't an 'over' image either).
  38360. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  38361. is pressed
  38362. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  38363. image when the button is pressed down - if this colour is
  38364. transparent, no overlay will be drawn
  38365. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  38366. whenever it's inside the button's bounding rectangle. If
  38367. set to values higher than 0, the mouse will only be
  38368. considered to be over the image when the value of the
  38369. image's alpha channel at that position is greater than
  38370. this level.
  38371. */
  38372. void setImages (bool resizeButtonNowToFitThisImage,
  38373. bool rescaleImagesWhenButtonSizeChanges,
  38374. bool preserveImageProportions,
  38375. const Image& normalImage,
  38376. float imageOpacityWhenNormal,
  38377. const Colour& overlayColourWhenNormal,
  38378. const Image& overImage,
  38379. float imageOpacityWhenOver,
  38380. const Colour& overlayColourWhenOver,
  38381. const Image& downImage,
  38382. float imageOpacityWhenDown,
  38383. const Colour& overlayColourWhenDown,
  38384. float hitTestAlphaThreshold = 0.0f);
  38385. /** Returns the currently set 'normal' image. */
  38386. const Image getNormalImage() const;
  38387. /** Returns the image that's drawn when the mouse is over the button.
  38388. If a valid 'over' image has been set, this will return it; otherwise it'll
  38389. just return the normal image.
  38390. */
  38391. const Image getOverImage() const;
  38392. /** Returns the image that's drawn when the button is held down.
  38393. If a valid 'down' image has been set, this will return it; otherwise it'll
  38394. return the 'over' image or normal image, depending on what's available.
  38395. */
  38396. const Image getDownImage() const;
  38397. protected:
  38398. /** @internal */
  38399. bool hitTest (int x, int y);
  38400. /** @internal */
  38401. void paintButton (Graphics& g,
  38402. bool isMouseOverButton,
  38403. bool isButtonDown);
  38404. private:
  38405. bool scaleImageToFit, preserveProportions;
  38406. unsigned char alphaThreshold;
  38407. int imageX, imageY, imageW, imageH;
  38408. Image normalImage, overImage, downImage;
  38409. float normalOpacity, overOpacity, downOpacity;
  38410. Colour normalOverlay, overOverlay, downOverlay;
  38411. const Image getCurrentImage() const;
  38412. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageButton);
  38413. };
  38414. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  38415. /*** End of inlined file: juce_ImageButton.h ***/
  38416. #endif
  38417. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  38418. /*** Start of inlined file: juce_ShapeButton.h ***/
  38419. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  38420. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  38421. /**
  38422. A button that contains a filled shape.
  38423. @see Button, ImageButton, TextButton, ArrowButton
  38424. */
  38425. class JUCE_API ShapeButton : public Button
  38426. {
  38427. public:
  38428. /** Creates a ShapeButton.
  38429. @param name a name to give the component - see Component::setName()
  38430. @param normalColour the colour to fill the shape with when the mouse isn't over
  38431. @param overColour the colour to use when the mouse is over the shape
  38432. @param downColour the colour to use when the button is in the pressed-down state
  38433. */
  38434. ShapeButton (const String& name,
  38435. const Colour& normalColour,
  38436. const Colour& overColour,
  38437. const Colour& downColour);
  38438. /** Destructor. */
  38439. ~ShapeButton();
  38440. /** Sets the shape to use.
  38441. @param newShape the shape to use
  38442. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  38443. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  38444. the button is resized
  38445. @param hasDropShadow if true, the button will be given a drop-shadow effect
  38446. */
  38447. void setShape (const Path& newShape,
  38448. bool resizeNowToFitThisShape,
  38449. bool maintainShapeProportions,
  38450. bool hasDropShadow);
  38451. /** Set the colours to use for drawing the shape.
  38452. @param normalColour the colour to fill the shape with when the mouse isn't over
  38453. @param overColour the colour to use when the mouse is over the shape
  38454. @param downColour the colour to use when the button is in the pressed-down state
  38455. */
  38456. void setColours (const Colour& normalColour,
  38457. const Colour& overColour,
  38458. const Colour& downColour);
  38459. /** Sets up an outline to draw around the shape.
  38460. @param outlineColour the colour to use
  38461. @param outlineStrokeWidth the thickness of line to draw
  38462. */
  38463. void setOutline (const Colour& outlineColour,
  38464. float outlineStrokeWidth);
  38465. protected:
  38466. /** @internal */
  38467. void paintButton (Graphics& g,
  38468. bool isMouseOverButton,
  38469. bool isButtonDown);
  38470. private:
  38471. Colour normalColour, overColour, downColour, outlineColour;
  38472. DropShadowEffect shadow;
  38473. Path shape;
  38474. bool maintainShapeProportions;
  38475. float outlineWidth;
  38476. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ShapeButton);
  38477. };
  38478. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  38479. /*** End of inlined file: juce_ShapeButton.h ***/
  38480. #endif
  38481. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  38482. #endif
  38483. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  38484. /*** Start of inlined file: juce_ToggleButton.h ***/
  38485. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  38486. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  38487. /**
  38488. A button that can be toggled on/off.
  38489. All buttons can be toggle buttons, but this lets you create one of the
  38490. standard ones which has a tick-box and a text label next to it.
  38491. @see Button, DrawableButton, TextButton
  38492. */
  38493. class JUCE_API ToggleButton : public Button
  38494. {
  38495. public:
  38496. /** Creates a ToggleButton.
  38497. @param buttonText the text to put in the button (the component's name is also
  38498. initially set to this string, but these can be changed later
  38499. using the setName() and setButtonText() methods)
  38500. */
  38501. explicit ToggleButton (const String& buttonText = String::empty);
  38502. /** Destructor. */
  38503. ~ToggleButton();
  38504. /** Resizes the button to fit neatly around its current text.
  38505. The button's height won't be affected, only its width.
  38506. */
  38507. void changeWidthToFitText();
  38508. /** A set of colour IDs to use to change the colour of various aspects of the button.
  38509. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38510. methods.
  38511. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38512. */
  38513. enum ColourIds
  38514. {
  38515. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  38516. };
  38517. protected:
  38518. /** @internal */
  38519. void paintButton (Graphics& g,
  38520. bool isMouseOverButton,
  38521. bool isButtonDown);
  38522. /** @internal */
  38523. void colourChanged();
  38524. private:
  38525. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToggleButton);
  38526. };
  38527. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  38528. /*** End of inlined file: juce_ToggleButton.h ***/
  38529. #endif
  38530. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38531. /*** Start of inlined file: juce_ToolbarButton.h ***/
  38532. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38533. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38534. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  38535. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  38536. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  38537. /*** Start of inlined file: juce_Toolbar.h ***/
  38538. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  38539. #define __JUCE_TOOLBAR_JUCEHEADER__
  38540. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  38541. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38542. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38543. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  38544. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  38545. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  38546. /**
  38547. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  38548. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  38549. derive your component from this class, and make sure that it is somewhere inside a
  38550. DragAndDropContainer component.
  38551. Note: If all that you need to do is to respond to files being drag-and-dropped from
  38552. the operating system onto your component, you don't need any of these classes: instead
  38553. see the FileDragAndDropTarget class.
  38554. @see DragAndDropContainer, FileDragAndDropTarget
  38555. */
  38556. class JUCE_API DragAndDropTarget
  38557. {
  38558. public:
  38559. /** Destructor. */
  38560. virtual ~DragAndDropTarget() {}
  38561. /** Contains details about the source of a drag-and-drop operation.
  38562. The contents of this
  38563. */
  38564. class JUCE_API SourceDetails
  38565. {
  38566. public:
  38567. /** Creates a SourceDetails object from its various settings. */
  38568. SourceDetails (const var& description, Component* sourceComponent, const Point<int>& localPosition) noexcept;
  38569. /** A descriptor for the drag - this is set DragAndDropContainer::startDragging(). */
  38570. var description;
  38571. /** The component from the drag operation was started. */
  38572. WeakReference<Component> sourceComponent;
  38573. /** The local position of the mouse, relative to the target component.
  38574. Note that for calls such as isInterestedInDragSource(), this may be a null position.
  38575. */
  38576. Point<int> localPosition;
  38577. };
  38578. /** Callback to check whether this target is interested in the type of object being
  38579. dragged.
  38580. @param dragSourceDetails contains information about the source of the drag operation.
  38581. @returns true if this component wants to receive the other callbacks regarging this
  38582. type of object; if it returns false, no other callbacks will be made.
  38583. */
  38584. virtual bool isInterestedInDragSource (const SourceDetails& dragSourceDetails) = 0;
  38585. /** Callback to indicate that something is being dragged over this component.
  38586. This gets called when the user moves the mouse into this component while dragging
  38587. something.
  38588. Use this callback as a trigger to make your component repaint itself to give the
  38589. user feedback about whether the item can be dropped here or not.
  38590. @param dragSourceDetails contains information about the source of the drag operation.
  38591. @see itemDragExit
  38592. */
  38593. virtual void itemDragEnter (const SourceDetails& dragSourceDetails);
  38594. /** Callback to indicate that the user is dragging something over this component.
  38595. This gets called when the user moves the mouse over this component while dragging
  38596. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  38597. this lets you know what happens in-between.
  38598. @param dragSourceDetails contains information about the source of the drag operation.
  38599. */
  38600. virtual void itemDragMove (const SourceDetails& dragSourceDetails);
  38601. /** Callback to indicate that something has been dragged off the edge of this component.
  38602. This gets called when the user moves the mouse out of this component while dragging
  38603. something.
  38604. If you've used itemDragEnter() to repaint your component and give feedback, use this
  38605. as a signal to repaint it in its normal state.
  38606. @param dragSourceDetails contains information about the source of the drag operation.
  38607. @see itemDragEnter
  38608. */
  38609. virtual void itemDragExit (const SourceDetails& dragSourceDetails);
  38610. /** Callback to indicate that the user has dropped something onto this component.
  38611. When the user drops an item this get called, and you can use the description to
  38612. work out whether your object wants to deal with it or not.
  38613. Note that after this is called, the itemDragExit method may not be called, so you should
  38614. clean up in here if there's anything you need to do when the drag finishes.
  38615. @param dragSourceDetails contains information about the source of the drag operation.
  38616. */
  38617. virtual void itemDropped (const SourceDetails& dragSourceDetails) = 0;
  38618. /** Overriding this allows the target to tell the drag container whether to
  38619. draw the drag image while the cursor is over it.
  38620. By default it returns true, but if you return false, then the normal drag
  38621. image will not be shown when the cursor is over this target.
  38622. */
  38623. virtual bool shouldDrawDragImageWhenOver();
  38624. private:
  38625. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  38626. // The parameters for these methods have changed - please update your code!
  38627. virtual void isInterestedInDragSource (const String&, Component*) {}
  38628. virtual int itemDragEnter (const String&, Component*, int, int) { return 0; }
  38629. virtual int itemDragMove (const String&, Component*, int, int) { return 0; }
  38630. virtual int itemDragExit (const String&, Component*) { return 0; }
  38631. virtual int itemDropped (const String&, Component*, int, int) { return 0; }
  38632. #endif
  38633. };
  38634. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  38635. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  38636. /**
  38637. Enables drag-and-drop behaviour for a component and all its sub-components.
  38638. For a component to be able to make or receive drag-and-drop events, one of its parent
  38639. components must derive from this class. It's probably best for the top-level
  38640. component to implement it.
  38641. Then to start a drag operation, any sub-component can just call the startDragging()
  38642. method, and this object will take over, tracking the mouse and sending appropriate
  38643. callbacks to any child components derived from DragAndDropTarget which the mouse
  38644. moves over.
  38645. Note: If all that you need to do is to respond to files being drag-and-dropped from
  38646. the operating system onto your component, you don't need any of these classes: you can do this
  38647. simply by overriding Component::filesDropped().
  38648. @see DragAndDropTarget
  38649. */
  38650. class JUCE_API DragAndDropContainer
  38651. {
  38652. public:
  38653. /** Creates a DragAndDropContainer.
  38654. The object that derives from this class must also be a Component.
  38655. */
  38656. DragAndDropContainer();
  38657. /** Destructor. */
  38658. virtual ~DragAndDropContainer();
  38659. /** Begins a drag-and-drop operation.
  38660. This starts a drag-and-drop operation - call it when the user drags the
  38661. mouse in your drag-source component, and this object will track mouse
  38662. movements until the user lets go of the mouse button, and will send
  38663. appropriate messages to DragAndDropTarget objects that the mouse moves
  38664. over.
  38665. findParentDragContainerFor() is a handy method to call to find the
  38666. drag container to use for a component.
  38667. @param sourceDescription a string or value to use as the description of the thing being dragged -
  38668. this will be passed to the objects that might be dropped-onto so they can
  38669. decide whether they want to handle it
  38670. @param sourceComponent the component that is being dragged
  38671. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  38672. a snapshot of the sourceComponent will be used instead.
  38673. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  38674. window, and can be dragged to DragAndDropTargets that are the
  38675. children of components other than this one.
  38676. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  38677. at which the image should be drawn from the mouse. If it isn't
  38678. specified, then the image will be centred around the mouse. If
  38679. an image hasn't been passed-in, this will be ignored.
  38680. */
  38681. void startDragging (const var& sourceDescription,
  38682. Component* sourceComponent,
  38683. const Image& dragImage = Image::null,
  38684. bool allowDraggingToOtherJuceWindows = false,
  38685. const Point<int>* imageOffsetFromMouse = nullptr);
  38686. /** Returns true if something is currently being dragged. */
  38687. bool isDragAndDropActive() const;
  38688. /** Returns the description of the thing that's currently being dragged.
  38689. If nothing's being dragged, this will return an empty string, otherwise it's the
  38690. string that was passed into startDragging().
  38691. @see startDragging
  38692. */
  38693. const String getCurrentDragDescription() const;
  38694. /** Utility to find the DragAndDropContainer for a given Component.
  38695. This will search up this component's parent hierarchy looking for the first
  38696. parent component which is a DragAndDropContainer.
  38697. It's useful when a component wants to call startDragging but doesn't know
  38698. the DragAndDropContainer it should to use.
  38699. Obviously this may return 0 if it doesn't find a suitable component.
  38700. */
  38701. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  38702. /** This performs a synchronous drag-and-drop of a set of files to some external
  38703. application.
  38704. You can call this function in response to a mouseDrag callback, and it will
  38705. block, running its own internal message loop and tracking the mouse, while it
  38706. uses a native operating system drag-and-drop operation to move or copy some
  38707. files to another application.
  38708. @param files a list of filenames to drag
  38709. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  38710. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  38711. @returns true if the files were successfully dropped somewhere, or false if it
  38712. was interrupted
  38713. @see performExternalDragDropOfText
  38714. */
  38715. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  38716. /** This performs a synchronous drag-and-drop of a block of text to some external
  38717. application.
  38718. You can call this function in response to a mouseDrag callback, and it will
  38719. block, running its own internal message loop and tracking the mouse, while it
  38720. uses a native operating system drag-and-drop operation to move or copy some
  38721. text to another application.
  38722. @param text the text to copy
  38723. @returns true if the text was successfully dropped somewhere, or false if it
  38724. was interrupted
  38725. @see performExternalDragDropOfFiles
  38726. */
  38727. static bool performExternalDragDropOfText (const String& text);
  38728. protected:
  38729. /** Override this if you want to be able to perform an external drag a set of files
  38730. when the user drags outside of this container component.
  38731. This method will be called when a drag operation moves outside the Juce-based window,
  38732. and if you want it to then perform a file drag-and-drop, add the filenames you want
  38733. to the array passed in, and return true.
  38734. @param sourceDetails information about the source of the drag operation
  38735. @param files on return, the filenames you want to drag
  38736. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  38737. it must make a copy of them (see the performExternalDragDropOfFiles() method)
  38738. @see performExternalDragDropOfFiles
  38739. */
  38740. virtual bool shouldDropFilesWhenDraggedExternally (const DragAndDropTarget::SourceDetails& sourceDetails,
  38741. StringArray& files, bool& canMoveFiles);
  38742. private:
  38743. friend class DragImageComponent;
  38744. ScopedPointer <Component> dragImageComponent;
  38745. String currentDragDesc;
  38746. JUCE_DEPRECATED (virtual bool shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)) { return false; }
  38747. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DragAndDropContainer);
  38748. };
  38749. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38750. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  38751. class ToolbarItemComponent;
  38752. class ToolbarItemFactory;
  38753. /**
  38754. A toolbar component.
  38755. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  38756. and looks after their order and layout.
  38757. Items (icon buttons or other custom components) are added to a toolbar using a
  38758. ToolbarItemFactory - each type of item is given a unique ID number, and a
  38759. toolbar might contain more than one instance of a particular item type.
  38760. Toolbars can be interactively customised, allowing the user to drag the items
  38761. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  38762. component as a source of new items.
  38763. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  38764. */
  38765. class JUCE_API Toolbar : public Component,
  38766. public DragAndDropContainer,
  38767. public DragAndDropTarget,
  38768. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  38769. {
  38770. public:
  38771. /** Creates an empty toolbar component.
  38772. To add some icons or other components to your toolbar, you'll need to
  38773. create a ToolbarItemFactory class that can create a suitable set of
  38774. ToolbarItemComponents.
  38775. @see ToolbarItemFactory, ToolbarItemComponents
  38776. */
  38777. Toolbar();
  38778. /** Destructor.
  38779. Any items on the bar will be deleted when the toolbar is deleted.
  38780. */
  38781. ~Toolbar();
  38782. /** Changes the bar's orientation.
  38783. @see isVertical
  38784. */
  38785. void setVertical (bool shouldBeVertical);
  38786. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  38787. You can change the bar's orientation with setVertical().
  38788. */
  38789. bool isVertical() const noexcept { return vertical; }
  38790. /** Returns the depth of the bar.
  38791. If the bar is horizontal, this will return its height; if it's vertical, it
  38792. will return its width.
  38793. @see getLength
  38794. */
  38795. int getThickness() const noexcept;
  38796. /** Returns the length of the bar.
  38797. If the bar is horizontal, this will return its width; if it's vertical, it
  38798. will return its height.
  38799. @see getThickness
  38800. */
  38801. int getLength() const noexcept;
  38802. /** Deletes all items from the bar.
  38803. */
  38804. void clear();
  38805. /** Adds an item to the toolbar.
  38806. The factory's ToolbarItemFactory::createItem() will be called by this method
  38807. to create the component that will actually be added to the bar.
  38808. The new item will be inserted at the specified index (if the index is -1, it
  38809. will be added to the right-hand or bottom end of the bar).
  38810. Once added, the component will be automatically deleted by this object when it
  38811. is no longer needed.
  38812. @see ToolbarItemFactory
  38813. */
  38814. void addItem (ToolbarItemFactory& factory,
  38815. int itemId,
  38816. int insertIndex = -1);
  38817. /** Deletes one of the items from the bar.
  38818. */
  38819. void removeToolbarItem (int itemIndex);
  38820. /** Returns the number of items currently on the toolbar.
  38821. @see getItemId, getItemComponent
  38822. */
  38823. int getNumItems() const noexcept;
  38824. /** Returns the ID of the item with the given index.
  38825. If the index is less than zero or greater than the number of items,
  38826. this will return 0.
  38827. @see getNumItems
  38828. */
  38829. int getItemId (int itemIndex) const noexcept;
  38830. /** Returns the component being used for the item with the given index.
  38831. If the index is less than zero or greater than the number of items,
  38832. this will return 0.
  38833. @see getNumItems
  38834. */
  38835. ToolbarItemComponent* getItemComponent (int itemIndex) const noexcept;
  38836. /** Clears this toolbar and adds to it the default set of items that the specified
  38837. factory creates.
  38838. @see ToolbarItemFactory::getDefaultItemSet
  38839. */
  38840. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  38841. /** Options for the way items should be displayed.
  38842. @see setStyle, getStyle
  38843. */
  38844. enum ToolbarItemStyle
  38845. {
  38846. iconsOnly, /**< Means that the toolbar should just contain icons. */
  38847. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  38848. textOnly /**< Means that the toolbar only display text labels for each item. */
  38849. };
  38850. /** Returns the toolbar's current style.
  38851. @see ToolbarItemStyle, setStyle
  38852. */
  38853. ToolbarItemStyle getStyle() const noexcept { return toolbarStyle; }
  38854. /** Changes the toolbar's current style.
  38855. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  38856. */
  38857. void setStyle (const ToolbarItemStyle& newStyle);
  38858. /** Flags used by the showCustomisationDialog() method. */
  38859. enum CustomisationFlags
  38860. {
  38861. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  38862. show the "icons only" option on its choice of toolbar styles. */
  38863. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  38864. show the "icons with text" option on its choice of toolbar styles. */
  38865. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  38866. show the "text only" option on its choice of toolbar styles. */
  38867. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  38868. show a button to reset the toolbar to its default set of items. */
  38869. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  38870. };
  38871. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  38872. The dialog contains a ToolbarItemPalette and various controls for editing other
  38873. aspects of the toolbar. This method will block and run the dialog box modally,
  38874. returning when the user closes it.
  38875. The factory is used to determine the set of items that will be shown on the
  38876. palette.
  38877. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  38878. enum.
  38879. @see ToolbarItemPalette
  38880. */
  38881. void showCustomisationDialog (ToolbarItemFactory& factory,
  38882. int optionFlags = allCustomisationOptionsEnabled);
  38883. /** Turns on or off the toolbar's editing mode, in which its items can be
  38884. rearranged by the user.
  38885. (In most cases it's easier just to use showCustomisationDialog() instead of
  38886. trying to enable editing directly).
  38887. @see ToolbarItemPalette
  38888. */
  38889. void setEditingActive (bool editingEnabled);
  38890. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  38891. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38892. methods.
  38893. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38894. */
  38895. enum ColourIds
  38896. {
  38897. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  38898. more control over this, override LookAndFeel::paintToolbarBackground(). */
  38899. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  38900. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  38901. over them. */
  38902. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  38903. held down on them. */
  38904. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  38905. when the style is set to iconsWithText or textOnly. */
  38906. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  38907. the customisation dialog is active and the mouse moves over them. */
  38908. };
  38909. /** Returns a string that represents the toolbar's current set of items.
  38910. This lets you later restore the same item layout using restoreFromString().
  38911. @see restoreFromString
  38912. */
  38913. const String toString() const;
  38914. /** Restores a set of items that was previously stored in a string by the toString()
  38915. method.
  38916. The factory object is used to create any item components that are needed.
  38917. @see toString
  38918. */
  38919. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  38920. const String& savedVersion);
  38921. /** @internal */
  38922. void paint (Graphics& g);
  38923. /** @internal */
  38924. void resized();
  38925. /** @internal */
  38926. void buttonClicked (Button*);
  38927. /** @internal */
  38928. void mouseDown (const MouseEvent&);
  38929. /** @internal */
  38930. bool isInterestedInDragSource (const SourceDetails&);
  38931. /** @internal */
  38932. void itemDragMove (const SourceDetails&);
  38933. /** @internal */
  38934. void itemDragExit (const SourceDetails&);
  38935. /** @internal */
  38936. void itemDropped (const SourceDetails&);
  38937. /** @internal */
  38938. void updateAllItemPositions (bool animate);
  38939. /** @internal */
  38940. static ToolbarItemComponent* createItem (ToolbarItemFactory&, int itemId);
  38941. private:
  38942. ScopedPointer<Button> missingItemsButton;
  38943. bool vertical, isEditingActive;
  38944. ToolbarItemStyle toolbarStyle;
  38945. class MissingItemsComponent;
  38946. friend class MissingItemsComponent;
  38947. OwnedArray <ToolbarItemComponent> items;
  38948. friend class ItemDragAndDropOverlayComponent;
  38949. static const char* const toolbarDragDescriptor;
  38950. void addItemInternal (ToolbarItemFactory& factory, int itemId, int insertIndex);
  38951. ToolbarItemComponent* getNextActiveComponent (int index, int delta) const;
  38952. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Toolbar);
  38953. };
  38954. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  38955. /*** End of inlined file: juce_Toolbar.h ***/
  38956. class ItemDragAndDropOverlayComponent;
  38957. /**
  38958. A component that can be used as one of the items in a Toolbar.
  38959. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  38960. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  38961. class for further info about creating them.
  38962. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  38963. components too. To do this, set the value of isBeingUsedAsAButton to false when
  38964. calling the constructor, and override contentAreaChanged(), in which you can position
  38965. any sub-components you need to add.
  38966. To add basic buttons without writing a special subclass, have a look at the
  38967. ToolbarButton class.
  38968. @see ToolbarButton, Toolbar, ToolbarItemFactory
  38969. */
  38970. class JUCE_API ToolbarItemComponent : public Button
  38971. {
  38972. public:
  38973. /** Constructor.
  38974. @param itemId the ID of the type of toolbar item which this represents
  38975. @param labelText the text to display if the toolbar's style is set to
  38976. Toolbar::iconsWithText or Toolbar::textOnly
  38977. @param isBeingUsedAsAButton set this to false if you don't want the button
  38978. to draw itself with button over/down states when the mouse
  38979. moves over it or clicks
  38980. */
  38981. ToolbarItemComponent (int itemId,
  38982. const String& labelText,
  38983. bool isBeingUsedAsAButton);
  38984. /** Destructor. */
  38985. ~ToolbarItemComponent();
  38986. /** Returns the item type ID that this component represents.
  38987. This value is in the constructor.
  38988. */
  38989. int getItemId() const noexcept { return itemId; }
  38990. /** Returns the toolbar that contains this component, or 0 if it's not currently
  38991. inside one.
  38992. */
  38993. Toolbar* getToolbar() const;
  38994. /** Returns true if this component is currently inside a toolbar which is vertical.
  38995. @see Toolbar::isVertical
  38996. */
  38997. bool isToolbarVertical() const;
  38998. /** Returns the current style setting of this item.
  38999. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  39000. @see setStyle, Toolbar::getStyle
  39001. */
  39002. Toolbar::ToolbarItemStyle getStyle() const noexcept { return toolbarStyle; }
  39003. /** Changes the current style setting of this item.
  39004. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  39005. by the toolbar that holds this item.
  39006. @see setStyle, Toolbar::setStyle
  39007. */
  39008. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  39009. /** Returns the area of the component that should be used to display the button image or
  39010. other contents of the item.
  39011. This content area may change when the item's style changes, and may leave a space around the
  39012. edge of the component where the text label can be shown.
  39013. @see contentAreaChanged
  39014. */
  39015. const Rectangle<int> getContentArea() const noexcept { return contentArea; }
  39016. /** This method must return the size criteria for this item, based on a given toolbar
  39017. size and orientation.
  39018. The preferredSize, minSize and maxSize values must all be set by your implementation
  39019. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  39020. toolbar, they refer to the item's height.
  39021. The preferredSize is the size that the component would like to be, and this must be
  39022. between the min and max sizes. For a fixed-size item, simply set all three variables to
  39023. the same value.
  39024. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  39025. Toolbar::getThickness().
  39026. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  39027. vertically.
  39028. */
  39029. virtual bool getToolbarItemSizes (int toolbarThickness,
  39030. bool isToolbarVertical,
  39031. int& preferredSize,
  39032. int& minSize,
  39033. int& maxSize) = 0;
  39034. /** Your subclass should use this method to draw its content area.
  39035. The graphics object that is passed-in will have been clipped and had its origin
  39036. moved to fit the content area as specified get getContentArea(). The width and height
  39037. parameters are the width and height of the content area.
  39038. If the component you're writing isn't a button, you can just do nothing in this method.
  39039. */
  39040. virtual void paintButtonArea (Graphics& g,
  39041. int width, int height,
  39042. bool isMouseOver, bool isMouseDown) = 0;
  39043. /** Callback to indicate that the content area of this item has changed.
  39044. This might be because the component was resized, or because the style changed and
  39045. the space needed for the text label is different.
  39046. See getContentArea() for a description of what the area is.
  39047. */
  39048. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  39049. /** Editing modes.
  39050. These are used by setEditingMode(), but will be rarely needed in user code.
  39051. */
  39052. enum ToolbarEditingMode
  39053. {
  39054. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  39055. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  39056. customisation mode, and the items can be dragged around. */
  39057. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  39058. dragged onto a toolbar to add it to that bar.*/
  39059. };
  39060. /** Changes the editing mode of this component.
  39061. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  39062. and is unlikely to be of much use in end-user-code.
  39063. */
  39064. void setEditingMode (const ToolbarEditingMode newMode);
  39065. /** Returns the current editing mode of this component.
  39066. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  39067. and is unlikely to be of much use in end-user-code.
  39068. */
  39069. ToolbarEditingMode getEditingMode() const noexcept { return mode; }
  39070. /** @internal */
  39071. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  39072. /** @internal */
  39073. void resized();
  39074. private:
  39075. friend class Toolbar;
  39076. friend class ItemDragAndDropOverlayComponent;
  39077. const int itemId;
  39078. ToolbarEditingMode mode;
  39079. Toolbar::ToolbarItemStyle toolbarStyle;
  39080. ScopedPointer <Component> overlayComp;
  39081. int dragOffsetX, dragOffsetY;
  39082. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  39083. Rectangle<int> contentArea;
  39084. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemComponent);
  39085. };
  39086. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  39087. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  39088. /**
  39089. A type of button designed to go on a toolbar.
  39090. This simple button can have two Drawable objects specified - one for normal
  39091. use and another one (optionally) for the button's "on" state if it's a
  39092. toggle button.
  39093. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  39094. */
  39095. class JUCE_API ToolbarButton : public ToolbarItemComponent
  39096. {
  39097. public:
  39098. /** Creates a ToolbarButton.
  39099. @param itemId the ID for this toolbar item type. This is passed through to the
  39100. ToolbarItemComponent constructor
  39101. @param labelText the text to display on the button (if the toolbar is using a style
  39102. that shows text labels). This is passed through to the
  39103. ToolbarItemComponent constructor
  39104. @param normalImage a drawable object that the button should use as its icon. The object
  39105. that is passed-in here will be kept by this object and will be
  39106. deleted when no longer needed or when this button is deleted.
  39107. @param toggledOnImage a drawable object that the button can use as its icon if the button
  39108. is in a toggled-on state (see the Button::getToggleState() method). If
  39109. 0 is passed-in here, then the normal image will be used instead, regardless
  39110. of the toggle state. The object that is passed-in here will be kept by
  39111. this object and will be deleted when no longer needed or when this button
  39112. is deleted.
  39113. */
  39114. ToolbarButton (int itemId,
  39115. const String& labelText,
  39116. Drawable* normalImage,
  39117. Drawable* toggledOnImage);
  39118. /** Destructor. */
  39119. ~ToolbarButton();
  39120. /** @internal */
  39121. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  39122. int& minSize, int& maxSize);
  39123. /** @internal */
  39124. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  39125. /** @internal */
  39126. void contentAreaChanged (const Rectangle<int>& newBounds);
  39127. /** @internal */
  39128. void buttonStateChanged();
  39129. /** @internal */
  39130. void resized();
  39131. /** @internal */
  39132. void enablementChanged();
  39133. private:
  39134. ScopedPointer<Drawable> normalImage, toggledOnImage;
  39135. Drawable* currentImage;
  39136. void updateDrawable();
  39137. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarButton);
  39138. };
  39139. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  39140. /*** End of inlined file: juce_ToolbarButton.h ***/
  39141. #endif
  39142. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  39143. /*** Start of inlined file: juce_CodeDocument.h ***/
  39144. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  39145. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  39146. class CodeDocumentLine;
  39147. /**
  39148. A class for storing and manipulating a source code file.
  39149. When using a CodeEditorComponent, it takes one of these as its source object.
  39150. The CodeDocument stores its content as an array of lines, which makes it
  39151. quick to insert and delete.
  39152. @see CodeEditorComponent
  39153. */
  39154. class JUCE_API CodeDocument
  39155. {
  39156. public:
  39157. /** Creates a new, empty document.
  39158. */
  39159. CodeDocument();
  39160. /** Destructor. */
  39161. ~CodeDocument();
  39162. /** A position in a code document.
  39163. Using this class you can find a position in a code document and quickly get its
  39164. character position, line, and index. By calling setPositionMaintained (true), the
  39165. position is automatically updated when text is inserted or deleted in the document,
  39166. so that it maintains its original place in the text.
  39167. */
  39168. class JUCE_API Position
  39169. {
  39170. public:
  39171. /** Creates an uninitialised postion.
  39172. Don't attempt to call any methods on this until you've given it an owner document
  39173. to refer to!
  39174. */
  39175. Position() noexcept;
  39176. /** Creates a position based on a line and index in a document.
  39177. Note that this index is NOT the column number, it's the number of characters from the
  39178. start of the line. The "column" number isn't quite the same, because if the line
  39179. contains any tab characters, the relationship of the index to its visual column depends on
  39180. the number of spaces per tab being used!
  39181. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  39182. they will be adjusted to keep them within its limits.
  39183. */
  39184. Position (const CodeDocument* ownerDocument,
  39185. int line, int indexInLine) noexcept;
  39186. /** Creates a position based on a character index in a document.
  39187. This position is placed at the specified number of characters from the start of the
  39188. document. The line and column are auto-calculated.
  39189. If the position is beyond the range of the document, it'll be adjusted to keep it
  39190. inside.
  39191. */
  39192. Position (const CodeDocument* ownerDocument,
  39193. int charactersFromStartOfDocument) noexcept;
  39194. /** Creates a copy of another position.
  39195. This will copy the position, but the new object will not be set to maintain its position,
  39196. even if the source object was set to do so.
  39197. */
  39198. Position (const Position& other) noexcept;
  39199. /** Destructor. */
  39200. ~Position();
  39201. Position& operator= (const Position& other);
  39202. bool operator== (const Position& other) const noexcept;
  39203. bool operator!= (const Position& other) const noexcept;
  39204. /** Points this object at a new position within the document.
  39205. If the position is beyond the range of the document, it'll be adjusted to keep it
  39206. inside.
  39207. @see getPosition, setLineAndIndex
  39208. */
  39209. void setPosition (int charactersFromStartOfDocument);
  39210. /** Returns the position as the number of characters from the start of the document.
  39211. @see setPosition, getLineNumber, getIndexInLine
  39212. */
  39213. int getPosition() const noexcept { return characterPos; }
  39214. /** Moves the position to a new line and index within the line.
  39215. Note that the index is NOT the column at which the position appears in an editor.
  39216. If the line contains any tab characters, the relationship of the index to its
  39217. visual position depends on the number of spaces per tab being used!
  39218. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  39219. they will be adjusted to keep them within its limits.
  39220. */
  39221. void setLineAndIndex (int newLine, int newIndexInLine);
  39222. /** Returns the line number of this position.
  39223. The first line in the document is numbered zero, not one!
  39224. */
  39225. int getLineNumber() const noexcept { return line; }
  39226. /** Returns the number of characters from the start of the line.
  39227. Note that this value is NOT the column at which the position appears in an editor.
  39228. If the line contains any tab characters, the relationship of the index to its
  39229. visual position depends on the number of spaces per tab being used!
  39230. */
  39231. int getIndexInLine() const noexcept { return indexInLine; }
  39232. /** Allows the position to be automatically updated when the document changes.
  39233. If this is set to true, the positon will register with its document so that
  39234. when the document has text inserted or deleted, this position will be automatically
  39235. moved to keep it at the same position in the text.
  39236. */
  39237. void setPositionMaintained (bool isMaintained);
  39238. /** Moves the position forwards or backwards by the specified number of characters.
  39239. @see movedBy
  39240. */
  39241. void moveBy (int characterDelta);
  39242. /** Returns a position which is the same as this one, moved by the specified number of
  39243. characters.
  39244. @see moveBy
  39245. */
  39246. const Position movedBy (int characterDelta) const;
  39247. /** Returns a position which is the same as this one, moved up or down by the specified
  39248. number of lines.
  39249. @see movedBy
  39250. */
  39251. const Position movedByLines (int deltaLines) const;
  39252. /** Returns the character in the document at this position.
  39253. @see getLineText
  39254. */
  39255. const juce_wchar getCharacter() const;
  39256. /** Returns the line from the document that this position is within.
  39257. @see getCharacter, getLineNumber
  39258. */
  39259. const String getLineText() const;
  39260. private:
  39261. CodeDocument* owner;
  39262. int characterPos, line, indexInLine;
  39263. bool positionMaintained;
  39264. };
  39265. /** Returns the full text of the document. */
  39266. const String getAllContent() const;
  39267. /** Returns a section of the document's text. */
  39268. const String getTextBetween (const Position& start, const Position& end) const;
  39269. /** Returns a line from the document. */
  39270. const String getLine (int lineIndex) const noexcept;
  39271. /** Returns the number of characters in the document. */
  39272. int getNumCharacters() const noexcept;
  39273. /** Returns the number of lines in the document. */
  39274. int getNumLines() const noexcept { return lines.size(); }
  39275. /** Returns the number of characters in the longest line of the document. */
  39276. int getMaximumLineLength() noexcept;
  39277. /** Deletes a section of the text.
  39278. This operation is undoable.
  39279. */
  39280. void deleteSection (const Position& startPosition, const Position& endPosition);
  39281. /** Inserts some text into the document at a given position.
  39282. This operation is undoable.
  39283. */
  39284. void insertText (const Position& position, const String& text);
  39285. /** Clears the document and replaces it with some new text.
  39286. This operation is undoable - if you're trying to completely reset the document, you
  39287. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  39288. */
  39289. void replaceAllContent (const String& newContent);
  39290. /** Replaces the editor's contents with the contents of a stream.
  39291. This will also reset the undo history and save point marker.
  39292. */
  39293. bool loadFromStream (InputStream& stream);
  39294. /** Writes the editor's current contents to a stream. */
  39295. bool writeToStream (OutputStream& stream);
  39296. /** Returns the preferred new-line characters for the document.
  39297. This will be either "\n", "\r\n", or (rarely) "\r".
  39298. @see setNewLineCharacters
  39299. */
  39300. const String getNewLineCharacters() const noexcept { return newLineChars; }
  39301. /** Sets the new-line characters that the document should use.
  39302. The string must be either "\n", "\r\n", or (rarely) "\r".
  39303. @see getNewLineCharacters
  39304. */
  39305. void setNewLineCharacters (const String& newLine) noexcept;
  39306. /** Begins a new undo transaction.
  39307. The document itself will not call this internally, so relies on whatever is using the
  39308. document to periodically call this to break up the undo sequence into sensible chunks.
  39309. @see UndoManager::beginNewTransaction
  39310. */
  39311. void newTransaction();
  39312. /** Undo the last operation.
  39313. @see UndoManager::undo
  39314. */
  39315. void undo();
  39316. /** Redo the last operation.
  39317. @see UndoManager::redo
  39318. */
  39319. void redo();
  39320. /** Clears the undo history.
  39321. @see UndoManager::clearUndoHistory
  39322. */
  39323. void clearUndoHistory();
  39324. /** Returns the document's UndoManager */
  39325. UndoManager& getUndoManager() noexcept { return undoManager; }
  39326. /** Makes a note that the document's current state matches the one that is saved.
  39327. After this has been called, hasChangedSinceSavePoint() will return false until
  39328. the document has been altered, and then it'll start returning true. If the document is
  39329. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  39330. will again return false.
  39331. @see hasChangedSinceSavePoint
  39332. */
  39333. void setSavePoint() noexcept;
  39334. /** Returns true if the state of the document differs from the state it was in when
  39335. setSavePoint() was last called.
  39336. @see setSavePoint
  39337. */
  39338. bool hasChangedSinceSavePoint() const noexcept;
  39339. /** Searches for a word-break. */
  39340. const Position findWordBreakAfter (const Position& position) const noexcept;
  39341. /** Searches for a word-break. */
  39342. const Position findWordBreakBefore (const Position& position) const noexcept;
  39343. /** An object that receives callbacks from the CodeDocument when its text changes.
  39344. @see CodeDocument::addListener, CodeDocument::removeListener
  39345. */
  39346. class JUCE_API Listener
  39347. {
  39348. public:
  39349. Listener() {}
  39350. virtual ~Listener() {}
  39351. /** Called by a CodeDocument when it is altered.
  39352. */
  39353. virtual void codeDocumentChanged (const Position& affectedTextStart,
  39354. const Position& affectedTextEnd) = 0;
  39355. };
  39356. /** Registers a listener object to receive callbacks when the document changes.
  39357. If the listener is already registered, this method has no effect.
  39358. @see removeListener
  39359. */
  39360. void addListener (Listener* listener) noexcept;
  39361. /** Deregisters a listener.
  39362. @see addListener
  39363. */
  39364. void removeListener (Listener* listener) noexcept;
  39365. /** Iterates the text in a CodeDocument.
  39366. This class lets you read characters from a CodeDocument. It's designed to be used
  39367. by a SyntaxAnalyser object.
  39368. @see CodeDocument, SyntaxAnalyser
  39369. */
  39370. class JUCE_API Iterator
  39371. {
  39372. public:
  39373. Iterator (CodeDocument* document);
  39374. Iterator (const Iterator& other);
  39375. Iterator& operator= (const Iterator& other) noexcept;
  39376. ~Iterator() noexcept;
  39377. /** Reads the next character and returns it.
  39378. @see peekNextChar
  39379. */
  39380. juce_wchar nextChar();
  39381. /** Reads the next character without advancing the current position. */
  39382. juce_wchar peekNextChar() const;
  39383. /** Advances the position by one character. */
  39384. void skip();
  39385. /** Returns the position of the next character as its position within the
  39386. whole document.
  39387. */
  39388. int getPosition() const noexcept { return position; }
  39389. /** Skips over any whitespace characters until the next character is non-whitespace. */
  39390. void skipWhitespace();
  39391. /** Skips forward until the next character will be the first character on the next line */
  39392. void skipToEndOfLine();
  39393. /** Returns the line number of the next character. */
  39394. int getLine() const noexcept { return line; }
  39395. /** Returns true if the iterator has reached the end of the document. */
  39396. bool isEOF() const noexcept;
  39397. private:
  39398. CodeDocument* document;
  39399. mutable String::CharPointerType charPointer;
  39400. int line, position;
  39401. };
  39402. private:
  39403. friend class CodeDocumentInsertAction;
  39404. friend class CodeDocumentDeleteAction;
  39405. friend class Iterator;
  39406. friend class Position;
  39407. OwnedArray <CodeDocumentLine> lines;
  39408. Array <Position*> positionsToMaintain;
  39409. UndoManager undoManager;
  39410. int currentActionIndex, indexOfSavedState;
  39411. int maximumLineLength;
  39412. ListenerList <Listener> listeners;
  39413. String newLineChars;
  39414. void sendListenerChangeMessage (int startLine, int endLine);
  39415. void insert (const String& text, int insertPos, bool undoable);
  39416. void remove (int startPos, int endPos, bool undoable);
  39417. void checkLastLineStatus();
  39418. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeDocument);
  39419. };
  39420. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  39421. /*** End of inlined file: juce_CodeDocument.h ***/
  39422. #endif
  39423. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39424. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  39425. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39426. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39427. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  39428. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  39429. #define __JUCE_CODETOKENISER_JUCEHEADER__
  39430. /**
  39431. A base class for tokenising code so that the syntax can be displayed in a
  39432. code editor.
  39433. @see CodeDocument, CodeEditorComponent
  39434. */
  39435. class JUCE_API CodeTokeniser
  39436. {
  39437. public:
  39438. CodeTokeniser() {}
  39439. virtual ~CodeTokeniser() {}
  39440. /** Reads the next token from the source and returns its token type.
  39441. This must leave the source pointing to the first character in the
  39442. next token.
  39443. */
  39444. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  39445. /** Returns a list of the names of the token types this analyser uses.
  39446. The index in this list must match the token type numbers that are
  39447. returned by readNextToken().
  39448. */
  39449. virtual const StringArray getTokenTypes() = 0;
  39450. /** Returns a suggested syntax highlighting colour for a specified
  39451. token type.
  39452. */
  39453. virtual const Colour getDefaultColour (int tokenType) = 0;
  39454. private:
  39455. JUCE_LEAK_DETECTOR (CodeTokeniser);
  39456. };
  39457. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  39458. /*** End of inlined file: juce_CodeTokeniser.h ***/
  39459. /**
  39460. A text editor component designed specifically for source code.
  39461. This is designed to handle syntax highlighting and fast editing of very large
  39462. files.
  39463. */
  39464. class JUCE_API CodeEditorComponent : public Component,
  39465. public TextInputTarget,
  39466. public Timer,
  39467. public ScrollBar::Listener,
  39468. public CodeDocument::Listener,
  39469. public AsyncUpdater
  39470. {
  39471. public:
  39472. /** Creates an editor for a document.
  39473. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  39474. The object that you pass in is not owned or deleted by the editor - you must
  39475. make sure that it doesn't get deleted while this component is still using it.
  39476. @see CodeDocument
  39477. */
  39478. CodeEditorComponent (CodeDocument& document,
  39479. CodeTokeniser* codeTokeniser);
  39480. /** Destructor. */
  39481. ~CodeEditorComponent();
  39482. /** Returns the code document that this component is editing. */
  39483. CodeDocument& getDocument() const noexcept { return document; }
  39484. /** Loads the given content into the document.
  39485. This will completely reset the CodeDocument object, clear its undo history,
  39486. and fill it with this text.
  39487. */
  39488. void loadContent (const String& newContent);
  39489. /** Returns the standard character width. */
  39490. float getCharWidth() const noexcept { return charWidth; }
  39491. /** Returns the height of a line of text, in pixels. */
  39492. int getLineHeight() const noexcept { return lineHeight; }
  39493. /** Returns the number of whole lines visible on the screen,
  39494. This doesn't include a cut-off line that might be visible at the bottom if the
  39495. component's height isn't an exact multiple of the line-height.
  39496. */
  39497. int getNumLinesOnScreen() const noexcept { return linesOnScreen; }
  39498. /** Returns the number of whole columns visible on the screen.
  39499. This doesn't include any cut-off columns at the right-hand edge.
  39500. */
  39501. int getNumColumnsOnScreen() const noexcept { return columnsOnScreen; }
  39502. /** Returns the current caret position. */
  39503. const CodeDocument::Position getCaretPos() const { return caretPos; }
  39504. /** Returns the position of the caret, relative to the editor's origin. */
  39505. const Rectangle<int> getCaretRectangle();
  39506. /** Moves the caret.
  39507. If selecting is true, the section of the document between the current
  39508. caret position and the new one will become selected. If false, any currently
  39509. selected region will be deselected.
  39510. */
  39511. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  39512. /** Returns the on-screen position of a character in the document.
  39513. The rectangle returned is relative to this component's top-left origin.
  39514. */
  39515. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const;
  39516. /** Finds the character at a given on-screen position.
  39517. The co-ordinates are relative to this component's top-left origin.
  39518. */
  39519. const CodeDocument::Position getPositionAt (int x, int y);
  39520. void cursorLeft (bool moveInWholeWordSteps, bool selecting);
  39521. void cursorRight (bool moveInWholeWordSteps, bool selecting);
  39522. void cursorDown (bool selecting);
  39523. void cursorUp (bool selecting);
  39524. void pageDown (bool selecting);
  39525. void pageUp (bool selecting);
  39526. void scrollDown();
  39527. void scrollUp();
  39528. void scrollToLine (int newFirstLineOnScreen);
  39529. void scrollBy (int deltaLines);
  39530. void scrollToColumn (int newFirstColumnOnScreen);
  39531. void scrollToKeepCaretOnScreen();
  39532. void goToStartOfDocument (bool selecting);
  39533. void goToStartOfLine (bool selecting);
  39534. void goToEndOfDocument (bool selecting);
  39535. void goToEndOfLine (bool selecting);
  39536. void deselectAll();
  39537. void selectAll();
  39538. void insertTextAtCaret (const String& textToInsert);
  39539. void insertTabAtCaret();
  39540. void cut();
  39541. void copy();
  39542. void copyThenCut();
  39543. void paste();
  39544. void backspace (bool moveInWholeWordSteps);
  39545. void deleteForward (bool moveInWholeWordSteps);
  39546. void undo();
  39547. void redo();
  39548. const Range<int> getHighlightedRegion() const;
  39549. void setHighlightedRegion (const Range<int>& newRange);
  39550. const String getTextInRange (const Range<int>& range) const;
  39551. /** Changes the current tab settings.
  39552. This lets you change the tab size and whether pressing the tab key inserts a
  39553. tab character, or its equivalent number of spaces.
  39554. */
  39555. void setTabSize (int numSpacesPerTab, bool insertSpacesInsteadOfTabCharacters);
  39556. /** Returns the current number of spaces per tab.
  39557. @see setTabSize
  39558. */
  39559. int getTabSize() const noexcept { return spacesPerTab; }
  39560. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  39561. @see setTabSize
  39562. */
  39563. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  39564. /** Changes the font.
  39565. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  39566. */
  39567. void setFont (const Font& newFont);
  39568. /** Returns the font that the editor is using. */
  39569. const Font& getFont() const noexcept { return font; }
  39570. /** Resets the syntax highlighting colours to the default ones provided by the
  39571. code tokeniser.
  39572. @see CodeTokeniser::getDefaultColour
  39573. */
  39574. void resetToDefaultColours();
  39575. /** Changes one of the syntax highlighting colours.
  39576. The token type values are dependent on the tokeniser being used - use
  39577. CodeTokeniser::getTokenTypes() to get a list of the token types.
  39578. @see getColourForTokenType
  39579. */
  39580. void setColourForTokenType (int tokenType, const Colour& colour);
  39581. /** Returns one of the syntax highlighting colours.
  39582. The token type values are dependent on the tokeniser being used - use
  39583. CodeTokeniser::getTokenTypes() to get a list of the token types.
  39584. @see setColourForTokenType
  39585. */
  39586. const Colour getColourForTokenType (int tokenType) const;
  39587. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  39588. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39589. methods.
  39590. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39591. */
  39592. enum ColourIds
  39593. {
  39594. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  39595. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  39596. selected text. */
  39597. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  39598. enabled. */
  39599. };
  39600. /** Changes the size of the scrollbars. */
  39601. void setScrollbarThickness (int thickness);
  39602. /** Returns the thickness of the scrollbars. */
  39603. int getScrollbarThickness() const noexcept { return scrollbarThickness; }
  39604. /** @internal */
  39605. void resized();
  39606. /** @internal */
  39607. void paint (Graphics& g);
  39608. /** @internal */
  39609. bool keyPressed (const KeyPress& key);
  39610. /** @internal */
  39611. void mouseDown (const MouseEvent& e);
  39612. /** @internal */
  39613. void mouseDrag (const MouseEvent& e);
  39614. /** @internal */
  39615. void mouseUp (const MouseEvent& e);
  39616. /** @internal */
  39617. void mouseDoubleClick (const MouseEvent& e);
  39618. /** @internal */
  39619. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39620. /** @internal */
  39621. void focusGained (FocusChangeType cause);
  39622. /** @internal */
  39623. void focusLost (FocusChangeType cause);
  39624. /** @internal */
  39625. void timerCallback();
  39626. /** @internal */
  39627. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  39628. /** @internal */
  39629. void handleAsyncUpdate();
  39630. /** @internal */
  39631. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  39632. const CodeDocument::Position& affectedTextEnd);
  39633. /** @internal */
  39634. bool isTextInputActive() const;
  39635. /** @internal */
  39636. void setTemporaryUnderlining (const Array <Range<int> >&);
  39637. private:
  39638. CodeDocument& document;
  39639. Font font;
  39640. int firstLineOnScreen, gutter, spacesPerTab;
  39641. float charWidth;
  39642. int lineHeight, linesOnScreen, columnsOnScreen;
  39643. int scrollbarThickness, columnToTryToMaintain;
  39644. bool useSpacesForTabs;
  39645. double xOffset;
  39646. CodeDocument::Position caretPos;
  39647. CodeDocument::Position selectionStart, selectionEnd;
  39648. ScopedPointer<CaretComponent> caret;
  39649. ScrollBar verticalScrollBar, horizontalScrollBar;
  39650. enum DragType
  39651. {
  39652. notDragging,
  39653. draggingSelectionStart,
  39654. draggingSelectionEnd
  39655. };
  39656. DragType dragType;
  39657. CodeTokeniser* codeTokeniser;
  39658. Array <Colour> coloursForTokenCategories;
  39659. class CodeEditorLine;
  39660. OwnedArray <CodeEditorLine> lines;
  39661. void rebuildLineTokens();
  39662. OwnedArray <CodeDocument::Iterator> cachedIterators;
  39663. void clearCachedIterators (int firstLineToBeInvalid);
  39664. void updateCachedIterators (int maxLineNum);
  39665. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  39666. void moveLineDelta (int delta, bool selecting);
  39667. void updateCaretPosition();
  39668. void updateScrollBars();
  39669. void scrollToLineInternal (int line);
  39670. void scrollToColumnInternal (double column);
  39671. void newTransaction();
  39672. int indexToColumn (int line, int index) const noexcept;
  39673. int columnToIndex (int line, int column) const noexcept;
  39674. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeEditorComponent);
  39675. };
  39676. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39677. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  39678. #endif
  39679. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  39680. #endif
  39681. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39682. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  39683. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39684. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39685. /**
  39686. A simple lexical analyser for syntax colouring of C++ code.
  39687. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  39688. */
  39689. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  39690. {
  39691. public:
  39692. CPlusPlusCodeTokeniser();
  39693. ~CPlusPlusCodeTokeniser();
  39694. enum TokenType
  39695. {
  39696. tokenType_error = 0,
  39697. tokenType_comment,
  39698. tokenType_builtInKeyword,
  39699. tokenType_identifier,
  39700. tokenType_integerLiteral,
  39701. tokenType_floatLiteral,
  39702. tokenType_stringLiteral,
  39703. tokenType_operator,
  39704. tokenType_bracket,
  39705. tokenType_punctuation,
  39706. tokenType_preprocessor
  39707. };
  39708. int readNextToken (CodeDocument::Iterator& source);
  39709. const StringArray getTokenTypes();
  39710. const Colour getDefaultColour (int tokenType);
  39711. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  39712. static bool isReservedKeyword (const String& token) noexcept;
  39713. private:
  39714. JUCE_LEAK_DETECTOR (CPlusPlusCodeTokeniser);
  39715. };
  39716. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39717. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  39718. #endif
  39719. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  39720. #endif
  39721. #ifndef __JUCE_IMAGECOMPONENT_JUCEHEADER__
  39722. /*** Start of inlined file: juce_ImageComponent.h ***/
  39723. #ifndef __JUCE_IMAGECOMPONENT_JUCEHEADER__
  39724. #define __JUCE_IMAGECOMPONENT_JUCEHEADER__
  39725. /**
  39726. A component that simply displays an image.
  39727. Use setImage to give it an image, and it'll display it - simple as that!
  39728. */
  39729. class JUCE_API ImageComponent : public Component,
  39730. public SettableTooltipClient
  39731. {
  39732. public:
  39733. /** Creates an ImageComponent. */
  39734. ImageComponent (const String& componentName = String::empty);
  39735. /** Destructor. */
  39736. ~ImageComponent();
  39737. /** Sets the image that should be displayed. */
  39738. void setImage (const Image& newImage);
  39739. /** Sets the image that should be displayed, and its placement within the component. */
  39740. void setImage (const Image& newImage,
  39741. const RectanglePlacement& placementToUse);
  39742. /** Returns the current image. */
  39743. const Image getImage() const;
  39744. /** Sets the method of positioning that will be used to fit the image within the component's bounds.
  39745. By default the positioning is centred, and will fit the image inside the component's bounds
  39746. whilst keeping its aspect ratio correct, but you can change it to whatever layout you need.
  39747. */
  39748. void setImagePlacement (const RectanglePlacement& newPlacement);
  39749. /** Returns the current image placement. */
  39750. const RectanglePlacement getImagePlacement() const;
  39751. /** @internal */
  39752. void paint (Graphics& g);
  39753. private:
  39754. Image image;
  39755. RectanglePlacement placement;
  39756. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageComponent);
  39757. };
  39758. #endif // __JUCE_IMAGECOMPONENT_JUCEHEADER__
  39759. /*** End of inlined file: juce_ImageComponent.h ***/
  39760. #endif
  39761. #ifndef __JUCE_LABEL_JUCEHEADER__
  39762. #endif
  39763. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  39764. #endif
  39765. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  39766. /*** Start of inlined file: juce_ProgressBar.h ***/
  39767. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  39768. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  39769. /**
  39770. A progress bar component.
  39771. To use this, just create one and make it visible. It'll run its own timer
  39772. to keep an eye on a variable that you give it, and will automatically
  39773. redraw itself when the variable changes.
  39774. For an easy way of running a background task with a dialog box showing its
  39775. progress, see the ThreadWithProgressWindow class.
  39776. @see ThreadWithProgressWindow
  39777. */
  39778. class JUCE_API ProgressBar : public Component,
  39779. public SettableTooltipClient,
  39780. private Timer
  39781. {
  39782. public:
  39783. /** Creates a ProgressBar.
  39784. @param progress pass in a reference to a double that you're going to
  39785. update with your task's progress. The ProgressBar will
  39786. monitor the value of this variable and will redraw itself
  39787. when the value changes. The range is from 0 to 1.0. Obviously
  39788. you'd better be careful not to delete this variable while the
  39789. ProgressBar still exists!
  39790. */
  39791. explicit ProgressBar (double& progress);
  39792. /** Destructor. */
  39793. ~ProgressBar();
  39794. /** Turns the percentage display on or off.
  39795. By default this is on, and the progress bar will display a text string showing
  39796. its current percentage.
  39797. */
  39798. void setPercentageDisplay (bool shouldDisplayPercentage);
  39799. /** Gives the progress bar a string to display inside it.
  39800. If you call this, it will turn off the percentage display.
  39801. @see setPercentageDisplay
  39802. */
  39803. void setTextToDisplay (const String& text);
  39804. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  39805. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39806. methods.
  39807. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39808. */
  39809. enum ColourIds
  39810. {
  39811. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  39812. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  39813. classes will probably use variations on this colour. */
  39814. };
  39815. protected:
  39816. /** @internal */
  39817. void paint (Graphics& g);
  39818. /** @internal */
  39819. void lookAndFeelChanged();
  39820. /** @internal */
  39821. void visibilityChanged();
  39822. /** @internal */
  39823. void colourChanged();
  39824. private:
  39825. double& progress;
  39826. double currentValue;
  39827. bool displayPercentage;
  39828. String displayedMessage, currentMessage;
  39829. uint32 lastCallbackTime;
  39830. void timerCallback();
  39831. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgressBar);
  39832. };
  39833. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  39834. /*** End of inlined file: juce_ProgressBar.h ***/
  39835. #endif
  39836. #ifndef __JUCE_SLIDER_JUCEHEADER__
  39837. /*** Start of inlined file: juce_Slider.h ***/
  39838. #ifndef __JUCE_SLIDER_JUCEHEADER__
  39839. #define __JUCE_SLIDER_JUCEHEADER__
  39840. #if JUCE_VC6
  39841. #define Listener LabelListener
  39842. #endif
  39843. /**
  39844. A slider control for changing a value.
  39845. The slider can be horizontal, vertical, or rotary, and can optionally have
  39846. a text-box inside it to show an editable display of the current value.
  39847. To use it, create a Slider object and use the setSliderStyle() method
  39848. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  39849. To define the values that it can be set to, see the setRange() and setValue() methods.
  39850. There are also lots of custom tweaks you can do by subclassing and overriding
  39851. some of the virtual methods, such as changing the scaling, changing the format of
  39852. the text display, custom ways of limiting the values, etc.
  39853. You can register Slider::Listener objects with a slider, and they'll be called when
  39854. the value changes.
  39855. @see Slider::Listener
  39856. */
  39857. class JUCE_API Slider : public Component,
  39858. public SettableTooltipClient,
  39859. public AsyncUpdater,
  39860. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  39861. public LabelListener,
  39862. public ValueListener
  39863. {
  39864. public:
  39865. /** Creates a slider.
  39866. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  39867. setRange(), etc.
  39868. */
  39869. explicit Slider (const String& componentName = String::empty);
  39870. /** Destructor. */
  39871. ~Slider();
  39872. /** The types of slider available.
  39873. @see setSliderStyle, setRotaryParameters
  39874. */
  39875. enum SliderStyle
  39876. {
  39877. LinearHorizontal, /**< A traditional horizontal slider. */
  39878. LinearVertical, /**< A traditional vertical slider. */
  39879. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  39880. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  39881. @see setRotaryParameters */
  39882. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  39883. @see setRotaryParameters */
  39884. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  39885. @see setRotaryParameters */
  39886. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  39887. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  39888. @see setMinValue, setMaxValue */
  39889. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  39890. @see setMinValue, setMaxValue */
  39891. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  39892. value, with the current value being somewhere between them.
  39893. @see setMinValue, setMaxValue */
  39894. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  39895. value, with the current value being somewhere between them.
  39896. @see setMinValue, setMaxValue */
  39897. };
  39898. /** Changes the type of slider interface being used.
  39899. @param newStyle the type of interface
  39900. @see setRotaryParameters, setVelocityBasedMode,
  39901. */
  39902. void setSliderStyle (SliderStyle newStyle);
  39903. /** Returns the slider's current style.
  39904. @see setSliderStyle
  39905. */
  39906. SliderStyle getSliderStyle() const noexcept { return style; }
  39907. /** Changes the properties of a rotary slider.
  39908. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  39909. the slider's minimum value is represented
  39910. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  39911. the slider's maximum value is represented. This must be
  39912. greater than startAngleRadians
  39913. @param stopAtEnd if true, then when the slider is dragged around past the
  39914. minimum or maximum, it'll stop there; if false, it'll wrap
  39915. back to the opposite value
  39916. */
  39917. void setRotaryParameters (float startAngleRadians,
  39918. float endAngleRadians,
  39919. bool stopAtEnd);
  39920. /** Sets the distance the mouse has to move to drag the slider across
  39921. the full extent of its range.
  39922. This only applies when in modes like RotaryHorizontalDrag, where it's using
  39923. relative mouse movements to adjust the slider.
  39924. */
  39925. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  39926. /** Returns the current sensitivity value set by setMouseDragSensitivity(). */
  39927. int getMouseDragSensitivity() const noexcept { return pixelsForFullDragExtent; }
  39928. /** Changes the way the the mouse is used when dragging the slider.
  39929. If true, this will turn on velocity-sensitive dragging, so that
  39930. the faster the mouse moves, the bigger the movement to the slider. This
  39931. helps when making accurate adjustments if the slider's range is quite large.
  39932. If false, the slider will just try to snap to wherever the mouse is.
  39933. */
  39934. void setVelocityBasedMode (bool isVelocityBased);
  39935. /** Returns true if velocity-based mode is active.
  39936. @see setVelocityBasedMode
  39937. */
  39938. bool getVelocityBasedMode() const noexcept { return isVelocityBased; }
  39939. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  39940. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  39941. or if you're holding down ctrl.
  39942. @param sensitivity higher values than 1.0 increase the range of acceleration used
  39943. @param threshold the minimum number of pixels that the mouse needs to move for it
  39944. to be treated as a movement
  39945. @param offset values greater than 0.0 increase the minimum speed that will be used when
  39946. the threshold is reached
  39947. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  39948. key to toggle velocity-sensitive mode
  39949. */
  39950. void setVelocityModeParameters (double sensitivity = 1.0,
  39951. int threshold = 1,
  39952. double offset = 0.0,
  39953. bool userCanPressKeyToSwapMode = true);
  39954. /** Returns the velocity sensitivity setting.
  39955. @see setVelocityModeParameters
  39956. */
  39957. double getVelocitySensitivity() const noexcept { return velocityModeSensitivity; }
  39958. /** Returns the velocity threshold setting.
  39959. @see setVelocityModeParameters
  39960. */
  39961. int getVelocityThreshold() const noexcept { return velocityModeThreshold; }
  39962. /** Returns the velocity offset setting.
  39963. @see setVelocityModeParameters
  39964. */
  39965. double getVelocityOffset() const noexcept { return velocityModeOffset; }
  39966. /** Returns the velocity user key setting.
  39967. @see setVelocityModeParameters
  39968. */
  39969. bool getVelocityModeIsSwappable() const noexcept { return userKeyOverridesVelocity; }
  39970. /** Sets up a skew factor to alter the way values are distributed.
  39971. You may want to use a range of values on the slider where more accuracy
  39972. is required towards one end of the range, so this will logarithmically
  39973. spread the values across the length of the slider.
  39974. If the factor is < 1.0, the lower end of the range will fill more of the
  39975. slider's length; if the factor is > 1.0, the upper end of the range
  39976. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  39977. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  39978. method instead.
  39979. @see getSkewFactor, setSkewFactorFromMidPoint
  39980. */
  39981. void setSkewFactor (double factor);
  39982. /** Sets up a skew factor to alter the way values are distributed.
  39983. This allows you to specify the slider value that should appear in the
  39984. centre of the slider's visible range.
  39985. @see setSkewFactor, getSkewFactor
  39986. */
  39987. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  39988. /** Returns the current skew factor.
  39989. See setSkewFactor for more info.
  39990. @see setSkewFactor, setSkewFactorFromMidPoint
  39991. */
  39992. double getSkewFactor() const noexcept { return skewFactor; }
  39993. /** Used by setIncDecButtonsMode().
  39994. */
  39995. enum IncDecButtonMode
  39996. {
  39997. incDecButtonsNotDraggable,
  39998. incDecButtonsDraggable_AutoDirection,
  39999. incDecButtonsDraggable_Horizontal,
  40000. incDecButtonsDraggable_Vertical
  40001. };
  40002. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  40003. can be dragged on the buttons to drag the values.
  40004. By default this is turned off. When enabled, clicking on the buttons still works
  40005. them as normal, but by holding down the mouse on a button and dragging it a little
  40006. distance, it flips into a mode where the value can be dragged. The drag direction can
  40007. either be set explicitly to be vertical or horizontal, or can be set to
  40008. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  40009. are side-by-side or above each other.
  40010. */
  40011. void setIncDecButtonsMode (IncDecButtonMode mode);
  40012. /** The position of the slider's text-entry box.
  40013. @see setTextBoxStyle
  40014. */
  40015. enum TextEntryBoxPosition
  40016. {
  40017. NoTextBox, /**< Doesn't display a text box. */
  40018. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  40019. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  40020. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  40021. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  40022. };
  40023. /** Changes the location and properties of the text-entry box.
  40024. @param newPosition where it should go (or NoTextBox to not have one at all)
  40025. @param isReadOnly if true, it's a read-only display
  40026. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  40027. room for the slider as well!
  40028. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  40029. room for the slider as well!
  40030. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  40031. */
  40032. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  40033. bool isReadOnly,
  40034. int textEntryBoxWidth,
  40035. int textEntryBoxHeight);
  40036. /** Returns the status of the text-box.
  40037. @see setTextBoxStyle
  40038. */
  40039. const TextEntryBoxPosition getTextBoxPosition() const noexcept { return textBoxPos; }
  40040. /** Returns the width used for the text-box.
  40041. @see setTextBoxStyle
  40042. */
  40043. int getTextBoxWidth() const noexcept { return textBoxWidth; }
  40044. /** Returns the height used for the text-box.
  40045. @see setTextBoxStyle
  40046. */
  40047. int getTextBoxHeight() const noexcept { return textBoxHeight; }
  40048. /** Makes the text-box editable.
  40049. By default this is true, and the user can enter values into the textbox,
  40050. but it can be turned off if that's not suitable.
  40051. @see setTextBoxStyle, getValueFromText, getTextFromValue
  40052. */
  40053. void setTextBoxIsEditable (bool shouldBeEditable);
  40054. /** Returns true if the text-box is read-only.
  40055. @see setTextBoxStyle
  40056. */
  40057. bool isTextBoxEditable() const { return editableText; }
  40058. /** If the text-box is editable, this will give it the focus so that the user can
  40059. type directly into it.
  40060. This is basically the effect as the user clicking on it.
  40061. */
  40062. void showTextBox();
  40063. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  40064. focus away from it.
  40065. @param discardCurrentEditorContents if true, the slider's value will be left
  40066. unchanged; if false, the current contents of the
  40067. text editor will be used to set the slider position
  40068. before it is hidden.
  40069. */
  40070. void hideTextBox (bool discardCurrentEditorContents);
  40071. /** Changes the slider's current value.
  40072. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40073. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40074. want to handle it.
  40075. @param newValue the new value to set - this will be restricted by the
  40076. minimum and maximum range, and will be snapped to the
  40077. nearest interval if one has been set
  40078. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40079. any Slider::Listeners or the valueChanged() method
  40080. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40081. synchronously; if false, it will be asynchronous
  40082. */
  40083. void setValue (double newValue,
  40084. bool sendUpdateMessage = true,
  40085. bool sendMessageSynchronously = false);
  40086. /** Returns the slider's current value. */
  40087. double getValue() const;
  40088. /** Returns the Value object that represents the slider's current position.
  40089. You can use this Value object to connect the slider's position to external values or setters,
  40090. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  40091. your own Value object.
  40092. @see Value, getMaxValue, getMinValueObject
  40093. */
  40094. Value& getValueObject() { return currentValue; }
  40095. /** Sets the limits that the slider's value can take.
  40096. @param newMinimum the lowest value allowed
  40097. @param newMaximum the highest value allowed
  40098. @param newInterval the steps in which the value is allowed to increase - if this
  40099. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  40100. */
  40101. void setRange (double newMinimum,
  40102. double newMaximum,
  40103. double newInterval = 0);
  40104. /** Returns the current maximum value.
  40105. @see setRange
  40106. */
  40107. double getMaximum() const { return maximum; }
  40108. /** Returns the current minimum value.
  40109. @see setRange
  40110. */
  40111. double getMinimum() const { return minimum; }
  40112. /** Returns the current step-size for values.
  40113. @see setRange
  40114. */
  40115. double getInterval() const { return interval; }
  40116. /** For a slider with two or three thumbs, this returns the lower of its values.
  40117. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  40118. A slider with three values also uses the normal getValue() and setValue() methods to
  40119. control the middle value.
  40120. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  40121. */
  40122. double getMinValue() const;
  40123. /** For a slider with two or three thumbs, this returns the lower of its values.
  40124. You can use this Value object to connect the slider's position to external values or setters,
  40125. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  40126. your own Value object.
  40127. @see Value, getMinValue, getMaxValueObject
  40128. */
  40129. Value& getMinValueObject() noexcept { return valueMin; }
  40130. /** For a slider with two or three thumbs, this sets the lower of its values.
  40131. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40132. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40133. want to handle it.
  40134. @param newValue the new value to set - this will be restricted by the
  40135. minimum and maximum range, and will be snapped to the nearest
  40136. interval if one has been set.
  40137. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40138. any Slider::Listeners or the valueChanged() method
  40139. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40140. synchronously; if false, it will be asynchronous
  40141. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  40142. max value (in a two-value slider) or the mid value (in a three-value
  40143. slider). If false, then if this value goes beyond those values,
  40144. it will push them along with it.
  40145. @see getMinValue, setMaxValue, setValue
  40146. */
  40147. void setMinValue (double newValue,
  40148. bool sendUpdateMessage = true,
  40149. bool sendMessageSynchronously = false,
  40150. bool allowNudgingOfOtherValues = false);
  40151. /** For a slider with two or three thumbs, this returns the higher of its values.
  40152. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  40153. A slider with three values also uses the normal getValue() and setValue() methods to
  40154. control the middle value.
  40155. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  40156. */
  40157. double getMaxValue() const;
  40158. /** For a slider with two or three thumbs, this returns the higher of its values.
  40159. You can use this Value object to connect the slider's position to external values or setters,
  40160. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  40161. your own Value object.
  40162. @see Value, getMaxValue, getMinValueObject
  40163. */
  40164. Value& getMaxValueObject() noexcept { return valueMax; }
  40165. /** For a slider with two or three thumbs, this sets the lower of its values.
  40166. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40167. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40168. want to handle it.
  40169. @param newValue the new value to set - this will be restricted by the
  40170. minimum and maximum range, and will be snapped to the nearest
  40171. interval if one has been set.
  40172. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40173. any Slider::Listeners or the valueChanged() method
  40174. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40175. synchronously; if false, it will be asynchronous
  40176. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  40177. min value (in a two-value slider) or the mid value (in a three-value
  40178. slider). If false, then if this value goes beyond those values,
  40179. it will push them along with it.
  40180. @see getMaxValue, setMinValue, setValue
  40181. */
  40182. void setMaxValue (double newValue,
  40183. bool sendUpdateMessage = true,
  40184. bool sendMessageSynchronously = false,
  40185. bool allowNudgingOfOtherValues = false);
  40186. /** For a slider with two or three thumbs, this sets the minimum and maximum thumb positions.
  40187. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40188. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40189. want to handle it.
  40190. @param newMinValue the new minimum value to set - this will be snapped to the
  40191. nearest interval if one has been set.
  40192. @param newMaxValue the new minimum value to set - this will be snapped to the
  40193. nearest interval if one has been set.
  40194. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40195. any Slider::Listeners or the valueChanged() method
  40196. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40197. synchronously; if false, it will be asynchronous
  40198. @see setMaxValue, setMinValue, setValue
  40199. */
  40200. void setMinAndMaxValues (double newMinValue, double newMaxValue,
  40201. bool sendUpdateMessage = true,
  40202. bool sendMessageSynchronously = false);
  40203. /** A class for receiving callbacks from a Slider.
  40204. To be told when a slider's value changes, you can register a Slider::Listener
  40205. object using Slider::addListener().
  40206. @see Slider::addListener, Slider::removeListener
  40207. */
  40208. class JUCE_API Listener
  40209. {
  40210. public:
  40211. /** Destructor. */
  40212. virtual ~Listener() {}
  40213. /** Called when the slider's value is changed.
  40214. This may be caused by dragging it, or by typing in its text entry box,
  40215. or by a call to Slider::setValue().
  40216. You can find out the new value using Slider::getValue().
  40217. @see Slider::valueChanged
  40218. */
  40219. virtual void sliderValueChanged (Slider* slider) = 0;
  40220. /** Called when the slider is about to be dragged.
  40221. This is called when a drag begins, then it's followed by multiple calls
  40222. to sliderValueChanged(), and then sliderDragEnded() is called after the
  40223. user lets go.
  40224. @see sliderDragEnded, Slider::startedDragging
  40225. */
  40226. virtual void sliderDragStarted (Slider* slider);
  40227. /** Called after a drag operation has finished.
  40228. @see sliderDragStarted, Slider::stoppedDragging
  40229. */
  40230. virtual void sliderDragEnded (Slider* slider);
  40231. };
  40232. /** Adds a listener to be called when this slider's value changes. */
  40233. void addListener (Listener* listener);
  40234. /** Removes a previously-registered listener. */
  40235. void removeListener (Listener* listener);
  40236. /** This lets you choose whether double-clicking moves the slider to a given position.
  40237. By default this is turned off, but it's handy if you want a double-click to act
  40238. as a quick way of resetting a slider. Just pass in the value you want it to
  40239. go to when double-clicked.
  40240. @see getDoubleClickReturnValue
  40241. */
  40242. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  40243. double valueToSetOnDoubleClick);
  40244. /** Returns the values last set by setDoubleClickReturnValue() method.
  40245. Sets isEnabled to true if double-click is enabled, and returns the value
  40246. that was set.
  40247. @see setDoubleClickReturnValue
  40248. */
  40249. double getDoubleClickReturnValue (bool& isEnabled) const;
  40250. /** Tells the slider whether to keep sending change messages while the user
  40251. is dragging the slider.
  40252. If set to true, a change message will only be sent when the user has
  40253. dragged the slider and let go. If set to false (the default), then messages
  40254. will be continuously sent as they drag it while the mouse button is still
  40255. held down.
  40256. */
  40257. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  40258. /** This lets you change whether the slider thumb jumps to the mouse position
  40259. when you click.
  40260. By default, this is true. If it's false, then the slider moves with relative
  40261. motion when you drag it.
  40262. This only applies to linear bars, and won't affect two- or three- value
  40263. sliders.
  40264. */
  40265. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  40266. /** If enabled, this gives the slider a pop-up bubble which appears while the
  40267. slider is being dragged.
  40268. This can be handy if your slider doesn't have a text-box, so that users can
  40269. see the value just when they're changing it.
  40270. If you pass a component as the parentComponentToUse parameter, the pop-up
  40271. bubble will be added as a child of that component when it's needed. If you
  40272. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  40273. transparent window, so if you're using an OS that can't do transparent windows
  40274. you'll have to add it to a parent component instead).
  40275. */
  40276. void setPopupDisplayEnabled (bool isEnabled,
  40277. Component* parentComponentToUse);
  40278. /** If this is set to true, then right-clicking on the slider will pop-up
  40279. a menu to let the user change the way it works.
  40280. By default this is turned off, but when turned on, the menu will include
  40281. things like velocity sensitivity, and for rotary sliders, whether they
  40282. use a linear or rotary mouse-drag to move them.
  40283. */
  40284. void setPopupMenuEnabled (bool menuEnabled);
  40285. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  40286. By default it's enabled.
  40287. */
  40288. void setScrollWheelEnabled (bool enabled);
  40289. /** Returns a number to indicate which thumb is currently being dragged by the
  40290. mouse.
  40291. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  40292. the maximum-value thumb, or -1 if none is currently down.
  40293. */
  40294. int getThumbBeingDragged() const noexcept { return sliderBeingDragged; }
  40295. /** Callback to indicate that the user is about to start dragging the slider.
  40296. @see Slider::Listener::sliderDragStarted
  40297. */
  40298. virtual void startedDragging();
  40299. /** Callback to indicate that the user has just stopped dragging the slider.
  40300. @see Slider::Listener::sliderDragEnded
  40301. */
  40302. virtual void stoppedDragging();
  40303. /** Callback to indicate that the user has just moved the slider.
  40304. @see Slider::Listener::sliderValueChanged
  40305. */
  40306. virtual void valueChanged();
  40307. /** Subclasses can override this to convert a text string to a value.
  40308. When the user enters something into the text-entry box, this method is
  40309. called to convert it to a value.
  40310. The default routine just tries to convert it to a double.
  40311. @see getTextFromValue
  40312. */
  40313. virtual double getValueFromText (const String& text);
  40314. /** Turns the slider's current value into a text string.
  40315. Subclasses can override this to customise the formatting of the text-entry box.
  40316. The default implementation just turns the value into a string, using
  40317. a number of decimal places based on the range interval. If a suffix string
  40318. has been set using setTextValueSuffix(), this will be appended to the text.
  40319. @see getValueFromText
  40320. */
  40321. virtual const String getTextFromValue (double value);
  40322. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  40323. a string.
  40324. This is used by the default implementation of getTextFromValue(), and is just
  40325. appended to the numeric value. For more advanced formatting, you can override
  40326. getTextFromValue() and do something else.
  40327. */
  40328. void setTextValueSuffix (const String& suffix);
  40329. /** Returns the suffix that was set by setTextValueSuffix(). */
  40330. const String getTextValueSuffix() const;
  40331. /** Allows a user-defined mapping of distance along the slider to its value.
  40332. The default implementation for this performs the skewing operation that
  40333. can be set up in the setSkewFactor() method. Override it if you need
  40334. some kind of custom mapping instead, but make sure you also implement the
  40335. inverse function in valueToProportionOfLength().
  40336. @param proportion a value 0 to 1.0, indicating a distance along the slider
  40337. @returns the slider value that is represented by this position
  40338. @see valueToProportionOfLength
  40339. */
  40340. virtual double proportionOfLengthToValue (double proportion);
  40341. /** Allows a user-defined mapping of value to the position of the slider along its length.
  40342. The default implementation for this performs the skewing operation that
  40343. can be set up in the setSkewFactor() method. Override it if you need
  40344. some kind of custom mapping instead, but make sure you also implement the
  40345. inverse function in proportionOfLengthToValue().
  40346. @param value a valid slider value, between the range of values specified in
  40347. setRange()
  40348. @returns a value 0 to 1.0 indicating the distance along the slider that
  40349. represents this value
  40350. @see proportionOfLengthToValue
  40351. */
  40352. virtual double valueToProportionOfLength (double value);
  40353. /** Returns the X or Y coordinate of a value along the slider's length.
  40354. If the slider is horizontal, this will be the X coordinate of the given
  40355. value, relative to the left of the slider. If it's vertical, then this will
  40356. be the Y coordinate, relative to the top of the slider.
  40357. If the slider is rotary, this will throw an assertion and return 0. If the
  40358. value is out-of-range, it will be constrained to the length of the slider.
  40359. */
  40360. float getPositionOfValue (double value);
  40361. /** This can be overridden to allow the slider to snap to user-definable values.
  40362. If overridden, it will be called when the user tries to move the slider to
  40363. a given position, and allows a subclass to sanity-check this value, possibly
  40364. returning a different value to use instead.
  40365. @param attemptedValue the value the user is trying to enter
  40366. @param userIsDragging true if the user is dragging with the mouse; false if
  40367. they are entering the value using the text box
  40368. @returns the value to use instead
  40369. */
  40370. virtual double snapValue (double attemptedValue, bool userIsDragging);
  40371. /** This can be called to force the text box to update its contents.
  40372. (Not normally needed, as this is done automatically).
  40373. */
  40374. void updateText();
  40375. /** True if the slider moves horizontally. */
  40376. bool isHorizontal() const;
  40377. /** True if the slider moves vertically. */
  40378. bool isVertical() const;
  40379. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  40380. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40381. methods.
  40382. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40383. */
  40384. enum ColourIds
  40385. {
  40386. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  40387. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  40388. and feel class how this is used. */
  40389. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  40390. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  40391. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  40392. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  40393. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  40394. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  40395. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  40396. };
  40397. protected:
  40398. /** @internal */
  40399. void labelTextChanged (Label*);
  40400. /** @internal */
  40401. void paint (Graphics& g);
  40402. /** @internal */
  40403. void resized();
  40404. /** @internal */
  40405. void mouseDown (const MouseEvent& e);
  40406. /** @internal */
  40407. void mouseUp (const MouseEvent& e);
  40408. /** @internal */
  40409. void mouseDrag (const MouseEvent& e);
  40410. /** @internal */
  40411. void mouseDoubleClick (const MouseEvent& e);
  40412. /** @internal */
  40413. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  40414. /** @internal */
  40415. void modifierKeysChanged (const ModifierKeys& modifiers);
  40416. /** @internal */
  40417. void buttonClicked (Button* button);
  40418. /** @internal */
  40419. void lookAndFeelChanged();
  40420. /** @internal */
  40421. void enablementChanged();
  40422. /** @internal */
  40423. void focusOfChildComponentChanged (FocusChangeType cause);
  40424. /** @internal */
  40425. void handleAsyncUpdate();
  40426. /** @internal */
  40427. void colourChanged();
  40428. /** @internal */
  40429. void valueChanged (Value& value);
  40430. /** Returns the best number of decimal places to use when displaying numbers.
  40431. This is calculated from the slider's interval setting.
  40432. */
  40433. int getNumDecimalPlacesToDisplay() const noexcept { return numDecimalPlaces; }
  40434. private:
  40435. ListenerList <Listener> listeners;
  40436. Value currentValue, valueMin, valueMax;
  40437. double lastCurrentValue, lastValueMin, lastValueMax;
  40438. double minimum, maximum, interval, doubleClickReturnValue;
  40439. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  40440. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  40441. int velocityModeThreshold;
  40442. float rotaryStart, rotaryEnd;
  40443. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  40444. int mouseDragStartX, mouseDragStartY;
  40445. int sliderRegionStart, sliderRegionSize;
  40446. int sliderBeingDragged;
  40447. int pixelsForFullDragExtent;
  40448. Rectangle<int> sliderRect;
  40449. String textSuffix;
  40450. SliderStyle style;
  40451. TextEntryBoxPosition textBoxPos;
  40452. int textBoxWidth, textBoxHeight;
  40453. IncDecButtonMode incDecButtonMode;
  40454. bool editableText : 1, doubleClickToValue : 1;
  40455. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  40456. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  40457. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  40458. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  40459. ScopedPointer<Label> valueBox;
  40460. ScopedPointer<Button> incButton, decButton;
  40461. class PopupDisplayComponent;
  40462. friend class PopupDisplayComponent;
  40463. friend class ScopedPointer <PopupDisplayComponent>;
  40464. ScopedPointer <PopupDisplayComponent> popupDisplay;
  40465. Component* parentForPopupDisplay;
  40466. float getLinearSliderPos (double value);
  40467. void restoreMouseIfHidden();
  40468. void sendDragStart();
  40469. void sendDragEnd();
  40470. double constrainedValue (double value) const;
  40471. void triggerChangeMessage (bool synchronous);
  40472. bool incDecDragDirectionIsHorizontal() const;
  40473. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Slider);
  40474. };
  40475. /** This typedef is just for compatibility with old code - newer code should use the Slider::Listener class directly. */
  40476. typedef Slider::Listener SliderListener;
  40477. #if JUCE_VC6
  40478. #undef Listener
  40479. #endif
  40480. #endif // __JUCE_SLIDER_JUCEHEADER__
  40481. /*** End of inlined file: juce_Slider.h ***/
  40482. #endif
  40483. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40484. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  40485. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40486. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40487. /**
  40488. A component that displays a strip of column headings for a table, and allows these
  40489. to be resized, dragged around, etc.
  40490. This is just the component that goes at the top of a table. You can use it
  40491. directly for custom components, or to create a simple table, use the
  40492. TableListBox class.
  40493. To use one of these, create it and use addColumn() to add all the columns that you need.
  40494. Each column must be given a unique ID number that's used to refer to it.
  40495. @see TableListBox, TableHeaderComponent::Listener
  40496. */
  40497. class JUCE_API TableHeaderComponent : public Component,
  40498. private AsyncUpdater
  40499. {
  40500. public:
  40501. /** Creates an empty table header.
  40502. */
  40503. TableHeaderComponent();
  40504. /** Destructor. */
  40505. ~TableHeaderComponent();
  40506. /** A combination of these flags are passed into the addColumn() method to specify
  40507. the properties of a column.
  40508. */
  40509. enum ColumnPropertyFlags
  40510. {
  40511. 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. */
  40512. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  40513. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  40514. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  40515. 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. */
  40516. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  40517. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  40518. /** This set of default flags is used as the default parameter value in addColumn(). */
  40519. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  40520. /** A quick way of combining flags for a column that's not resizable. */
  40521. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  40522. /** A quick way of combining flags for a column that's not resizable or sortable. */
  40523. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  40524. /** A quick way of combining flags for a column that's not sortable. */
  40525. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  40526. };
  40527. /** Adds a column to the table.
  40528. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  40529. registered listeners.
  40530. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  40531. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  40532. a unique ID. This is used to identify the column later on, after the user may have
  40533. changed the order that they appear in
  40534. @param width the initial width of the column, in pixels
  40535. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  40536. if the 'resizable' flag is specified for this column
  40537. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  40538. if the 'resizable' flag is specified for this column
  40539. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  40540. properties of this column
  40541. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  40542. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  40543. all columns, not just the index amongst those that are currently visible
  40544. */
  40545. void addColumn (const String& columnName,
  40546. int columnId,
  40547. int width,
  40548. int minimumWidth = 30,
  40549. int maximumWidth = -1,
  40550. int propertyFlags = defaultFlags,
  40551. int insertIndex = -1);
  40552. /** Removes a column with the given ID.
  40553. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  40554. registered listeners.
  40555. */
  40556. void removeColumn (int columnIdToRemove);
  40557. /** Deletes all columns from the table.
  40558. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  40559. registered listeners.
  40560. */
  40561. void removeAllColumns();
  40562. /** Returns the number of columns in the table.
  40563. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  40564. return the total number of columns, including hidden ones.
  40565. @see isColumnVisible
  40566. */
  40567. int getNumColumns (bool onlyCountVisibleColumns) const;
  40568. /** Returns the name for a column.
  40569. @see setColumnName
  40570. */
  40571. const String getColumnName (int columnId) const;
  40572. /** Changes the name of a column. */
  40573. void setColumnName (int columnId, const String& newName);
  40574. /** Moves a column to a different index in the table.
  40575. @param columnId the column to move
  40576. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  40577. */
  40578. void moveColumn (int columnId, int newVisibleIndex);
  40579. /** Returns the width of one of the columns.
  40580. */
  40581. int getColumnWidth (int columnId) const;
  40582. /** Changes the width of a column.
  40583. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  40584. */
  40585. void setColumnWidth (int columnId, int newWidth);
  40586. /** Shows or hides a column.
  40587. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  40588. @see isColumnVisible
  40589. */
  40590. void setColumnVisible (int columnId, bool shouldBeVisible);
  40591. /** Returns true if this column is currently visible.
  40592. @see setColumnVisible
  40593. */
  40594. bool isColumnVisible (int columnId) const;
  40595. /** Changes the column which is the sort column.
  40596. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  40597. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  40598. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  40599. @see getSortColumnId, isSortedForwards, reSortTable
  40600. */
  40601. void setSortColumnId (int columnId, bool sortForwards);
  40602. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  40603. @see setSortColumnId, isSortedForwards
  40604. */
  40605. int getSortColumnId() const;
  40606. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  40607. @see setSortColumnId
  40608. */
  40609. bool isSortedForwards() const;
  40610. /** Triggers a re-sort of the table according to the current sort-column.
  40611. If you modifiy the table's contents, you can call this to signal that the table needs
  40612. to be re-sorted.
  40613. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  40614. tableSortOrderChanged() method of any listeners).
  40615. */
  40616. void reSortTable();
  40617. /** Returns the total width of all the visible columns in the table.
  40618. */
  40619. int getTotalWidth() const;
  40620. /** Returns the index of a given column.
  40621. If there's no such column ID, this will return -1.
  40622. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  40623. otherwise it'll return the index amongst all the columns, including any hidden ones.
  40624. */
  40625. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  40626. /** Returns the ID of the column at a given index.
  40627. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  40628. otherwise it'll count it amongst all the columns, including any hidden ones.
  40629. If the index is out-of-range, it'll return 0.
  40630. */
  40631. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  40632. /** Returns the rectangle containing of one of the columns.
  40633. The index is an index from 0 to the number of columns that are currently visible (hidden
  40634. ones are not counted). It returns a rectangle showing the position of the column relative
  40635. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  40636. */
  40637. const Rectangle<int> getColumnPosition (int index) const;
  40638. /** Finds the column ID at a given x-position in the component.
  40639. If there is a column at this point this returns its ID, or if not, it will return 0.
  40640. */
  40641. int getColumnIdAtX (int xToFind) const;
  40642. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  40643. entire width of the component.
  40644. By default this is disabled. Turning it on also means that when resizing a column, those
  40645. on the right will be squashed to fit.
  40646. */
  40647. void setStretchToFitActive (bool shouldStretchToFit);
  40648. /** Returns true if stretch-to-fit has been enabled.
  40649. @see setStretchToFitActive
  40650. */
  40651. bool isStretchToFitActive() const;
  40652. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  40653. specified width, keeping their relative proportions the same.
  40654. If the minimum widths of the columns are too wide to fit into this space, it may
  40655. actually end up wider.
  40656. */
  40657. void resizeAllColumnsToFit (int targetTotalWidth);
  40658. /** Enables or disables the pop-up menu.
  40659. The default menu allows the user to show or hide columns. You can add custom
  40660. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  40661. By default the menu is enabled.
  40662. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  40663. */
  40664. void setPopupMenuActive (bool hasMenu);
  40665. /** Returns true if the pop-up menu is enabled.
  40666. @see setPopupMenuActive
  40667. */
  40668. bool isPopupMenuActive() const;
  40669. /** Returns a string that encapsulates the table's current layout.
  40670. This can be restored later using restoreFromString(). It saves the order of
  40671. the columns, the currently-sorted column, and the widths.
  40672. @see restoreFromString
  40673. */
  40674. const String toString() const;
  40675. /** Restores the state of the table, based on a string previously created with
  40676. toString().
  40677. @see toString
  40678. */
  40679. void restoreFromString (const String& storedVersion);
  40680. /**
  40681. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  40682. You can register one of these objects for table events using TableHeaderComponent::addListener()
  40683. and TableHeaderComponent::removeListener().
  40684. @see TableHeaderComponent
  40685. */
  40686. class JUCE_API Listener
  40687. {
  40688. public:
  40689. Listener() {}
  40690. /** Destructor. */
  40691. virtual ~Listener() {}
  40692. /** This is called when some of the table's columns are added, removed, hidden,
  40693. or rearranged.
  40694. */
  40695. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  40696. /** This is called when one or more of the table's columns are resized.
  40697. */
  40698. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  40699. /** This is called when the column by which the table should be sorted is changed.
  40700. */
  40701. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  40702. /** This is called when the user begins or ends dragging one of the columns around.
  40703. When the user starts dragging a column, this is called with the ID of that
  40704. column. When they finish dragging, it is called again with 0 as the ID.
  40705. */
  40706. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  40707. int columnIdNowBeingDragged);
  40708. };
  40709. /** Adds a listener to be informed about things that happen to the header. */
  40710. void addListener (Listener* newListener);
  40711. /** Removes a previously-registered listener. */
  40712. void removeListener (Listener* listenerToRemove);
  40713. /** This can be overridden to handle a mouse-click on one of the column headers.
  40714. The default implementation will use this click to call getSortColumnId() and
  40715. change the sort order.
  40716. */
  40717. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  40718. /** This can be overridden to add custom items to the pop-up menu.
  40719. If you override this, you should call the superclass's method to add its
  40720. column show/hide items, if you want them on the menu as well.
  40721. Then to handle the result, override reactToMenuItem().
  40722. @see reactToMenuItem
  40723. */
  40724. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  40725. /** Override this to handle any custom items that you have added to the
  40726. pop-up menu with an addMenuItems() override.
  40727. If the menuReturnId isn't one of your own custom menu items, you'll need to
  40728. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  40729. handle the items that it had added.
  40730. @see addMenuItems
  40731. */
  40732. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  40733. /** @internal */
  40734. void paint (Graphics& g);
  40735. /** @internal */
  40736. void resized();
  40737. /** @internal */
  40738. void mouseMove (const MouseEvent&);
  40739. /** @internal */
  40740. void mouseEnter (const MouseEvent&);
  40741. /** @internal */
  40742. void mouseExit (const MouseEvent&);
  40743. /** @internal */
  40744. void mouseDown (const MouseEvent&);
  40745. /** @internal */
  40746. void mouseDrag (const MouseEvent&);
  40747. /** @internal */
  40748. void mouseUp (const MouseEvent&);
  40749. /** @internal */
  40750. const MouseCursor getMouseCursor();
  40751. /** Can be overridden for more control over the pop-up menu behaviour. */
  40752. virtual void showColumnChooserMenu (int columnIdClicked);
  40753. private:
  40754. struct ColumnInfo
  40755. {
  40756. String name;
  40757. int id, propertyFlags, width, minimumWidth, maximumWidth;
  40758. double lastDeliberateWidth;
  40759. bool isVisible() const;
  40760. };
  40761. OwnedArray <ColumnInfo> columns;
  40762. Array <Listener*> listeners;
  40763. ScopedPointer <Component> dragOverlayComp;
  40764. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  40765. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  40766. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  40767. ColumnInfo* getInfoForId (int columnId) const;
  40768. int visibleIndexToTotalIndex (int visibleIndex) const;
  40769. void sendColumnsChanged();
  40770. void handleAsyncUpdate();
  40771. void beginDrag (const MouseEvent&);
  40772. void endDrag (int finalIndex);
  40773. int getResizeDraggerAt (int mouseX) const;
  40774. void updateColumnUnderMouse (int x, int y);
  40775. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  40776. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableHeaderComponent);
  40777. };
  40778. /** This typedef is just for compatibility with old code - newer code should use the TableHeaderComponent::Listener class directly. */
  40779. typedef TableHeaderComponent::Listener TableHeaderListener;
  40780. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40781. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  40782. #endif
  40783. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  40784. /*** Start of inlined file: juce_TableListBox.h ***/
  40785. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  40786. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  40787. /**
  40788. One of these is used by a TableListBox as the data model for the table's contents.
  40789. The virtual methods that you override in this class take care of drawing the
  40790. table cells, and reacting to events.
  40791. @see TableListBox
  40792. */
  40793. class JUCE_API TableListBoxModel
  40794. {
  40795. public:
  40796. TableListBoxModel() {}
  40797. /** Destructor. */
  40798. virtual ~TableListBoxModel() {}
  40799. /** This must return the number of rows currently in the table.
  40800. If the number of rows changes, you must call TableListBox::updateContent() to
  40801. cause it to refresh the list.
  40802. */
  40803. virtual int getNumRows() = 0;
  40804. /** This must draw the background behind one of the rows in the table.
  40805. The graphics context has its origin at the row's top-left, and your method
  40806. should fill the area specified by the width and height parameters.
  40807. */
  40808. virtual void paintRowBackground (Graphics& g,
  40809. int rowNumber,
  40810. int width, int height,
  40811. bool rowIsSelected) = 0;
  40812. /** This must draw one of the cells.
  40813. The graphics context's origin will already be set to the top-left of the cell,
  40814. whose size is specified by (width, height).
  40815. */
  40816. virtual void paintCell (Graphics& g,
  40817. int rowNumber,
  40818. int columnId,
  40819. int width, int height,
  40820. bool rowIsSelected) = 0;
  40821. /** This is used to create or update a custom component to go in a cell.
  40822. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  40823. and handle mouse clicks with cellClicked().
  40824. This method will be called whenever a custom component might need to be updated - e.g.
  40825. when the table is changed, or TableListBox::updateContent() is called.
  40826. If you don't need a custom component for the specified cell, then return 0.
  40827. If you do want a custom component, and the existingComponentToUpdate is null, then
  40828. this method must create a new component suitable for the cell, and return it.
  40829. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  40830. by this method. In this case, the method must either update it to make sure it's correctly representing
  40831. the given cell (which may be different from the one that the component was created for), or it can
  40832. delete this component and return a new one.
  40833. */
  40834. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  40835. Component* existingComponentToUpdate);
  40836. /** This callback is made when the user clicks on one of the cells in the table.
  40837. The mouse event's coordinates will be relative to the entire table row.
  40838. @see cellDoubleClicked, backgroundClicked
  40839. */
  40840. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  40841. /** This callback is made when the user clicks on one of the cells in the table.
  40842. The mouse event's coordinates will be relative to the entire table row.
  40843. @see cellClicked, backgroundClicked
  40844. */
  40845. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  40846. /** This can be overridden to react to the user double-clicking on a part of the list where
  40847. there are no rows.
  40848. @see cellClicked
  40849. */
  40850. virtual void backgroundClicked();
  40851. /** This callback is made when the table's sort order is changed.
  40852. This could be because the user has clicked a column header, or because the
  40853. TableHeaderComponent::setSortColumnId() method was called.
  40854. If you implement this, your method should re-sort the table using the given
  40855. column as the key.
  40856. */
  40857. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  40858. /** Returns the best width for one of the columns.
  40859. If you implement this method, you should measure the width of all the items
  40860. in this column, and return the best size.
  40861. Returning 0 means that the column shouldn't be changed.
  40862. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  40863. */
  40864. virtual int getColumnAutoSizeWidth (int columnId);
  40865. /** Returns a tooltip for a particular cell in the table.
  40866. */
  40867. virtual const String getCellTooltip (int rowNumber, int columnId);
  40868. /** Override this to be informed when rows are selected or deselected.
  40869. @see ListBox::selectedRowsChanged()
  40870. */
  40871. virtual void selectedRowsChanged (int lastRowSelected);
  40872. /** Override this to be informed when the delete key is pressed.
  40873. @see ListBox::deleteKeyPressed()
  40874. */
  40875. virtual void deleteKeyPressed (int lastRowSelected);
  40876. /** Override this to be informed when the return key is pressed.
  40877. @see ListBox::returnKeyPressed()
  40878. */
  40879. virtual void returnKeyPressed (int lastRowSelected);
  40880. /** Override this to be informed when the list is scrolled.
  40881. This might be caused by the user moving the scrollbar, or by programmatic changes
  40882. to the list position.
  40883. */
  40884. virtual void listWasScrolled();
  40885. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  40886. If this returns a non-null variant then when the user drags a row, the table will try to
  40887. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  40888. drag-and-drop operation, using this string as the source description, and the listbox
  40889. itself as the source component.
  40890. @see getDragSourceCustomData, DragAndDropContainer::startDragging
  40891. */
  40892. virtual const var getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  40893. };
  40894. /**
  40895. A table of cells, using a TableHeaderComponent as its header.
  40896. This component makes it easy to create a table by providing a TableListBoxModel as
  40897. the data source.
  40898. @see TableListBoxModel, TableHeaderComponent
  40899. */
  40900. class JUCE_API TableListBox : public ListBox,
  40901. private ListBoxModel,
  40902. private TableHeaderComponent::Listener
  40903. {
  40904. public:
  40905. /** Creates a TableListBox.
  40906. The model pointer passed-in can be null, in which case you can set it later
  40907. with setModel().
  40908. */
  40909. TableListBox (const String& componentName = String::empty,
  40910. TableListBoxModel* model = 0);
  40911. /** Destructor. */
  40912. ~TableListBox();
  40913. /** Changes the TableListBoxModel that is being used for this table.
  40914. */
  40915. void setModel (TableListBoxModel* newModel);
  40916. /** Returns the model currently in use. */
  40917. TableListBoxModel* getModel() const { return model; }
  40918. /** Returns the header component being used in this table. */
  40919. TableHeaderComponent& getHeader() const { return *header; }
  40920. /** Sets the header component to use for the table.
  40921. The table will take ownership of the component that you pass in, and will delete it
  40922. when it's no longer needed.
  40923. */
  40924. void setHeader (TableHeaderComponent* newHeader);
  40925. /** Changes the height of the table header component.
  40926. @see getHeaderHeight
  40927. */
  40928. void setHeaderHeight (int newHeight);
  40929. /** Returns the height of the table header.
  40930. @see setHeaderHeight
  40931. */
  40932. int getHeaderHeight() const;
  40933. /** Resizes a column to fit its contents.
  40934. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  40935. and applies that to the column.
  40936. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  40937. */
  40938. void autoSizeColumn (int columnId);
  40939. /** Calls autoSizeColumn() for all columns in the table. */
  40940. void autoSizeAllColumns();
  40941. /** Enables or disables the auto size options on the popup menu.
  40942. By default, these are enabled.
  40943. */
  40944. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  40945. /** True if the auto-size options should be shown on the menu.
  40946. @see setAutoSizeMenuOptionsShown
  40947. */
  40948. bool isAutoSizeMenuOptionShown() const;
  40949. /** Returns the position of one of the cells in the table.
  40950. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  40951. the table component's top-left. The row number isn't checked to see if it's
  40952. in-range, but the column ID must exist or this will return an empty rectangle.
  40953. If relativeToComponentTopLeft is false, the co-ords are relative to the
  40954. top-left of the table's top-left cell.
  40955. */
  40956. const Rectangle<int> getCellPosition (int columnId, int rowNumber,
  40957. bool relativeToComponentTopLeft) const;
  40958. /** Returns the component that currently represents a given cell.
  40959. If the component for this cell is off-screen or if the position is out-of-range,
  40960. this may return 0.
  40961. @see getCellPosition
  40962. */
  40963. Component* getCellComponent (int columnId, int rowNumber) const;
  40964. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  40965. @see ListBox::scrollToEnsureRowIsOnscreen
  40966. */
  40967. void scrollToEnsureColumnIsOnscreen (int columnId);
  40968. /** @internal */
  40969. int getNumRows();
  40970. /** @internal */
  40971. void paintListBoxItem (int, Graphics&, int, int, bool);
  40972. /** @internal */
  40973. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  40974. /** @internal */
  40975. void selectedRowsChanged (int lastRowSelected);
  40976. /** @internal */
  40977. void deleteKeyPressed (int currentSelectedRow);
  40978. /** @internal */
  40979. void returnKeyPressed (int currentSelectedRow);
  40980. /** @internal */
  40981. void backgroundClicked();
  40982. /** @internal */
  40983. void listWasScrolled();
  40984. /** @internal */
  40985. void tableColumnsChanged (TableHeaderComponent*);
  40986. /** @internal */
  40987. void tableColumnsResized (TableHeaderComponent*);
  40988. /** @internal */
  40989. void tableSortOrderChanged (TableHeaderComponent*);
  40990. /** @internal */
  40991. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  40992. /** @internal */
  40993. void resized();
  40994. private:
  40995. TableHeaderComponent* header;
  40996. TableListBoxModel* model;
  40997. int columnIdNowBeingDragged;
  40998. bool autoSizeOptionsShown;
  40999. void updateColumnComponents() const;
  41000. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBox);
  41001. };
  41002. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  41003. /*** End of inlined file: juce_TableListBox.h ***/
  41004. #endif
  41005. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  41006. #endif
  41007. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  41008. #endif
  41009. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  41010. #endif
  41011. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41012. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  41013. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41014. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41015. /**
  41016. A factory object which can create ToolbarItemComponent objects.
  41017. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  41018. that it can create.
  41019. Each type of item is identified by a unique ID, and multiple instances of an
  41020. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  41021. bars).
  41022. @see Toolbar, ToolbarItemComponent, ToolbarButton
  41023. */
  41024. class JUCE_API ToolbarItemFactory
  41025. {
  41026. public:
  41027. ToolbarItemFactory();
  41028. /** Destructor. */
  41029. virtual ~ToolbarItemFactory();
  41030. /** A set of reserved item ID values, used for the built-in item types.
  41031. */
  41032. enum SpecialItemIds
  41033. {
  41034. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  41035. can be placed between sets of items to break them into groups. */
  41036. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  41037. items.*/
  41038. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  41039. either side of it, filling any available space. */
  41040. };
  41041. /** Must return a list of the IDs for all the item types that this factory can create.
  41042. The ids should be added to the array that is passed-in.
  41043. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  41044. and the predefined IDs in the SpecialItemIds enum.
  41045. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  41046. to this list if you want your toolbar to be able to contain those items.
  41047. The list returned here is used by the ToolbarItemPalette class to obtain its list
  41048. of available items, and their order on the palette will reflect the order in which
  41049. they appear on this list.
  41050. @see ToolbarItemPalette
  41051. */
  41052. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  41053. /** Must return the set of items that should be added to a toolbar as its default set.
  41054. This method is used by Toolbar::addDefaultItems() to determine which items to
  41055. create.
  41056. The items that your method adds to the array that is passed-in will be added to the
  41057. toolbar in the same order. Items can appear in the list more than once.
  41058. */
  41059. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  41060. /** Must create an instance of one of the items that the factory lists in its
  41061. getAllToolbarItemIds() method.
  41062. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  41063. method, except for the built-in item types from the SpecialItemIds enum, which
  41064. are created internally by the toolbar code.
  41065. Try not to keep a pointer to the object that is returned, as it will be deleted
  41066. automatically by the toolbar, and remember that multiple instances of the same
  41067. item type are likely to exist at the same time.
  41068. */
  41069. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  41070. };
  41071. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41072. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  41073. #endif
  41074. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41075. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  41076. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41077. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41078. /**
  41079. A component containing a list of toolbar items, which the user can drag onto
  41080. a toolbar to add them.
  41081. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  41082. which automatically shows one of these in a dialog box with lots of extra controls.
  41083. @see Toolbar
  41084. */
  41085. class JUCE_API ToolbarItemPalette : public Component,
  41086. public DragAndDropContainer
  41087. {
  41088. public:
  41089. /** Creates a palette of items for a given factory, with the aim of adding them
  41090. to the specified toolbar.
  41091. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  41092. set of items that are shown in this palette.
  41093. The toolbar and factory must not be deleted while this object exists.
  41094. */
  41095. ToolbarItemPalette (ToolbarItemFactory& factory,
  41096. Toolbar* toolbar);
  41097. /** Destructor. */
  41098. ~ToolbarItemPalette();
  41099. /** @internal */
  41100. void resized();
  41101. private:
  41102. ToolbarItemFactory& factory;
  41103. Toolbar* toolbar;
  41104. Viewport viewport;
  41105. OwnedArray <ToolbarItemComponent> items;
  41106. friend class Toolbar;
  41107. void replaceComponent (ToolbarItemComponent* comp);
  41108. void addComponent (int itemId, int index);
  41109. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemPalette);
  41110. };
  41111. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41112. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  41113. #endif
  41114. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  41115. /*** Start of inlined file: juce_TreeView.h ***/
  41116. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  41117. #define __JUCE_TREEVIEW_JUCEHEADER__
  41118. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  41119. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41120. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41121. /**
  41122. Components derived from this class can have files dropped onto them by an external application.
  41123. @see DragAndDropContainer
  41124. */
  41125. class JUCE_API FileDragAndDropTarget
  41126. {
  41127. public:
  41128. /** Destructor. */
  41129. virtual ~FileDragAndDropTarget() {}
  41130. /** Callback to check whether this target is interested in the set of files being offered.
  41131. Note that this will be called repeatedly when the user is dragging the mouse around over your
  41132. component, so don't do anything time-consuming in here, like opening the files to have a look
  41133. inside them!
  41134. @param files the set of (absolute) pathnames of the files that the user is dragging
  41135. @returns true if this component wants to receive the other callbacks regarging this
  41136. type of object; if it returns false, no other callbacks will be made.
  41137. */
  41138. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  41139. /** Callback to indicate that some files are being dragged over this component.
  41140. This gets called when the user moves the mouse into this component while dragging.
  41141. Use this callback as a trigger to make your component repaint itself to give the
  41142. user feedback about whether the files can be dropped here or not.
  41143. @param files the set of (absolute) pathnames of the files that the user is dragging
  41144. @param x the mouse x position, relative to this component
  41145. @param y the mouse y position, relative to this component
  41146. */
  41147. virtual void fileDragEnter (const StringArray& files, int x, int y);
  41148. /** Callback to indicate that the user is dragging some files over this component.
  41149. This gets called when the user moves the mouse over this component while dragging.
  41150. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  41151. this lets you know what happens in-between.
  41152. @param files the set of (absolute) pathnames of the files that the user is dragging
  41153. @param x the mouse x position, relative to this component
  41154. @param y the mouse y position, relative to this component
  41155. */
  41156. virtual void fileDragMove (const StringArray& files, int x, int y);
  41157. /** Callback to indicate that the mouse has moved away from this component.
  41158. This gets called when the user moves the mouse out of this component while dragging
  41159. the files.
  41160. If you've used fileDragEnter() to repaint your component and give feedback, use this
  41161. as a signal to repaint it in its normal state.
  41162. @param files the set of (absolute) pathnames of the files that the user is dragging
  41163. */
  41164. virtual void fileDragExit (const StringArray& files);
  41165. /** Callback to indicate that the user has dropped the files onto this component.
  41166. When the user drops the files, this get called, and you can use the files in whatever
  41167. way is appropriate.
  41168. Note that after this is called, the fileDragExit method may not be called, so you should
  41169. clean up in here if there's anything you need to do when the drag finishes.
  41170. @param files the set of (absolute) pathnames of the files that the user is dragging
  41171. @param x the mouse x position, relative to this component
  41172. @param y the mouse y position, relative to this component
  41173. */
  41174. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  41175. };
  41176. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41177. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  41178. class TreeView;
  41179. /**
  41180. An item in a treeview.
  41181. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  41182. own sub-items.
  41183. To implement an item that contains sub-items, override the itemOpennessChanged()
  41184. method so that when it is opened, it adds the new sub-items to itself using the
  41185. addSubItem method. Depending on the nature of the item it might choose to only
  41186. do this the first time it's opened, or it might want to refresh itself each time.
  41187. It also has the option of deleting its sub-items when it is closed, or leaving them
  41188. in place.
  41189. */
  41190. class JUCE_API TreeViewItem
  41191. {
  41192. public:
  41193. /** Constructor. */
  41194. TreeViewItem();
  41195. /** Destructor. */
  41196. virtual ~TreeViewItem();
  41197. /** Returns the number of sub-items that have been added to this item.
  41198. Note that this doesn't mean much if the node isn't open.
  41199. @see getSubItem, mightContainSubItems, addSubItem
  41200. */
  41201. int getNumSubItems() const noexcept;
  41202. /** Returns one of the item's sub-items.
  41203. Remember that the object returned might get deleted at any time when its parent
  41204. item is closed or refreshed, depending on the nature of the items you're using.
  41205. @see getNumSubItems
  41206. */
  41207. TreeViewItem* getSubItem (int index) const noexcept;
  41208. /** Removes any sub-items. */
  41209. void clearSubItems();
  41210. /** Adds a sub-item.
  41211. @param newItem the object to add to the item's sub-item list. Once added, these can be
  41212. found using getSubItem(). When the items are later removed with
  41213. removeSubItem() (or when this item is deleted), they will be deleted.
  41214. @param insertPosition the index which the new item should have when it's added. If this
  41215. value is less than 0, the item will be added to the end of the list.
  41216. */
  41217. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  41218. /** Removes one of the sub-items.
  41219. @param index the item to remove
  41220. @param deleteItem if true, the item that is removed will also be deleted.
  41221. */
  41222. void removeSubItem (int index, bool deleteItem = true);
  41223. /** Returns the TreeView to which this item belongs. */
  41224. TreeView* getOwnerView() const noexcept { return ownerView; }
  41225. /** Returns the item within which this item is contained. */
  41226. TreeViewItem* getParentItem() const noexcept { return parentItem; }
  41227. /** True if this item is currently open in the treeview. */
  41228. bool isOpen() const noexcept;
  41229. /** Opens or closes the item.
  41230. When opened or closed, the item's itemOpennessChanged() method will be called,
  41231. and a subclass should use this callback to create and add any sub-items that
  41232. it needs to.
  41233. @see itemOpennessChanged, mightContainSubItems
  41234. */
  41235. void setOpen (bool shouldBeOpen);
  41236. /** True if this item is currently selected.
  41237. Use this when painting the node, to decide whether to draw it as selected or not.
  41238. */
  41239. bool isSelected() const noexcept;
  41240. /** Selects or deselects the item.
  41241. This will cause a callback to itemSelectionChanged()
  41242. */
  41243. void setSelected (bool shouldBeSelected,
  41244. bool deselectOtherItemsFirst);
  41245. /** Returns the rectangle that this item occupies.
  41246. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  41247. top-left of the TreeView comp, so this will depend on the scroll-position of
  41248. the tree. If false, it is relative to the top-left of the topmost item in the
  41249. tree (so this would be unaffected by scrolling the view).
  41250. */
  41251. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const noexcept;
  41252. /** Sends a signal to the treeview to make it refresh itself.
  41253. Call this if your items have changed and you want the tree to update to reflect
  41254. this.
  41255. */
  41256. void treeHasChanged() const noexcept;
  41257. /** Sends a repaint message to redraw just this item.
  41258. Note that you should only call this if you want to repaint a superficial change. If
  41259. you're altering the tree's nodes, you should instead call treeHasChanged().
  41260. */
  41261. void repaintItem() const;
  41262. /** Returns the row number of this item in the tree.
  41263. The row number of an item will change according to which items are open.
  41264. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  41265. */
  41266. int getRowNumberInTree() const noexcept;
  41267. /** Returns true if all the item's parent nodes are open.
  41268. This is useful to check whether the item might actually be visible or not.
  41269. */
  41270. bool areAllParentsOpen() const noexcept;
  41271. /** Changes whether lines are drawn to connect any sub-items to this item.
  41272. By default, line-drawing is turned on.
  41273. */
  41274. void setLinesDrawnForSubItems (bool shouldDrawLines) noexcept;
  41275. /** Tells the tree whether this item can potentially be opened.
  41276. If your item could contain sub-items, this should return true; if it returns
  41277. false then the tree will not try to open the item. This determines whether or
  41278. not the item will be drawn with a 'plus' button next to it.
  41279. */
  41280. virtual bool mightContainSubItems() = 0;
  41281. /** Returns a string to uniquely identify this item.
  41282. If you're planning on using the TreeView::getOpennessState() method, then
  41283. these strings will be used to identify which nodes are open. The string
  41284. should be unique amongst the item's sibling items, but it's ok for there
  41285. to be duplicates at other levels of the tree.
  41286. If you're not going to store the state, then it's ok not to bother implementing
  41287. this method.
  41288. */
  41289. virtual const String getUniqueName() const;
  41290. /** Called when an item is opened or closed.
  41291. When setOpen() is called and the item has specified that it might
  41292. have sub-items with the mightContainSubItems() method, this method
  41293. is called to let the item create or manage its sub-items.
  41294. So when this is called with isNowOpen set to true (i.e. when the item is being
  41295. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  41296. refresh its sub-item list.
  41297. When this is called with isNowOpen set to false, the subclass might want
  41298. to use clearSubItems() to save on space, or it might choose to leave them,
  41299. depending on the nature of the tree.
  41300. You could also use this callback as a trigger to start a background process
  41301. which asynchronously creates sub-items and adds them, if that's more
  41302. appropriate for the task in hand.
  41303. @see mightContainSubItems
  41304. */
  41305. virtual void itemOpennessChanged (bool isNowOpen);
  41306. /** Must return the width required by this item.
  41307. If your item needs to have a particular width in pixels, return that value; if
  41308. you'd rather have it just fill whatever space is available in the treeview,
  41309. return -1.
  41310. If all your items return -1, no horizontal scrollbar will be shown, but if any
  41311. items have fixed widths and extend beyond the width of the treeview, a
  41312. scrollbar will appear.
  41313. Each item can be a different width, but if they change width, you should call
  41314. treeHasChanged() to update the tree.
  41315. */
  41316. virtual int getItemWidth() const { return -1; }
  41317. /** Must return the height required by this item.
  41318. This is the height in pixels that the item will take up. Items in the tree
  41319. can be different heights, but if they change height, you should call
  41320. treeHasChanged() to update the tree.
  41321. */
  41322. virtual int getItemHeight() const { return 20; }
  41323. /** You can override this method to return false if you don't want to allow the
  41324. user to select this item.
  41325. */
  41326. virtual bool canBeSelected() const { return true; }
  41327. /** Creates a component that will be used to represent this item.
  41328. You don't have to implement this method - if it returns 0 then no component
  41329. will be used for the item, and you can just draw it using the paintItem()
  41330. callback. But if you do return a component, it will be positioned in the
  41331. treeview so that it can be used to represent this item.
  41332. The component returned will be managed by the treeview, so always return
  41333. a new component, and don't keep a reference to it, as the treeview will
  41334. delete it later when it goes off the screen or is no longer needed. Also
  41335. bear in mind that if the component keeps a reference to the item that
  41336. created it, that item could be deleted before the component. Its position
  41337. and size will be completely managed by the tree, so don't attempt to move it
  41338. around.
  41339. Something you may want to do with your component is to give it a pointer to
  41340. the TreeView that created it. This is perfectly safe, and there's no danger
  41341. of it becoming a dangling pointer because the TreeView will always delete
  41342. the component before it is itself deleted.
  41343. As long as you stick to these rules you can return whatever kind of
  41344. component you like. It's most useful if you're doing things like drag-and-drop
  41345. of items, or want to use a Label component to edit item names, etc.
  41346. */
  41347. virtual Component* createItemComponent() { return nullptr; }
  41348. /** Draws the item's contents.
  41349. You can choose to either implement this method and draw each item, or you
  41350. can use createItemComponent() to create a component that will represent the
  41351. item.
  41352. If all you need in your tree is to be able to draw the items and detect when
  41353. the user selects or double-clicks one of them, it's probably enough to
  41354. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  41355. complicated interactions, you may need to use createItemComponent() instead.
  41356. @param g the graphics context to draw into
  41357. @param width the width of the area available for drawing
  41358. @param height the height of the area available for drawing
  41359. */
  41360. virtual void paintItem (Graphics& g, int width, int height);
  41361. /** Draws the item's open/close button.
  41362. If you don't implement this method, the default behaviour is to
  41363. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  41364. it for custom effects.
  41365. */
  41366. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  41367. /** Called when the user clicks on this item.
  41368. If you're using createItemComponent() to create a custom component for the
  41369. item, the mouse-clicks might not make it through to the treeview, but this
  41370. is how you find out about clicks when just drawing each item individually.
  41371. The associated mouse-event details are passed in, so you can find out about
  41372. which button, where it was, etc.
  41373. @see itemDoubleClicked
  41374. */
  41375. virtual void itemClicked (const MouseEvent& e);
  41376. /** Called when the user double-clicks on this item.
  41377. If you're using createItemComponent() to create a custom component for the
  41378. item, the mouse-clicks might not make it through to the treeview, but this
  41379. is how you find out about clicks when just drawing each item individually.
  41380. The associated mouse-event details are passed in, so you can find out about
  41381. which button, where it was, etc.
  41382. If not overridden, the base class method here will open or close the item as
  41383. if the 'plus' button had been clicked.
  41384. @see itemClicked
  41385. */
  41386. virtual void itemDoubleClicked (const MouseEvent& e);
  41387. /** Called when the item is selected or deselected.
  41388. Use this if you want to do something special when the item's selectedness
  41389. changes. By default it'll get repainted when this happens.
  41390. */
  41391. virtual void itemSelectionChanged (bool isNowSelected);
  41392. /** The item can return a tool tip string here if it wants to.
  41393. @see TooltipClient
  41394. */
  41395. virtual const String getTooltip();
  41396. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  41397. If this returns a non-null variant then when the user drags an item, the treeview will
  41398. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  41399. a drag-and-drop operation, using this string as the source description, with the treeview
  41400. itself as the source component.
  41401. If you need more complex drag-and-drop behaviour, you can use custom components for
  41402. the items, and use those to trigger the drag.
  41403. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  41404. isInterestedInFileDrag(), etc.
  41405. @see DragAndDropContainer::startDragging
  41406. */
  41407. virtual const var getDragSourceDescription();
  41408. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  41409. method and return true.
  41410. If you return true and allow some files to be dropped, you'll also need to implement the
  41411. filesDropped() method to do something with them.
  41412. Note that this will be called often, so make your implementation very quick! There's
  41413. certainly no time to try opening the files and having a think about what's inside them!
  41414. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  41415. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  41416. */
  41417. virtual bool isInterestedInFileDrag (const StringArray& files);
  41418. /** When files are dropped into this item, this callback is invoked.
  41419. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  41420. The insertIndex value indicates where in the list of sub-items the files were dropped.
  41421. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  41422. */
  41423. virtual void filesDropped (const StringArray& files, int insertIndex);
  41424. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  41425. If you implement this method, you'll also need to implement itemDropped() in order to handle
  41426. the items when they are dropped.
  41427. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  41428. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  41429. */
  41430. virtual bool isInterestedInDragSource (const DragAndDropTarget::SourceDetails& dragSourceDetails);
  41431. /** When a things are dropped into this item, this callback is invoked.
  41432. For this to work, you need to have also implemented isInterestedInDragSource().
  41433. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  41434. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  41435. */
  41436. virtual void itemDropped (const DragAndDropTarget::SourceDetails& dragSourceDetails, int insertIndex);
  41437. /** Sets a flag to indicate that the item wants to be allowed
  41438. to draw all the way across to the left edge of the treeview.
  41439. By default this is false, which means that when the paintItem()
  41440. method is called, its graphics context is clipped to only allow
  41441. drawing within the item's rectangle. If this flag is set to true,
  41442. then the graphics context isn't clipped on its left side, so it
  41443. can draw all the way across to the left margin. Note that the
  41444. context will still have its origin in the same place though, so
  41445. the coordinates of anything to its left will be negative. It's
  41446. mostly useful if you want to draw a wider bar behind the
  41447. highlighted item.
  41448. */
  41449. void setDrawsInLeftMargin (bool canDrawInLeftMargin) noexcept;
  41450. /** Saves the current state of open/closed nodes so it can be restored later.
  41451. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  41452. and records it as XML. To identify node objects it uses the
  41453. TreeViewItem::getUniqueName() method to create named paths. This
  41454. means that the same state of open/closed nodes can be restored to a
  41455. completely different instance of the tree, as long as it contains nodes
  41456. whose unique names are the same.
  41457. You'd normally want to use TreeView::getOpennessState() rather than call it
  41458. for a specific item, but this can be handy if you need to briefly save the state
  41459. for a section of the tree.
  41460. The caller is responsible for deleting the object that is returned.
  41461. @see TreeView::getOpennessState, restoreOpennessState
  41462. */
  41463. XmlElement* getOpennessState() const noexcept;
  41464. /** Restores the openness of this item and all its sub-items from a saved state.
  41465. See TreeView::restoreOpennessState for more details.
  41466. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  41467. for a specific item, but this can be handy if you need to briefly save the state
  41468. for a section of the tree.
  41469. @see TreeView::restoreOpennessState, getOpennessState
  41470. */
  41471. void restoreOpennessState (const XmlElement& xml) noexcept;
  41472. /** Returns the index of this item in its parent's sub-items. */
  41473. int getIndexInParent() const noexcept;
  41474. /** Returns true if this item is the last of its parent's sub-itens. */
  41475. bool isLastOfSiblings() const noexcept;
  41476. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  41477. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  41478. The string takes the form of a path, constructed from the getUniqueName() of this
  41479. item and all its parents, so these must all be correctly implemented for it to work.
  41480. @see TreeView::findItemFromIdentifierString, getUniqueName
  41481. */
  41482. const String getItemIdentifierString() const;
  41483. /**
  41484. This handy class takes a copy of a TreeViewItem's openness when you create it,
  41485. and restores that openness state when its destructor is called.
  41486. This can very handy when you're refreshing sub-items - e.g.
  41487. @code
  41488. void MyTreeViewItem::updateChildItems()
  41489. {
  41490. OpennessRestorer openness (*this); // saves the openness state here..
  41491. clearSubItems();
  41492. // add a bunch of sub-items here which may or may not be the same as the ones that
  41493. // were previously there
  41494. addSubItem (...
  41495. // ..and at this point, the old openness is restored, so any items that haven't
  41496. // changed will have their old openness retained.
  41497. }
  41498. @endcode
  41499. */
  41500. class OpennessRestorer
  41501. {
  41502. public:
  41503. OpennessRestorer (TreeViewItem& treeViewItem);
  41504. ~OpennessRestorer();
  41505. private:
  41506. TreeViewItem& treeViewItem;
  41507. ScopedPointer <XmlElement> oldOpenness;
  41508. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpennessRestorer);
  41509. };
  41510. private:
  41511. TreeView* ownerView;
  41512. TreeViewItem* parentItem;
  41513. OwnedArray <TreeViewItem> subItems;
  41514. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  41515. int uid;
  41516. bool selected : 1;
  41517. bool redrawNeeded : 1;
  41518. bool drawLinesInside : 1;
  41519. bool drawsInLeftMargin : 1;
  41520. unsigned int openness : 2;
  41521. friend class TreeView;
  41522. friend class TreeViewContentComponent;
  41523. void updatePositions (int newY);
  41524. int getIndentX() const noexcept;
  41525. void setOwnerView (TreeView* newOwner) noexcept;
  41526. void paintRecursively (Graphics& g, int width);
  41527. TreeViewItem* getTopLevelItem() noexcept;
  41528. TreeViewItem* findItemRecursively (int y) noexcept;
  41529. TreeViewItem* getDeepestOpenParentItem() noexcept;
  41530. int getNumRows() const noexcept;
  41531. TreeViewItem* getItemOnRow (int index) noexcept;
  41532. void deselectAllRecursively();
  41533. int countSelectedItemsRecursively (int depth) const noexcept;
  41534. TreeViewItem* getSelectedItemWithIndex (int index) noexcept;
  41535. TreeViewItem* getNextVisibleItem (bool recurse) const noexcept;
  41536. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  41537. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  41538. // The parameters for these methods have changed - please update your code!
  41539. virtual void isInterestedInDragSource (const String&, Component*) {}
  41540. virtual int itemDropped (const String&, Component*, int) { return 0; }
  41541. #endif
  41542. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewItem);
  41543. };
  41544. /**
  41545. A tree-view component.
  41546. Use one of these to hold and display a structure of TreeViewItem objects.
  41547. */
  41548. class JUCE_API TreeView : public Component,
  41549. public SettableTooltipClient,
  41550. public FileDragAndDropTarget,
  41551. public DragAndDropTarget,
  41552. private AsyncUpdater
  41553. {
  41554. public:
  41555. /** Creates an empty treeview.
  41556. Once you've got a treeview component, you'll need to give it something to
  41557. display, using the setRootItem() method.
  41558. */
  41559. TreeView (const String& componentName = String::empty);
  41560. /** Destructor. */
  41561. ~TreeView();
  41562. /** Sets the item that is displayed in the treeview.
  41563. A tree has a single root item which contains as many sub-items as it needs. If
  41564. you want the tree to contain a number of root items, you should still use a single
  41565. root item above these, but hide it using setRootItemVisible().
  41566. You can pass in 0 to this method to clear the tree and remove its current root item.
  41567. The object passed in will not be deleted by the treeview, it's up to the caller
  41568. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  41569. this item until you've removed it from the tree, either by calling setRootItem (nullptr),
  41570. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  41571. to delete it.
  41572. */
  41573. void setRootItem (TreeViewItem* newRootItem);
  41574. /** Returns the tree's root item.
  41575. This will be the last object passed to setRootItem(), or 0 if none has been set.
  41576. */
  41577. TreeViewItem* getRootItem() const noexcept { return rootItem; }
  41578. /** This will remove and delete the current root item.
  41579. It's a convenient way of deleting the item and calling setRootItem (nullptr).
  41580. */
  41581. void deleteRootItem();
  41582. /** Changes whether the tree's root item is shown or not.
  41583. If the root item is hidden, only its sub-items will be shown in the treeview - this
  41584. lets you make the tree look as if it's got many root items. If it's hidden, this call
  41585. will also make sure the root item is open (otherwise the treeview would look empty).
  41586. */
  41587. void setRootItemVisible (bool shouldBeVisible);
  41588. /** Returns true if the root item is visible.
  41589. @see setRootItemVisible
  41590. */
  41591. bool isRootItemVisible() const noexcept { return rootItemVisible; }
  41592. /** Sets whether items are open or closed by default.
  41593. Normally, items are closed until the user opens them, but you can use this
  41594. to make them default to being open until explicitly closed.
  41595. @see areItemsOpenByDefault
  41596. */
  41597. void setDefaultOpenness (bool isOpenByDefault);
  41598. /** Returns true if the tree's items default to being open.
  41599. @see setDefaultOpenness
  41600. */
  41601. bool areItemsOpenByDefault() const noexcept { return defaultOpenness; }
  41602. /** This sets a flag to indicate that the tree can be used for multi-selection.
  41603. You can always select multiple items internally by calling the
  41604. TreeViewItem::setSelected() method, but this flag indicates whether the user
  41605. is allowed to multi-select by clicking on the tree.
  41606. By default it is disabled.
  41607. @see isMultiSelectEnabled
  41608. */
  41609. void setMultiSelectEnabled (bool canMultiSelect);
  41610. /** Returns whether multi-select has been enabled for the tree.
  41611. @see setMultiSelectEnabled
  41612. */
  41613. bool isMultiSelectEnabled() const noexcept { return multiSelectEnabled; }
  41614. /** Sets a flag to indicate whether to hide the open/close buttons.
  41615. @see areOpenCloseButtonsVisible
  41616. */
  41617. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  41618. /** Returns whether open/close buttons are shown.
  41619. @see setOpenCloseButtonsVisible
  41620. */
  41621. bool areOpenCloseButtonsVisible() const noexcept { return openCloseButtonsVisible; }
  41622. /** Deselects any items that are currently selected. */
  41623. void clearSelectedItems();
  41624. /** Returns the number of items that are currently selected.
  41625. If maximumDepthToSearchTo is >= 0, it lets you specify a maximum depth to which the
  41626. tree will be recursed.
  41627. @see getSelectedItem, clearSelectedItems
  41628. */
  41629. int getNumSelectedItems (int maximumDepthToSearchTo = -1) const noexcept;
  41630. /** Returns one of the selected items in the tree.
  41631. @param index the index, 0 to (getNumSelectedItems() - 1)
  41632. */
  41633. TreeViewItem* getSelectedItem (int index) const noexcept;
  41634. /** Returns the number of rows the tree is using.
  41635. This will depend on which items are open.
  41636. @see TreeViewItem::getRowNumberInTree()
  41637. */
  41638. int getNumRowsInTree() const;
  41639. /** Returns the item on a particular row of the tree.
  41640. If the index is out of range, this will return 0.
  41641. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  41642. */
  41643. TreeViewItem* getItemOnRow (int index) const;
  41644. /** Returns the item that contains a given y position.
  41645. The y is relative to the top of the TreeView component.
  41646. */
  41647. TreeViewItem* getItemAt (int yPosition) const noexcept;
  41648. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  41649. void scrollToKeepItemVisible (TreeViewItem* item);
  41650. /** Returns the treeview's Viewport object. */
  41651. Viewport* getViewport() const noexcept;
  41652. /** Returns the number of pixels by which each nested level of the tree is indented.
  41653. @see setIndentSize
  41654. */
  41655. int getIndentSize() const noexcept { return indentSize; }
  41656. /** Changes the distance by which each nested level of the tree is indented.
  41657. @see getIndentSize
  41658. */
  41659. void setIndentSize (int newIndentSize);
  41660. /** Searches the tree for an item with the specified identifier.
  41661. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  41662. If no such item exists, this will return false. If the item is found, all of its items
  41663. will be automatically opened.
  41664. */
  41665. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  41666. /** Saves the current state of open/closed nodes so it can be restored later.
  41667. This takes a snapshot of which nodes have been explicitly opened or closed,
  41668. and records it as XML. To identify node objects it uses the
  41669. TreeViewItem::getUniqueName() method to create named paths. This
  41670. means that the same state of open/closed nodes can be restored to a
  41671. completely different instance of the tree, as long as it contains nodes
  41672. whose unique names are the same.
  41673. The caller is responsible for deleting the object that is returned.
  41674. @param alsoIncludeScrollPosition if this is true, the state will also
  41675. include information about where the
  41676. tree has been scrolled to vertically,
  41677. so this can also be restored
  41678. @see restoreOpennessState
  41679. */
  41680. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  41681. /** Restores a previously saved arrangement of open/closed nodes.
  41682. This will try to restore a snapshot of the tree's state that was created by
  41683. the getOpennessState() method. If any of the nodes named in the original
  41684. XML aren't present in this tree, they will be ignored.
  41685. @see getOpennessState
  41686. */
  41687. void restoreOpennessState (const XmlElement& newState);
  41688. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  41689. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41690. methods.
  41691. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41692. */
  41693. enum ColourIds
  41694. {
  41695. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  41696. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  41697. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  41698. };
  41699. /** @internal */
  41700. void paint (Graphics& g);
  41701. /** @internal */
  41702. void resized();
  41703. /** @internal */
  41704. bool keyPressed (const KeyPress& key);
  41705. /** @internal */
  41706. void colourChanged();
  41707. /** @internal */
  41708. void enablementChanged();
  41709. /** @internal */
  41710. bool isInterestedInFileDrag (const StringArray& files);
  41711. /** @internal */
  41712. void fileDragEnter (const StringArray& files, int x, int y);
  41713. /** @internal */
  41714. void fileDragMove (const StringArray& files, int x, int y);
  41715. /** @internal */
  41716. void fileDragExit (const StringArray& files);
  41717. /** @internal */
  41718. void filesDropped (const StringArray& files, int x, int y);
  41719. /** @internal */
  41720. bool isInterestedInDragSource (const SourceDetails&);
  41721. /** @internal */
  41722. void itemDragEnter (const SourceDetails&);
  41723. /** @internal */
  41724. void itemDragMove (const SourceDetails&);
  41725. /** @internal */
  41726. void itemDragExit (const SourceDetails&);
  41727. /** @internal */
  41728. void itemDropped (const SourceDetails&);
  41729. private:
  41730. friend class TreeViewItem;
  41731. friend class TreeViewContentComponent;
  41732. class TreeViewport;
  41733. class InsertPointHighlight;
  41734. class TargetGroupHighlight;
  41735. friend class ScopedPointer<TreeViewport>;
  41736. friend class ScopedPointer<InsertPointHighlight>;
  41737. friend class ScopedPointer<TargetGroupHighlight>;
  41738. ScopedPointer<TreeViewport> viewport;
  41739. CriticalSection nodeAlterationLock;
  41740. TreeViewItem* rootItem;
  41741. ScopedPointer<InsertPointHighlight> dragInsertPointHighlight;
  41742. ScopedPointer<TargetGroupHighlight> dragTargetGroupHighlight;
  41743. int indentSize;
  41744. bool defaultOpenness : 1;
  41745. bool needsRecalculating : 1;
  41746. bool rootItemVisible : 1;
  41747. bool multiSelectEnabled : 1;
  41748. bool openCloseButtonsVisible : 1;
  41749. void itemsChanged() noexcept;
  41750. void handleAsyncUpdate();
  41751. void moveSelectedRow (int delta);
  41752. void updateButtonUnderMouse (const MouseEvent& e);
  41753. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) noexcept;
  41754. void hideDragHighlight() noexcept;
  41755. void handleDrag (const StringArray& files, const SourceDetails&);
  41756. void handleDrop (const StringArray& files, const SourceDetails&);
  41757. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  41758. const StringArray& files, const SourceDetails&) const noexcept;
  41759. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeView);
  41760. };
  41761. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  41762. /*** End of inlined file: juce_TreeView.h ***/
  41763. #endif
  41764. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41765. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  41766. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41767. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41768. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  41769. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41770. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41771. /*** Start of inlined file: juce_FileFilter.h ***/
  41772. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  41773. #define __JUCE_FILEFILTER_JUCEHEADER__
  41774. /**
  41775. Interface for deciding which files are suitable for something.
  41776. For example, this is used by DirectoryContentsList to select which files
  41777. go into the list.
  41778. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  41779. */
  41780. class JUCE_API FileFilter
  41781. {
  41782. public:
  41783. /** Creates a filter with the given description.
  41784. The description can be returned later with the getDescription() method.
  41785. */
  41786. FileFilter (const String& filterDescription);
  41787. /** Destructor. */
  41788. virtual ~FileFilter();
  41789. /** Returns the description that the filter was created with. */
  41790. const String& getDescription() const noexcept;
  41791. /** Should return true if this file is suitable for inclusion in whatever context
  41792. the object is being used.
  41793. */
  41794. virtual bool isFileSuitable (const File& file) const = 0;
  41795. /** Should return true if this directory is suitable for inclusion in whatever context
  41796. the object is being used.
  41797. */
  41798. virtual bool isDirectorySuitable (const File& file) const = 0;
  41799. protected:
  41800. String description;
  41801. };
  41802. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  41803. /*** End of inlined file: juce_FileFilter.h ***/
  41804. /**
  41805. A class to asynchronously scan for details about the files in a directory.
  41806. This keeps a list of files and some information about them, using a background
  41807. thread to scan for more files. As files are found, it broadcasts change messages
  41808. to tell any listeners.
  41809. @see FileListComponent, FileBrowserComponent
  41810. */
  41811. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  41812. public TimeSliceClient
  41813. {
  41814. public:
  41815. /** Creates a directory list.
  41816. To set the directory it should point to, use setDirectory(), which will
  41817. also start it scanning for files on the background thread.
  41818. When the background thread finds and adds new files to this list, the
  41819. ChangeBroadcaster class will send a change message, so you can register
  41820. listeners and update them when the list changes.
  41821. @param fileFilter an optional filter to select which files are
  41822. included in the list. If this is 0, then all files
  41823. and directories are included. Make sure that the
  41824. filter doesn't get deleted during the lifetime of this
  41825. object
  41826. @param threadToUse a thread object that this list can use
  41827. to scan for files as a background task. Make sure
  41828. that the thread you give it has been started, or you
  41829. won't get any files!
  41830. */
  41831. DirectoryContentsList (const FileFilter* fileFilter,
  41832. TimeSliceThread& threadToUse);
  41833. /** Destructor. */
  41834. ~DirectoryContentsList();
  41835. /** Sets the directory to look in for files.
  41836. If the directory that's passed in is different to the current one, this will
  41837. also start the background thread scanning it for files.
  41838. */
  41839. void setDirectory (const File& directory,
  41840. bool includeDirectories,
  41841. bool includeFiles);
  41842. /** Returns the directory that's currently being used. */
  41843. const File& getDirectory() const;
  41844. /** Clears the list, and stops the thread scanning for files. */
  41845. void clear();
  41846. /** Clears the list and restarts scanning the directory for files. */
  41847. void refresh();
  41848. /** True if the background thread hasn't yet finished scanning for files. */
  41849. bool isStillLoading() const;
  41850. /** Tells the list whether or not to ignore hidden files.
  41851. By default these are ignored.
  41852. */
  41853. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  41854. /** Returns true if hidden files are ignored.
  41855. @see setIgnoresHiddenFiles
  41856. */
  41857. bool ignoresHiddenFiles() const;
  41858. /** Contains cached information about one of the files in a DirectoryContentsList.
  41859. */
  41860. struct FileInfo
  41861. {
  41862. /** The filename.
  41863. This isn't a full pathname, it's just the last part of the path, same as you'd
  41864. get from File::getFileName().
  41865. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  41866. */
  41867. String filename;
  41868. /** File size in bytes. */
  41869. int64 fileSize;
  41870. /** File modification time.
  41871. As supplied by File::getLastModificationTime().
  41872. */
  41873. Time modificationTime;
  41874. /** File creation time.
  41875. As supplied by File::getCreationTime().
  41876. */
  41877. Time creationTime;
  41878. /** True if the file is a directory. */
  41879. bool isDirectory;
  41880. /** True if the file is read-only. */
  41881. bool isReadOnly;
  41882. };
  41883. /** Returns the number of files currently available in the list.
  41884. The info about one of these files can be retrieved with getFileInfo() or
  41885. getFile().
  41886. Obviously as the background thread runs and scans the directory for files, this
  41887. number will change.
  41888. @see getFileInfo, getFile
  41889. */
  41890. int getNumFiles() const;
  41891. /** Returns the cached information about one of the files in the list.
  41892. If the index is in-range, this will return true and will copy the file's details
  41893. to the structure that is passed-in.
  41894. If it returns false, then the index wasn't in range, and the structure won't
  41895. be affected.
  41896. @see getNumFiles, getFile
  41897. */
  41898. bool getFileInfo (int index, FileInfo& resultInfo) const;
  41899. /** Returns one of the files in the list.
  41900. @param index should be less than getNumFiles(). If this is out-of-range, the
  41901. return value will be File::nonexistent
  41902. @see getNumFiles, getFileInfo
  41903. */
  41904. const File getFile (int index) const;
  41905. /** Returns the file filter being used.
  41906. The filter is specified in the constructor.
  41907. */
  41908. const FileFilter* getFilter() const { return fileFilter; }
  41909. /** @internal */
  41910. int useTimeSlice();
  41911. /** @internal */
  41912. TimeSliceThread& getTimeSliceThread() { return thread; }
  41913. /** @internal */
  41914. static int compareElements (const DirectoryContentsList::FileInfo* first,
  41915. const DirectoryContentsList::FileInfo* second);
  41916. private:
  41917. File root;
  41918. const FileFilter* fileFilter;
  41919. TimeSliceThread& thread;
  41920. int fileTypeFlags;
  41921. CriticalSection fileListLock;
  41922. OwnedArray <FileInfo> files;
  41923. ScopedPointer <DirectoryIterator> fileFindHandle;
  41924. bool volatile shouldStop;
  41925. void changed();
  41926. bool checkNextFile (bool& hasChanged);
  41927. bool addFile (const File& file, bool isDir,
  41928. const int64 fileSize, const Time& modTime,
  41929. const Time& creationTime, bool isReadOnly);
  41930. void setTypeFlags (int newFlags);
  41931. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsList);
  41932. };
  41933. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41934. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  41935. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  41936. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41937. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41938. /**
  41939. A listener for user selection events in a file browser.
  41940. This is used by a FileBrowserComponent or FileListComponent.
  41941. */
  41942. class JUCE_API FileBrowserListener
  41943. {
  41944. public:
  41945. /** Destructor. */
  41946. virtual ~FileBrowserListener();
  41947. /** Callback when the user selects a different file in the browser. */
  41948. virtual void selectionChanged() = 0;
  41949. /** Callback when the user clicks on a file in the browser. */
  41950. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  41951. /** Callback when the user double-clicks on a file in the browser. */
  41952. virtual void fileDoubleClicked (const File& file) = 0;
  41953. };
  41954. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41955. /*** End of inlined file: juce_FileBrowserListener.h ***/
  41956. /**
  41957. A base class for components that display a list of the files in a directory.
  41958. @see DirectoryContentsList
  41959. */
  41960. class JUCE_API DirectoryContentsDisplayComponent
  41961. {
  41962. public:
  41963. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  41964. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  41965. /** Destructor. */
  41966. virtual ~DirectoryContentsDisplayComponent();
  41967. /** Returns the number of files the user has got selected.
  41968. @see getSelectedFile
  41969. */
  41970. virtual int getNumSelectedFiles() const = 0;
  41971. /** Returns one of the files that the user has currently selected.
  41972. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  41973. @see getNumSelectedFiles
  41974. */
  41975. virtual const File getSelectedFile (int index) const = 0;
  41976. /** Deselects any selected files. */
  41977. virtual void deselectAllFiles() = 0;
  41978. /** Scrolls this view to the top. */
  41979. virtual void scrollToTop() = 0;
  41980. /** Adds a listener to be told when files are selected or clicked.
  41981. @see removeListener
  41982. */
  41983. void addListener (FileBrowserListener* listener);
  41984. /** Removes a listener.
  41985. @see addListener
  41986. */
  41987. void removeListener (FileBrowserListener* listener);
  41988. /** A set of colour IDs to use to change the colour of various aspects of the list.
  41989. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41990. methods.
  41991. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41992. */
  41993. enum ColourIds
  41994. {
  41995. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  41996. textColourId = 0x1000541, /**< The colour for the text. */
  41997. };
  41998. /** @internal */
  41999. void sendSelectionChangeMessage();
  42000. /** @internal */
  42001. void sendDoubleClickMessage (const File& file);
  42002. /** @internal */
  42003. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  42004. protected:
  42005. DirectoryContentsList& fileList;
  42006. ListenerList <FileBrowserListener> listeners;
  42007. private:
  42008. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsDisplayComponent);
  42009. };
  42010. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  42011. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  42012. #endif
  42013. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  42014. #endif
  42015. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42016. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  42017. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42018. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42019. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  42020. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  42021. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  42022. /**
  42023. Base class for components that live inside a file chooser dialog box and
  42024. show previews of the files that get selected.
  42025. One of these allows special extra information to be displayed for files
  42026. in a dialog box as the user selects them. Each time the current file or
  42027. directory is changed, the selectedFileChanged() method will be called
  42028. to allow it to update itself appropriately.
  42029. @see FileChooser, ImagePreviewComponent
  42030. */
  42031. class JUCE_API FilePreviewComponent : public Component
  42032. {
  42033. public:
  42034. /** Creates a FilePreviewComponent. */
  42035. FilePreviewComponent();
  42036. /** Destructor. */
  42037. ~FilePreviewComponent();
  42038. /** Called to indicate that the user's currently selected file has changed.
  42039. @param newSelectedFile the newly selected file or directory, which may be
  42040. File::nonexistent if none is selected.
  42041. */
  42042. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  42043. private:
  42044. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilePreviewComponent);
  42045. };
  42046. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  42047. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  42048. /**
  42049. A component for browsing and selecting a file or directory to open or save.
  42050. This contains a FileListComponent and adds various boxes and controls for
  42051. navigating and selecting a file. It can work in different modes so that it can
  42052. be used for loading or saving a file, or for choosing a directory.
  42053. @see FileChooserDialogBox, FileChooser, FileListComponent
  42054. */
  42055. class JUCE_API FileBrowserComponent : public Component,
  42056. public ChangeBroadcaster,
  42057. private FileBrowserListener,
  42058. private TextEditorListener,
  42059. private ButtonListener,
  42060. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  42061. private FileFilter
  42062. {
  42063. public:
  42064. /** Various options for the browser.
  42065. A combination of these is passed into the FileBrowserComponent constructor.
  42066. */
  42067. enum FileChooserFlags
  42068. {
  42069. openMode = 1, /**< specifies that the component should allow the user to
  42070. choose an existing file with the intention of opening it. */
  42071. saveMode = 2, /**< specifies that the component should allow the user to specify
  42072. the name of a file that will be used to save something. */
  42073. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  42074. conjunction with canSelectDirectories). */
  42075. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  42076. conjuction with canSelectFiles). */
  42077. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  42078. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  42079. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  42080. };
  42081. /** Creates a FileBrowserComponent.
  42082. @param flags A combination of flags from the FileChooserFlags enumeration,
  42083. used to specify the component's behaviour. The flags must contain
  42084. either openMode or saveMode, and canSelectFiles and/or
  42085. canSelectDirectories.
  42086. @param initialFileOrDirectory The file or directory that should be selected when
  42087. the component begins. If this is File::nonexistent,
  42088. a default directory will be chosen.
  42089. @param fileFilter an optional filter to use to determine which files
  42090. are shown. If this is 0 then all files are displayed. Note
  42091. that a pointer is kept internally to this object, so
  42092. make sure that it is not deleted before the browser object
  42093. is deleted.
  42094. @param previewComp an optional preview component that will be used to
  42095. show previews of files that the user selects
  42096. */
  42097. FileBrowserComponent (int flags,
  42098. const File& initialFileOrDirectory,
  42099. const FileFilter* fileFilter,
  42100. FilePreviewComponent* previewComp);
  42101. /** Destructor. */
  42102. ~FileBrowserComponent();
  42103. /** Returns the number of files that the user has got selected.
  42104. If multiple select isn't active, this will only be 0 or 1. To get the complete
  42105. list of files they've chosen, pass an index to getCurrentFile().
  42106. */
  42107. int getNumSelectedFiles() const noexcept;
  42108. /** Returns one of the files that the user has chosen.
  42109. If the box has multi-select enabled, the index lets you specify which of the files
  42110. to get - see getNumSelectedFiles() to find out how many files were chosen.
  42111. @see getHighlightedFile
  42112. */
  42113. const File getSelectedFile (int index) const noexcept;
  42114. /** Deselects any files that are currently selected.
  42115. */
  42116. void deselectAllFiles();
  42117. /** Returns true if the currently selected file(s) are usable.
  42118. This can be used to decide whether the user can press "ok" for the
  42119. current file. What it does depends on the mode, so for example in an "open"
  42120. mode, this only returns true if a file has been selected and if it exists.
  42121. In a "save" mode, a non-existent file would also be valid.
  42122. */
  42123. bool currentFileIsValid() const;
  42124. /** This returns the last item in the view that the user has highlighted.
  42125. This may be different from getCurrentFile(), which returns the value
  42126. that is shown in the filename box, and if there are multiple selections,
  42127. this will only return one of them.
  42128. @see getSelectedFile
  42129. */
  42130. const File getHighlightedFile() const noexcept;
  42131. /** Returns the directory whose contents are currently being shown in the listbox. */
  42132. const File getRoot() const;
  42133. /** Changes the directory that's being shown in the listbox. */
  42134. void setRoot (const File& newRootDirectory);
  42135. /** Equivalent to pressing the "up" button to browse the parent directory. */
  42136. void goUp();
  42137. /** Refreshes the directory that's currently being listed. */
  42138. void refresh();
  42139. /** Changes the filter that's being used to sift the files. */
  42140. void setFileFilter (const FileFilter* newFileFilter);
  42141. /** Returns a verb to describe what should happen when the file is accepted.
  42142. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  42143. mode, it'll be "Save", etc.
  42144. */
  42145. virtual const String getActionVerb() const;
  42146. /** Returns true if the saveMode flag was set when this component was created.
  42147. */
  42148. bool isSaveMode() const noexcept;
  42149. /** Adds a listener to be told when the user selects and clicks on files.
  42150. @see removeListener
  42151. */
  42152. void addListener (FileBrowserListener* listener);
  42153. /** Removes a listener.
  42154. @see addListener
  42155. */
  42156. void removeListener (FileBrowserListener* listener);
  42157. /** @internal */
  42158. void resized();
  42159. /** @internal */
  42160. void buttonClicked (Button* b);
  42161. /** @internal */
  42162. void comboBoxChanged (ComboBox*);
  42163. /** @internal */
  42164. void textEditorTextChanged (TextEditor& editor);
  42165. /** @internal */
  42166. void textEditorReturnKeyPressed (TextEditor& editor);
  42167. /** @internal */
  42168. void textEditorEscapeKeyPressed (TextEditor& editor);
  42169. /** @internal */
  42170. void textEditorFocusLost (TextEditor& editor);
  42171. /** @internal */
  42172. bool keyPressed (const KeyPress& key);
  42173. /** @internal */
  42174. void selectionChanged();
  42175. /** @internal */
  42176. void fileClicked (const File& f, const MouseEvent& e);
  42177. /** @internal */
  42178. void fileDoubleClicked (const File& f);
  42179. /** @internal */
  42180. bool isFileSuitable (const File& file) const;
  42181. /** @internal */
  42182. bool isDirectorySuitable (const File&) const;
  42183. /** @internal */
  42184. FilePreviewComponent* getPreviewComponent() const noexcept;
  42185. protected:
  42186. /** Returns a list of names and paths for the default places the user might want to look.
  42187. Use an empty string to indicate a section break.
  42188. */
  42189. virtual void getRoots (StringArray& rootNames, StringArray& rootPaths);
  42190. private:
  42191. ScopedPointer <DirectoryContentsList> fileList;
  42192. const FileFilter* fileFilter;
  42193. int flags;
  42194. File currentRoot;
  42195. Array<File> chosenFiles;
  42196. ListenerList <FileBrowserListener> listeners;
  42197. ScopedPointer<DirectoryContentsDisplayComponent> fileListComponent;
  42198. FilePreviewComponent* previewComp;
  42199. ComboBox currentPathBox;
  42200. TextEditor filenameBox;
  42201. Label fileLabel;
  42202. ScopedPointer<Button> goUpButton;
  42203. TimeSliceThread thread;
  42204. void sendListenerChangeMessage();
  42205. bool isFileOrDirSuitable (const File& f) const;
  42206. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBrowserComponent);
  42207. };
  42208. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42209. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  42210. #endif
  42211. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  42212. #endif
  42213. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  42214. /*** Start of inlined file: juce_FileChooser.h ***/
  42215. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  42216. #define __JUCE_FILECHOOSER_JUCEHEADER__
  42217. /**
  42218. Creates a dialog box to choose a file or directory to load or save.
  42219. To use a FileChooser:
  42220. - create one (as a local stack variable is the neatest way)
  42221. - call one of its browseFor.. methods
  42222. - if this returns true, the user has selected a file, so you can retrieve it
  42223. with the getResult() method.
  42224. e.g. @code
  42225. void loadMooseFile()
  42226. {
  42227. FileChooser myChooser ("Please select the moose you want to load...",
  42228. File::getSpecialLocation (File::userHomeDirectory),
  42229. "*.moose");
  42230. if (myChooser.browseForFileToOpen())
  42231. {
  42232. File mooseFile (myChooser.getResult());
  42233. loadMoose (mooseFile);
  42234. }
  42235. }
  42236. @endcode
  42237. */
  42238. class JUCE_API FileChooser
  42239. {
  42240. public:
  42241. /** Creates a FileChooser.
  42242. After creating one of these, use one of the browseFor... methods to display it.
  42243. @param dialogBoxTitle a text string to display in the dialog box to
  42244. tell the user what's going on
  42245. @param initialFileOrDirectory the file or directory that should be selected when
  42246. the dialog box opens. If this parameter is set to
  42247. File::nonexistent, a sensible default directory
  42248. will be used instead.
  42249. @param filePatternsAllowed a set of file patterns to specify which files can be
  42250. selected - each pattern should be separated by a
  42251. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  42252. empty string means that all files are allowed
  42253. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  42254. possible; if false, then a Juce-based browser dialog
  42255. box will always be used
  42256. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  42257. */
  42258. FileChooser (const String& dialogBoxTitle,
  42259. const File& initialFileOrDirectory = File::nonexistent,
  42260. const String& filePatternsAllowed = String::empty,
  42261. bool useOSNativeDialogBox = true);
  42262. /** Destructor. */
  42263. ~FileChooser();
  42264. /** Shows a dialog box to choose a file to open.
  42265. This will display the dialog box modally, using an "open file" mode, so that
  42266. it won't allow non-existent files or directories to be chosen.
  42267. @param previewComponent an optional component to display inside the dialog
  42268. box to show special info about the files that the user
  42269. is browsing. The component will not be deleted by this
  42270. object, so the caller must take care of it.
  42271. @returns true if the user selected a file, in which case, use the getResult()
  42272. method to find out what it was. Returns false if they cancelled instead.
  42273. @see browseForFileToSave, browseForDirectory
  42274. */
  42275. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  42276. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  42277. The files that are returned can be obtained by calling getResults(). See
  42278. browseForFileToOpen() for more info about the behaviour of this method.
  42279. */
  42280. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  42281. /** Shows a dialog box to choose a file to save.
  42282. This will display the dialog box modally, using an "save file" mode, so it
  42283. will allow non-existent files to be chosen, but not directories.
  42284. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  42285. the user if they're sure they want to overwrite a file that already
  42286. exists
  42287. @returns true if the user chose a file and pressed 'ok', in which case, use
  42288. the getResult() method to find out what the file was. Returns false
  42289. if they cancelled instead.
  42290. @see browseForFileToOpen, browseForDirectory
  42291. */
  42292. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  42293. /** Shows a dialog box to choose a directory.
  42294. This will display the dialog box modally, using an "open directory" mode, so it
  42295. will only allow directories to be returned, not files.
  42296. @returns true if the user chose a directory and pressed 'ok', in which case, use
  42297. the getResult() method to find out what they chose. Returns false
  42298. if they cancelled instead.
  42299. @see browseForFileToOpen, browseForFileToSave
  42300. */
  42301. bool browseForDirectory();
  42302. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  42303. The files that are returned can be obtained by calling getResults(). See
  42304. browseForFileToOpen() for more info about the behaviour of this method.
  42305. */
  42306. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  42307. /** Returns the last file that was chosen by one of the browseFor methods.
  42308. After calling the appropriate browseFor... method, this method lets you
  42309. find out what file or directory they chose.
  42310. Note that the file returned is only valid if the browse method returned true (i.e.
  42311. if the user pressed 'ok' rather than cancelling).
  42312. If you're using a multiple-file select, then use the getResults() method instead,
  42313. to obtain the list of all files chosen.
  42314. @see getResults
  42315. */
  42316. const File getResult() const;
  42317. /** Returns a list of all the files that were chosen during the last call to a
  42318. browse method.
  42319. This array may be empty if no files were chosen, or can contain multiple entries
  42320. if multiple files were chosen.
  42321. @see getResult
  42322. */
  42323. const Array<File>& getResults() const;
  42324. private:
  42325. String title, filters;
  42326. File startingFile;
  42327. Array<File> results;
  42328. bool useNativeDialogBox;
  42329. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  42330. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  42331. FilePreviewComponent* previewComponent);
  42332. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  42333. const String& filters, bool selectsDirectories, bool selectsFiles,
  42334. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  42335. FilePreviewComponent* previewComponent);
  42336. JUCE_LEAK_DETECTOR (FileChooser);
  42337. };
  42338. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  42339. /*** End of inlined file: juce_FileChooser.h ***/
  42340. #endif
  42341. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42342. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  42343. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42344. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42345. /*** Start of inlined file: juce_ResizableWindow.h ***/
  42346. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42347. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42348. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  42349. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42350. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42351. /*** Start of inlined file: juce_DropShadower.h ***/
  42352. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  42353. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  42354. /**
  42355. Adds a drop-shadow to a component.
  42356. This object creates and manages a set of components which sit around a
  42357. component, creating a gaussian shadow around it. The components will track
  42358. the position of the component and if it's brought to the front they'll also
  42359. follow this.
  42360. For desktop windows you don't need to use this class directly - just
  42361. set the Component::windowHasDropShadow flag when calling
  42362. Component::addToDesktop(), and the system will create one of these if it's
  42363. needed (which it obviously isn't on the Mac, for example).
  42364. */
  42365. class JUCE_API DropShadower : public ComponentListener
  42366. {
  42367. public:
  42368. /** Creates a DropShadower.
  42369. @param alpha the opacity of the shadows, from 0 to 1.0
  42370. @param xOffset the horizontal displacement of the shadow, in pixels
  42371. @param yOffset the vertical displacement of the shadow, in pixels
  42372. @param blurRadius the radius of the blur to use for creating the shadow
  42373. */
  42374. DropShadower (float alpha = 0.5f,
  42375. int xOffset = 1,
  42376. int yOffset = 5,
  42377. float blurRadius = 10.0f);
  42378. /** Destructor. */
  42379. virtual ~DropShadower();
  42380. /** Attaches the DropShadower to the component you want to shadow. */
  42381. void setOwner (Component* componentToFollow);
  42382. /** @internal */
  42383. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  42384. /** @internal */
  42385. void componentBroughtToFront (Component& component);
  42386. /** @internal */
  42387. void componentParentHierarchyChanged (Component& component);
  42388. /** @internal */
  42389. void componentVisibilityChanged (Component& component);
  42390. private:
  42391. Component* owner;
  42392. OwnedArray<Component> shadowWindows;
  42393. Image shadowImageSections[12];
  42394. const int xOffset, yOffset;
  42395. const float alpha, blurRadius;
  42396. bool reentrant;
  42397. void updateShadows();
  42398. void setShadowImage (const Image& src, int num, int w, int h, int sx, int sy);
  42399. void bringShadowWindowsToFront();
  42400. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DropShadower);
  42401. };
  42402. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  42403. /*** End of inlined file: juce_DropShadower.h ***/
  42404. /**
  42405. A base class for top-level windows.
  42406. This class is used for components that are considered a major part of your
  42407. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  42408. etc. Things like menus that pop up briefly aren't derived from it.
  42409. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  42410. could itself be the child of another component.
  42411. The class manages a list of all instances of top-level windows that are in use,
  42412. and each one is also given the concept of being "active". The active window is
  42413. one that is actively being used by the user. This isn't quite the same as the
  42414. component with the keyboard focus, because there may be a popup menu or other
  42415. temporary window which gets keyboard focus while the active top level window is
  42416. unchanged.
  42417. A top-level window also has an optional drop-shadow.
  42418. @see ResizableWindow, DocumentWindow, DialogWindow
  42419. */
  42420. class JUCE_API TopLevelWindow : public Component
  42421. {
  42422. public:
  42423. /** Creates a TopLevelWindow.
  42424. @param name the name to give the component
  42425. @param addToDesktop if true, the window will be automatically added to the
  42426. desktop; if false, you can use it as a child component
  42427. */
  42428. TopLevelWindow (const String& name, bool addToDesktop);
  42429. /** Destructor. */
  42430. ~TopLevelWindow();
  42431. /** True if this is currently the TopLevelWindow that is actively being used.
  42432. This isn't quite the same as having keyboard focus, because the focus may be
  42433. on a child component or a temporary pop-up menu, etc, while this window is
  42434. still considered to be active.
  42435. @see activeWindowStatusChanged
  42436. */
  42437. bool isActiveWindow() const noexcept { return windowIsActive_; }
  42438. /** This will set the bounds of the window so that it's centred in front of another
  42439. window.
  42440. If your app has a few windows open and want to pop up a dialog box for one of
  42441. them, you can use this to show it in front of the relevent parent window, which
  42442. is a bit neater than just having it appear in the middle of the screen.
  42443. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  42444. be used instead. If no window is focused, it'll just default to the middle of the
  42445. screen.
  42446. */
  42447. void centreAroundComponent (Component* componentToCentreAround,
  42448. int width, int height);
  42449. /** Turns the drop-shadow on and off. */
  42450. void setDropShadowEnabled (bool useShadow);
  42451. /** Sets whether an OS-native title bar will be used, or a Juce one.
  42452. @see isUsingNativeTitleBar
  42453. */
  42454. void setUsingNativeTitleBar (bool useNativeTitleBar);
  42455. /** Returns true if the window is currently using an OS-native title bar.
  42456. @see setUsingNativeTitleBar
  42457. */
  42458. bool isUsingNativeTitleBar() const noexcept { return useNativeTitleBar && isOnDesktop(); }
  42459. /** Returns the number of TopLevelWindow objects currently in use.
  42460. @see getTopLevelWindow
  42461. */
  42462. static int getNumTopLevelWindows() noexcept;
  42463. /** Returns one of the TopLevelWindow objects currently in use.
  42464. The index is 0 to (getNumTopLevelWindows() - 1).
  42465. */
  42466. static TopLevelWindow* getTopLevelWindow (int index) noexcept;
  42467. /** Returns the currently-active top level window.
  42468. There might not be one, of course, so this can return 0.
  42469. */
  42470. static TopLevelWindow* getActiveTopLevelWindow() noexcept;
  42471. /** @internal */
  42472. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = nullptr);
  42473. protected:
  42474. /** This callback happens when this window becomes active or inactive.
  42475. @see isActiveWindow
  42476. */
  42477. virtual void activeWindowStatusChanged();
  42478. /** @internal */
  42479. void focusOfChildComponentChanged (FocusChangeType cause);
  42480. /** @internal */
  42481. void parentHierarchyChanged();
  42482. /** @internal */
  42483. virtual int getDesktopWindowStyleFlags() const;
  42484. /** @internal */
  42485. void recreateDesktopWindow();
  42486. /** @internal */
  42487. void visibilityChanged();
  42488. private:
  42489. friend class TopLevelWindowManager;
  42490. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  42491. ScopedPointer <DropShadower> shadower;
  42492. void setWindowActive (bool isNowActive);
  42493. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TopLevelWindow);
  42494. };
  42495. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42496. /*** End of inlined file: juce_TopLevelWindow.h ***/
  42497. /*** Start of inlined file: juce_ComponentDragger.h ***/
  42498. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  42499. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  42500. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  42501. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  42502. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  42503. /**
  42504. A class that imposes restrictions on a Component's size or position.
  42505. This is used by classes such as ResizableCornerComponent,
  42506. ResizableBorderComponent and ResizableWindow.
  42507. The base class can impose some basic size and position limits, but you can
  42508. also subclass this for custom uses.
  42509. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  42510. */
  42511. class JUCE_API ComponentBoundsConstrainer
  42512. {
  42513. public:
  42514. /** When first created, the object will not impose any restrictions on the components. */
  42515. ComponentBoundsConstrainer() noexcept;
  42516. /** Destructor. */
  42517. virtual ~ComponentBoundsConstrainer();
  42518. /** Imposes a minimum width limit. */
  42519. void setMinimumWidth (int minimumWidth) noexcept;
  42520. /** Returns the current minimum width. */
  42521. int getMinimumWidth() const noexcept { return minW; }
  42522. /** Imposes a maximum width limit. */
  42523. void setMaximumWidth (int maximumWidth) noexcept;
  42524. /** Returns the current maximum width. */
  42525. int getMaximumWidth() const noexcept { return maxW; }
  42526. /** Imposes a minimum height limit. */
  42527. void setMinimumHeight (int minimumHeight) noexcept;
  42528. /** Returns the current minimum height. */
  42529. int getMinimumHeight() const noexcept { return minH; }
  42530. /** Imposes a maximum height limit. */
  42531. void setMaximumHeight (int maximumHeight) noexcept;
  42532. /** Returns the current maximum height. */
  42533. int getMaximumHeight() const noexcept { return maxH; }
  42534. /** Imposes a minimum width and height limit. */
  42535. void setMinimumSize (int minimumWidth,
  42536. int minimumHeight) noexcept;
  42537. /** Imposes a maximum width and height limit. */
  42538. void setMaximumSize (int maximumWidth,
  42539. int maximumHeight) noexcept;
  42540. /** Set all the maximum and minimum dimensions. */
  42541. void setSizeLimits (int minimumWidth,
  42542. int minimumHeight,
  42543. int maximumWidth,
  42544. int maximumHeight) noexcept;
  42545. /** Sets the amount by which the component is allowed to go off-screen.
  42546. The values indicate how many pixels must remain on-screen when dragged off
  42547. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  42548. when the component goes off the top of the screen, its y-position will be
  42549. clipped so that there are always at least 10 pixels on-screen. In other words,
  42550. the lowest y-position it can take would be (10 - the component's height).
  42551. If you pass 0 or less for one of these amounts, the component is allowed
  42552. to move beyond that edge completely, with no restrictions at all.
  42553. If you pass a very large number (i.e. larger that the dimensions of the
  42554. component itself), then the component won't be allowed to overlap that
  42555. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  42556. the component will bump into the left side of the screen and go no further.
  42557. */
  42558. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  42559. int minimumWhenOffTheLeft,
  42560. int minimumWhenOffTheBottom,
  42561. int minimumWhenOffTheRight) noexcept;
  42562. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  42563. int getMinimumWhenOffTheTop() const noexcept { return minOffTop; }
  42564. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  42565. int getMinimumWhenOffTheLeft() const noexcept { return minOffLeft; }
  42566. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  42567. int getMinimumWhenOffTheBottom() const noexcept { return minOffBottom; }
  42568. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  42569. int getMinimumWhenOffTheRight() const noexcept { return minOffRight; }
  42570. /** Specifies a width-to-height ratio that the resizer should always maintain.
  42571. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  42572. will always be maintained as this multiple of the height.
  42573. @see setResizeLimits
  42574. */
  42575. void setFixedAspectRatio (double widthOverHeight) noexcept;
  42576. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  42577. If no aspect ratio is being enforced, this will return 0.
  42578. */
  42579. double getFixedAspectRatio() const noexcept;
  42580. /** This callback changes the given co-ordinates to impose whatever the current
  42581. constraints are set to be.
  42582. @param bounds the target position that should be examined and adjusted
  42583. @param previousBounds the component's current size
  42584. @param limits the region in which the component can be positioned
  42585. @param isStretchingTop whether the top edge of the component is being resized
  42586. @param isStretchingLeft whether the left edge of the component is being resized
  42587. @param isStretchingBottom whether the bottom edge of the component is being resized
  42588. @param isStretchingRight whether the right edge of the component is being resized
  42589. */
  42590. virtual void checkBounds (Rectangle<int>& bounds,
  42591. const Rectangle<int>& previousBounds,
  42592. const Rectangle<int>& limits,
  42593. bool isStretchingTop,
  42594. bool isStretchingLeft,
  42595. bool isStretchingBottom,
  42596. bool isStretchingRight);
  42597. /** This callback happens when the resizer is about to start dragging. */
  42598. virtual void resizeStart();
  42599. /** This callback happens when the resizer has finished dragging. */
  42600. virtual void resizeEnd();
  42601. /** Checks the given bounds, and then sets the component to the corrected size. */
  42602. void setBoundsForComponent (Component* component,
  42603. const Rectangle<int>& bounds,
  42604. bool isStretchingTop,
  42605. bool isStretchingLeft,
  42606. bool isStretchingBottom,
  42607. bool isStretchingRight);
  42608. /** Performs a check on the current size of a component, and moves or resizes
  42609. it if it fails the constraints.
  42610. */
  42611. void checkComponentBounds (Component* component);
  42612. /** Called by setBoundsForComponent() to apply a new constrained size to a
  42613. component.
  42614. By default this just calls setBounds(), but it virtual in case it's needed for
  42615. extremely cunning purposes.
  42616. */
  42617. virtual void applyBoundsToComponent (Component* component,
  42618. const Rectangle<int>& bounds);
  42619. private:
  42620. int minW, maxW, minH, maxH;
  42621. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  42622. double aspectRatio;
  42623. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBoundsConstrainer);
  42624. };
  42625. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  42626. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  42627. /**
  42628. An object to take care of the logic for dragging components around with the mouse.
  42629. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  42630. then in your mouseDrag() callback, call dragComponent().
  42631. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  42632. to limit the component's position and keep it on-screen.
  42633. e.g. @code
  42634. class MyDraggableComp
  42635. {
  42636. ComponentDragger myDragger;
  42637. void mouseDown (const MouseEvent& e)
  42638. {
  42639. myDragger.startDraggingComponent (this, e);
  42640. }
  42641. void mouseDrag (const MouseEvent& e)
  42642. {
  42643. myDragger.dragComponent (this, e, nullptr);
  42644. }
  42645. };
  42646. @endcode
  42647. */
  42648. class JUCE_API ComponentDragger
  42649. {
  42650. public:
  42651. /** Creates a ComponentDragger. */
  42652. ComponentDragger();
  42653. /** Destructor. */
  42654. virtual ~ComponentDragger();
  42655. /** Call this from your component's mouseDown() method, to prepare for dragging.
  42656. @param componentToDrag the component that you want to drag
  42657. @param e the mouse event that is triggering the drag
  42658. @see dragComponent
  42659. */
  42660. void startDraggingComponent (Component* componentToDrag,
  42661. const MouseEvent& e);
  42662. /** Call this from your mouseDrag() callback to move the component.
  42663. This will move the component, but will first check the validity of the
  42664. component's new position using the checkPosition() method, which you
  42665. can override if you need to enforce special positioning limits on the
  42666. component.
  42667. @param componentToDrag the component that you want to drag
  42668. @param e the current mouse-drag event
  42669. @param constrainer an optional constrainer object that should be used
  42670. to apply limits to the component's position. Pass
  42671. null if you don't want to contrain the movement.
  42672. @see startDraggingComponent
  42673. */
  42674. void dragComponent (Component* componentToDrag,
  42675. const MouseEvent& e,
  42676. ComponentBoundsConstrainer* constrainer);
  42677. private:
  42678. Point<int> mouseDownWithinTarget;
  42679. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentDragger);
  42680. };
  42681. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  42682. /*** End of inlined file: juce_ComponentDragger.h ***/
  42683. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  42684. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  42685. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  42686. /**
  42687. A component that resizes its parent component when dragged.
  42688. This component forms a frame around the edge of a component, allowing it to
  42689. be dragged by the edges or corners to resize it - like the way windows are
  42690. resized in MSWindows or Linux.
  42691. To use it, just add it to your component, making it fill the entire parent component
  42692. (there's a mouse hit-test that only traps mouse-events which land around the
  42693. edge of the component, so it's even ok to put it on top of any other components
  42694. you're using). Make sure you rescale the resizer component to fill the parent
  42695. each time the parent's size changes.
  42696. @see ResizableCornerComponent
  42697. */
  42698. class JUCE_API ResizableBorderComponent : public Component
  42699. {
  42700. public:
  42701. /** Creates a resizer.
  42702. Pass in the target component which you want to be resized when this one is
  42703. dragged.
  42704. The target component will usually be a parent of the resizer component, but this
  42705. isn't mandatory.
  42706. Remember that when the target component is resized, it'll need to move and
  42707. resize this component to keep it in place, as this won't happen automatically.
  42708. If the constrainer parameter is non-zero, then this object will be used to enforce
  42709. limits on the size and position that the component can be stretched to. Make sure
  42710. that the constrainer isn't deleted while still in use by this object.
  42711. @see ComponentBoundsConstrainer
  42712. */
  42713. ResizableBorderComponent (Component* componentToResize,
  42714. ComponentBoundsConstrainer* constrainer);
  42715. /** Destructor. */
  42716. ~ResizableBorderComponent();
  42717. /** Specifies how many pixels wide the draggable edges of this component are.
  42718. @see getBorderThickness
  42719. */
  42720. void setBorderThickness (const BorderSize<int>& newBorderSize);
  42721. /** Returns the number of pixels wide that the draggable edges of this component are.
  42722. @see setBorderThickness
  42723. */
  42724. const BorderSize<int> getBorderThickness() const;
  42725. /** Represents the different sections of a resizable border, which allow it to
  42726. resized in different ways.
  42727. */
  42728. class Zone
  42729. {
  42730. public:
  42731. enum Zones
  42732. {
  42733. centre = 0,
  42734. left = 1,
  42735. top = 2,
  42736. right = 4,
  42737. bottom = 8
  42738. };
  42739. /** Creates a Zone from a combination of the flags in \enum Zones. */
  42740. explicit Zone (int zoneFlags = 0) noexcept;
  42741. Zone (const Zone& other) noexcept;
  42742. Zone& operator= (const Zone& other) noexcept;
  42743. bool operator== (const Zone& other) const noexcept;
  42744. bool operator!= (const Zone& other) const noexcept;
  42745. /** Given a point within a rectangle with a resizable border, this returns the
  42746. zone that the point lies within.
  42747. */
  42748. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  42749. const BorderSize<int>& border,
  42750. const Point<int>& position);
  42751. /** Returns an appropriate mouse-cursor for this resize zone. */
  42752. const MouseCursor getMouseCursor() const noexcept;
  42753. /** Returns true if dragging this zone will move the enire object without resizing it. */
  42754. bool isDraggingWholeObject() const noexcept { return zone == centre; }
  42755. /** Returns true if dragging this zone will move the object's left edge. */
  42756. bool isDraggingLeftEdge() const noexcept { return (zone & left) != 0; }
  42757. /** Returns true if dragging this zone will move the object's right edge. */
  42758. bool isDraggingRightEdge() const noexcept { return (zone & right) != 0; }
  42759. /** Returns true if dragging this zone will move the object's top edge. */
  42760. bool isDraggingTopEdge() const noexcept { return (zone & top) != 0; }
  42761. /** Returns true if dragging this zone will move the object's bottom edge. */
  42762. bool isDraggingBottomEdge() const noexcept { return (zone & bottom) != 0; }
  42763. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  42764. applies to.
  42765. */
  42766. template <typename ValueType>
  42767. const Rectangle<ValueType> resizeRectangleBy (Rectangle<ValueType> original,
  42768. const Point<ValueType>& distance) const noexcept
  42769. {
  42770. if (isDraggingWholeObject())
  42771. return original + distance;
  42772. if (isDraggingLeftEdge())
  42773. original.setLeft (jmin (original.getRight(), original.getX() + distance.getX()));
  42774. if (isDraggingRightEdge())
  42775. original.setWidth (jmax (ValueType(), original.getWidth() + distance.getX()));
  42776. if (isDraggingTopEdge())
  42777. original.setTop (jmin (original.getBottom(), original.getY() + distance.getY()));
  42778. if (isDraggingBottomEdge())
  42779. original.setHeight (jmax (ValueType(), original.getHeight() + distance.getY()));
  42780. return original;
  42781. }
  42782. /** Returns the raw flags for this zone. */
  42783. int getZoneFlags() const noexcept { return zone; }
  42784. private:
  42785. int zone;
  42786. };
  42787. protected:
  42788. /** @internal */
  42789. void paint (Graphics& g);
  42790. /** @internal */
  42791. void mouseEnter (const MouseEvent& e);
  42792. /** @internal */
  42793. void mouseMove (const MouseEvent& e);
  42794. /** @internal */
  42795. void mouseDown (const MouseEvent& e);
  42796. /** @internal */
  42797. void mouseDrag (const MouseEvent& e);
  42798. /** @internal */
  42799. void mouseUp (const MouseEvent& e);
  42800. /** @internal */
  42801. bool hitTest (int x, int y);
  42802. private:
  42803. WeakReference<Component> component;
  42804. ComponentBoundsConstrainer* constrainer;
  42805. BorderSize<int> borderSize;
  42806. Rectangle<int> originalBounds;
  42807. Zone mouseZone;
  42808. void updateMouseZone (const MouseEvent& e);
  42809. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableBorderComponent);
  42810. };
  42811. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  42812. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  42813. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  42814. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42815. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42816. /** A component that resizes a parent component when dragged.
  42817. This is the small triangular stripey resizer component you get in the bottom-right
  42818. of windows (more commonly on the Mac than Windows). Put one in the corner of
  42819. a larger component and it will automatically resize its parent when it gets dragged
  42820. around.
  42821. @see ResizableFrameComponent
  42822. */
  42823. class JUCE_API ResizableCornerComponent : public Component
  42824. {
  42825. public:
  42826. /** Creates a resizer.
  42827. Pass in the target component which you want to be resized when this one is
  42828. dragged.
  42829. The target component will usually be a parent of the resizer component, but this
  42830. isn't mandatory.
  42831. Remember that when the target component is resized, it'll need to move and
  42832. resize this component to keep it in place, as this won't happen automatically.
  42833. If the constrainer parameter is non-zero, then this object will be used to enforce
  42834. limits on the size and position that the component can be stretched to. Make sure
  42835. that the constrainer isn't deleted while still in use by this object. If you
  42836. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  42837. @see ComponentBoundsConstrainer
  42838. */
  42839. ResizableCornerComponent (Component* componentToResize,
  42840. ComponentBoundsConstrainer* constrainer);
  42841. /** Destructor. */
  42842. ~ResizableCornerComponent();
  42843. protected:
  42844. /** @internal */
  42845. void paint (Graphics& g);
  42846. /** @internal */
  42847. void mouseDown (const MouseEvent& e);
  42848. /** @internal */
  42849. void mouseDrag (const MouseEvent& e);
  42850. /** @internal */
  42851. void mouseUp (const MouseEvent& e);
  42852. /** @internal */
  42853. bool hitTest (int x, int y);
  42854. private:
  42855. WeakReference<Component> component;
  42856. ComponentBoundsConstrainer* constrainer;
  42857. Rectangle<int> originalBounds;
  42858. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableCornerComponent);
  42859. };
  42860. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42861. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  42862. /**
  42863. A base class for top-level windows that can be dragged around and resized.
  42864. To add content to the window, use its setContentOwned() or setContentNonOwned() methods
  42865. to give it a component that will remain positioned inside it (leaving a gap around
  42866. the edges for a border).
  42867. It's not advisable to add child components directly to a ResizableWindow: put them
  42868. inside your content component instead. And overriding methods like resized(), moved(), etc
  42869. is also not recommended - instead override these methods for your content component.
  42870. (If for some obscure reason you do need to override these methods, always remember to
  42871. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  42872. decorations correctly).
  42873. By default resizing isn't enabled - use the setResizable() method to enable it and
  42874. to choose the style of resizing to use.
  42875. @see TopLevelWindow
  42876. */
  42877. class JUCE_API ResizableWindow : public TopLevelWindow
  42878. {
  42879. public:
  42880. /** Creates a ResizableWindow.
  42881. This constructor doesn't specify a background colour, so the LookAndFeel's default
  42882. background colour will be used.
  42883. @param name the name to give the component
  42884. @param addToDesktop if true, the window will be automatically added to the
  42885. desktop; if false, you can use it as a child component
  42886. */
  42887. ResizableWindow (const String& name,
  42888. bool addToDesktop);
  42889. /** Creates a ResizableWindow.
  42890. @param name the name to give the component
  42891. @param backgroundColour the colour to use for filling the window's background.
  42892. @param addToDesktop if true, the window will be automatically added to the
  42893. desktop; if false, you can use it as a child component
  42894. */
  42895. ResizableWindow (const String& name,
  42896. const Colour& backgroundColour,
  42897. bool addToDesktop);
  42898. /** Destructor.
  42899. If a content component has been set with setContentOwned(), it will be deleted.
  42900. */
  42901. ~ResizableWindow();
  42902. /** Returns the colour currently being used for the window's background.
  42903. As a convenience the window will fill itself with this colour, but you
  42904. can override the paint() method if you need more customised behaviour.
  42905. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  42906. @see setBackgroundColour
  42907. */
  42908. const Colour getBackgroundColour() const noexcept;
  42909. /** Changes the colour currently being used for the window's background.
  42910. As a convenience the window will fill itself with this colour, but you
  42911. can override the paint() method if you need more customised behaviour.
  42912. Note that the opaque state of this window is altered by this call to reflect
  42913. the opacity of the colour passed-in. On window systems which can't support
  42914. semi-transparent windows this might cause problems, (though it's unlikely you'll
  42915. be using this class as a base for a semi-transparent component anyway).
  42916. You can also use the ResizableWindow::backgroundColourId colour id to set
  42917. this colour.
  42918. @see getBackgroundColour
  42919. */
  42920. void setBackgroundColour (const Colour& newColour);
  42921. /** Make the window resizable or fixed.
  42922. @param shouldBeResizable whether it's resizable at all
  42923. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  42924. bottom-right; if false, it'll use a ResizableBorderComponent
  42925. around the edge
  42926. @see setResizeLimits, isResizable
  42927. */
  42928. void setResizable (bool shouldBeResizable,
  42929. bool useBottomRightCornerResizer);
  42930. /** True if resizing is enabled.
  42931. @see setResizable
  42932. */
  42933. bool isResizable() const noexcept;
  42934. /** This sets the maximum and minimum sizes for the window.
  42935. If the window's current size is outside these limits, it will be resized to
  42936. make sure it's within them.
  42937. Calling setBounds() on the component will bypass any size checking - it's only when
  42938. the window is being resized by the user that these values are enforced.
  42939. @see setResizable, setFixedAspectRatio
  42940. */
  42941. void setResizeLimits (int newMinimumWidth,
  42942. int newMinimumHeight,
  42943. int newMaximumWidth,
  42944. int newMaximumHeight) noexcept;
  42945. /** Returns the bounds constrainer object that this window is using.
  42946. You can access this to change its properties.
  42947. */
  42948. ComponentBoundsConstrainer* getConstrainer() noexcept { return constrainer; }
  42949. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  42950. A pointer to the object you pass in will be kept, but it won't be deleted
  42951. by this object, so it's the caller's responsiblity to manage it.
  42952. If you pass 0, then no contraints will be placed on the positioning of the window.
  42953. */
  42954. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  42955. /** Calls the window's setBounds method, after first checking these bounds
  42956. with the current constrainer.
  42957. @see setConstrainer
  42958. */
  42959. void setBoundsConstrained (const Rectangle<int>& bounds);
  42960. /** Returns true if the window is currently in full-screen mode.
  42961. @see setFullScreen
  42962. */
  42963. bool isFullScreen() const;
  42964. /** Puts the window into full-screen mode, or restores it to its normal size.
  42965. If true, the window will become full-screen; if false, it will return to the
  42966. last size it was before being made full-screen.
  42967. @see isFullScreen
  42968. */
  42969. void setFullScreen (bool shouldBeFullScreen);
  42970. /** Returns true if the window is currently minimised.
  42971. @see setMinimised
  42972. */
  42973. bool isMinimised() const;
  42974. /** Minimises the window, or restores it to its previous position and size.
  42975. When being un-minimised, it'll return to the last position and size it
  42976. was in before being minimised.
  42977. @see isMinimised
  42978. */
  42979. void setMinimised (bool shouldMinimise);
  42980. /** Returns a string which encodes the window's current size and position.
  42981. This string will encapsulate the window's size, position, and whether it's
  42982. in full-screen mode. It's intended for letting your application save and
  42983. restore a window's position.
  42984. Use the restoreWindowStateFromString() to restore from a saved state.
  42985. @see restoreWindowStateFromString
  42986. */
  42987. const String getWindowStateAsString();
  42988. /** Restores the window to a previously-saved size and position.
  42989. This restores the window's size, positon and full-screen status from an
  42990. string that was previously created with the getWindowStateAsString()
  42991. method.
  42992. @returns false if the string wasn't a valid window state
  42993. @see getWindowStateAsString
  42994. */
  42995. bool restoreWindowStateFromString (const String& previousState);
  42996. /** Returns the current content component.
  42997. This will be the component set by setContentOwned() or setContentNonOwned, or 0 if none
  42998. has yet been specified.
  42999. @see setContentOwned, setContentNonOwned
  43000. */
  43001. Component* getContentComponent() const noexcept { return contentComponent; }
  43002. /** Changes the current content component.
  43003. This sets a component that will be placed in the centre of the ResizableWindow,
  43004. (leaving a space around the edge for the border).
  43005. You should never add components directly to a ResizableWindow (or any of its subclasses)
  43006. with addChildComponent(). Instead, add them to the content component.
  43007. @param newContentComponent the new component to use - this component will be deleted when it's
  43008. no longer needed (i.e. when the window is deleted or a new content
  43009. component is set for it). To set a component that this window will not
  43010. delete, call setContentNonOwned() instead.
  43011. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  43012. such that it always fits around the size of the content component. If false,
  43013. the new content will be resized to fit the current space available.
  43014. */
  43015. void setContentOwned (Component* newContentComponent,
  43016. bool resizeToFitWhenContentChangesSize);
  43017. /** Changes the current content component.
  43018. This sets a component that will be placed in the centre of the ResizableWindow,
  43019. (leaving a space around the edge for the border).
  43020. You should never add components directly to a ResizableWindow (or any of its subclasses)
  43021. with addChildComponent(). Instead, add them to the content component.
  43022. @param newContentComponent the new component to use - this component will NOT be deleted by this
  43023. component, so it's the caller's responsibility to manage its lifetime (it's
  43024. ok to delete it while this window is still using it). To set a content
  43025. component that the window will delete, call setContentOwned() instead.
  43026. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  43027. such that it always fits around the size of the content component. If false,
  43028. the new content will be resized to fit the current space available.
  43029. */
  43030. void setContentNonOwned (Component* newContentComponent,
  43031. bool resizeToFitWhenContentChangesSize);
  43032. /** Removes the current content component.
  43033. If the previous content component was added with setContentOwned(), it will also be deleted. If
  43034. it was added with setContentNonOwned(), it will simply be removed from this component.
  43035. */
  43036. void clearContentComponent();
  43037. /** Changes the window so that the content component ends up with the specified size.
  43038. This is basically a setSize call on the window, but which adds on the borders,
  43039. so you can specify the content component's target size.
  43040. */
  43041. void setContentComponentSize (int width, int height);
  43042. /** Returns the width of the frame to use around the window.
  43043. @see getContentComponentBorder
  43044. */
  43045. virtual const BorderSize<int> getBorderThickness();
  43046. /** Returns the insets to use when positioning the content component.
  43047. @see getBorderThickness
  43048. */
  43049. virtual const BorderSize<int> getContentComponentBorder();
  43050. /** A set of colour IDs to use to change the colour of various aspects of the window.
  43051. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43052. methods.
  43053. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43054. */
  43055. enum ColourIds
  43056. {
  43057. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  43058. };
  43059. /** @deprecated - use setContentOwned() and setContentNonOwned() instead. */
  43060. JUCE_DEPRECATED (void setContentComponent (Component* newContentComponent,
  43061. bool deleteOldOne = true,
  43062. bool resizeToFit = false));
  43063. protected:
  43064. /** @internal */
  43065. void paint (Graphics& g);
  43066. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  43067. void moved();
  43068. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  43069. void resized();
  43070. /** @internal */
  43071. void mouseDown (const MouseEvent& e);
  43072. /** @internal */
  43073. void mouseDrag (const MouseEvent& e);
  43074. /** @internal */
  43075. void lookAndFeelChanged();
  43076. /** @internal */
  43077. void childBoundsChanged (Component* child);
  43078. /** @internal */
  43079. void parentSizeChanged();
  43080. /** @internal */
  43081. void visibilityChanged();
  43082. /** @internal */
  43083. void activeWindowStatusChanged();
  43084. /** @internal */
  43085. int getDesktopWindowStyleFlags() const;
  43086. #if JUCE_DEBUG
  43087. /** Overridden to warn people about adding components directly to this component
  43088. instead of using setContentOwned().
  43089. If you know what you're doing and are sure you really want to add a component, specify
  43090. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  43091. */
  43092. void addChildComponent (Component* child, int zOrder = -1);
  43093. /** Overridden to warn people about adding components directly to this component
  43094. instead of using setContentOwned().
  43095. If you know what you're doing and are sure you really want to add a component, specify
  43096. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  43097. */
  43098. void addAndMakeVisible (Component* child, int zOrder = -1);
  43099. #endif
  43100. ScopedPointer <ResizableCornerComponent> resizableCorner;
  43101. ScopedPointer <ResizableBorderComponent> resizableBorder;
  43102. private:
  43103. Component::SafePointer <Component> contentComponent;
  43104. bool ownsContentComponent, resizeToFitContent, fullscreen;
  43105. ComponentDragger dragger;
  43106. Rectangle<int> lastNonFullScreenPos;
  43107. ComponentBoundsConstrainer defaultConstrainer;
  43108. ComponentBoundsConstrainer* constrainer;
  43109. #if JUCE_DEBUG
  43110. bool hasBeenResized;
  43111. #endif
  43112. void updateLastPos();
  43113. void setContent (Component* newComp, bool takeOwnership, bool resizeToFit);
  43114. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  43115. // The parameters for these methods have changed - please update your code!
  43116. JUCE_DEPRECATED (void getBorderThickness (int& left, int& top, int& right, int& bottom));
  43117. JUCE_DEPRECATED (void getContentComponentBorder (int& left, int& top, int& right, int& bottom));
  43118. #endif
  43119. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableWindow);
  43120. };
  43121. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  43122. /*** End of inlined file: juce_ResizableWindow.h ***/
  43123. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  43124. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43125. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43126. /**
  43127. A glyph from a particular font, with a particular size, style,
  43128. typeface and position.
  43129. @see GlyphArrangement, Font
  43130. */
  43131. class JUCE_API PositionedGlyph
  43132. {
  43133. public:
  43134. PositionedGlyph (const PositionedGlyph& other);
  43135. /** Returns the character the glyph represents. */
  43136. juce_wchar getCharacter() const { return character; }
  43137. /** Checks whether the glyph is actually empty. */
  43138. bool isWhitespace() const { return CharacterFunctions::isWhitespace (character); }
  43139. /** Returns the position of the glyph's left-hand edge. */
  43140. float getLeft() const { return x; }
  43141. /** Returns the position of the glyph's right-hand edge. */
  43142. float getRight() const { return x + w; }
  43143. /** Returns the y position of the glyph's baseline. */
  43144. float getBaselineY() const { return y; }
  43145. /** Returns the y position of the top of the glyph. */
  43146. float getTop() const { return y - font.getAscent(); }
  43147. /** Returns the y position of the bottom of the glyph. */
  43148. float getBottom() const { return y + font.getDescent(); }
  43149. /** Returns the bounds of the glyph. */
  43150. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  43151. /** Shifts the glyph's position by a relative amount. */
  43152. void moveBy (float deltaX, float deltaY);
  43153. /** Draws the glyph into a graphics context. */
  43154. void draw (const Graphics& g) const;
  43155. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  43156. void draw (const Graphics& g, const AffineTransform& transform) const;
  43157. /** Returns the path for this glyph.
  43158. @param path the glyph's outline will be appended to this path
  43159. */
  43160. void createPath (Path& path) const;
  43161. /** Checks to see if a point lies within this glyph. */
  43162. bool hitTest (float x, float y) const;
  43163. private:
  43164. friend class GlyphArrangement;
  43165. float x, y, w;
  43166. Font font;
  43167. juce_wchar character;
  43168. int glyph;
  43169. PositionedGlyph (float x, float y, float w, const Font& font, juce_wchar character, int glyph);
  43170. JUCE_LEAK_DETECTOR (PositionedGlyph);
  43171. };
  43172. /**
  43173. A set of glyphs, each with a position.
  43174. You can create a GlyphArrangement, text to it and then draw it onto a
  43175. graphics context. It's used internally by the text methods in the
  43176. Graphics class, but can be used directly if more control is needed.
  43177. @see Font, PositionedGlyph
  43178. */
  43179. class JUCE_API GlyphArrangement
  43180. {
  43181. public:
  43182. /** Creates an empty arrangement. */
  43183. GlyphArrangement();
  43184. /** Takes a copy of another arrangement. */
  43185. GlyphArrangement (const GlyphArrangement& other);
  43186. /** Copies another arrangement onto this one.
  43187. To add another arrangement without clearing this one, use addGlyphArrangement().
  43188. */
  43189. GlyphArrangement& operator= (const GlyphArrangement& other);
  43190. /** Destructor. */
  43191. ~GlyphArrangement();
  43192. /** Returns the total number of glyphs in the arrangement. */
  43193. int getNumGlyphs() const noexcept { return glyphs.size(); }
  43194. /** Returns one of the glyphs from the arrangement.
  43195. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  43196. careful not to pass an out-of-range index here, as it
  43197. doesn't do any bounds-checking.
  43198. */
  43199. PositionedGlyph& getGlyph (int index) const;
  43200. /** Clears all text from the arrangement and resets it.
  43201. */
  43202. void clear();
  43203. /** Appends a line of text to the arrangement.
  43204. This will add the text as a single line, where x is the left-hand edge of the
  43205. first character, and y is the position for the text's baseline.
  43206. If the text contains new-lines or carriage-returns, this will ignore them - use
  43207. addJustifiedText() to add multi-line arrangements.
  43208. */
  43209. void addLineOfText (const Font& font,
  43210. const String& text,
  43211. float x, float y);
  43212. /** Adds a line of text, truncating it if it's wider than a specified size.
  43213. This is the same as addLineOfText(), but if the line's width exceeds the value
  43214. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  43215. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  43216. */
  43217. void addCurtailedLineOfText (const Font& font,
  43218. const String& text,
  43219. float x, float y,
  43220. float maxWidthPixels,
  43221. bool useEllipsis);
  43222. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  43223. This will add text to the arrangement, breaking it into new lines either where there
  43224. is a new-line or carriage-return character in the text, or where a line's width
  43225. exceeds the value set in maxLineWidth.
  43226. Each line that is added will be laid out using the flags set in horizontalLayout, so
  43227. the lines can be left- or right-justified, or centred horizontally in the space
  43228. between x and (x + maxLineWidth).
  43229. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  43230. lines will be placed below it, separated by a distance of font.getHeight().
  43231. */
  43232. void addJustifiedText (const Font& font,
  43233. const String& text,
  43234. float x, float y,
  43235. float maxLineWidth,
  43236. const Justification& horizontalLayout);
  43237. /** Tries to fit some text withing a given space.
  43238. This does its best to make the given text readable within the specified rectangle,
  43239. so it useful for labelling things.
  43240. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  43241. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  43242. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  43243. it's been truncated.
  43244. A Justification parameter lets you specify how the text is laid out within the rectangle,
  43245. both horizontally and vertically.
  43246. @see Graphics::drawFittedText
  43247. */
  43248. void addFittedText (const Font& font,
  43249. const String& text,
  43250. float x, float y, float width, float height,
  43251. const Justification& layout,
  43252. int maximumLinesToUse,
  43253. float minimumHorizontalScale = 0.7f);
  43254. /** Appends another glyph arrangement to this one. */
  43255. void addGlyphArrangement (const GlyphArrangement& other);
  43256. /** Draws this glyph arrangement to a graphics context.
  43257. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  43258. method, which renders the glyphs as filled vectors.
  43259. */
  43260. void draw (const Graphics& g) const;
  43261. /** Draws this glyph arrangement to a graphics context.
  43262. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  43263. method for non-transformed arrangements.
  43264. */
  43265. void draw (const Graphics& g, const AffineTransform& transform) const;
  43266. /** Converts the set of glyphs into a path.
  43267. @param path the glyphs' outlines will be appended to this path
  43268. */
  43269. void createPath (Path& path) const;
  43270. /** Looks for a glyph that contains the given co-ordinate.
  43271. @returns the index of the glyph, or -1 if none were found.
  43272. */
  43273. int findGlyphIndexAt (float x, float y) const;
  43274. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  43275. @param startIndex the first glyph to test
  43276. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  43277. startIndex will be included
  43278. @param includeWhitespace if true, the extent of any whitespace characters will also
  43279. be taken into account
  43280. */
  43281. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  43282. /** Shifts a set of glyphs by a given amount.
  43283. @param startIndex the first glyph to transform
  43284. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  43285. startIndex will be used
  43286. @param deltaX the amount to add to their x-positions
  43287. @param deltaY the amount to add to their y-positions
  43288. */
  43289. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  43290. float deltaX, float deltaY);
  43291. /** Removes a set of glyphs from the arrangement.
  43292. @param startIndex the first glyph to remove
  43293. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  43294. startIndex will be deleted
  43295. */
  43296. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  43297. /** Expands or compresses a set of glyphs horizontally.
  43298. @param startIndex the first glyph to transform
  43299. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  43300. startIndex will be used
  43301. @param horizontalScaleFactor how much to scale their horizontal width by
  43302. */
  43303. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  43304. float horizontalScaleFactor);
  43305. /** Justifies a set of glyphs within a given space.
  43306. This moves the glyphs as a block so that the whole thing is located within the
  43307. given rectangle with the specified layout.
  43308. If the Justification::horizontallyJustified flag is specified, each line will
  43309. be stretched out to fill the specified width.
  43310. */
  43311. void justifyGlyphs (int startIndex, int numGlyphs,
  43312. float x, float y, float width, float height,
  43313. const Justification& justification);
  43314. private:
  43315. OwnedArray <PositionedGlyph> glyphs;
  43316. int insertEllipsis (const Font& font, float maxXPos, int startIndex, int endIndex);
  43317. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  43318. const Justification& justification, float minimumHorizontalScale);
  43319. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  43320. JUCE_LEAK_DETECTOR (GlyphArrangement);
  43321. };
  43322. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43323. /*** End of inlined file: juce_GlyphArrangement.h ***/
  43324. /*** Start of inlined file: juce_AlertWindow.h ***/
  43325. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  43326. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  43327. /*** Start of inlined file: juce_TextLayout.h ***/
  43328. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  43329. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  43330. class Graphics;
  43331. /**
  43332. A laid-out arrangement of text.
  43333. You can add text in different fonts to a TextLayout object, then call its
  43334. layout() method to word-wrap it into lines. The layout can then be drawn
  43335. using a graphics context.
  43336. It's handy if you've got a message to display, because you can format it,
  43337. measure the extent of the layout, and then create a suitably-sized window
  43338. to show it in.
  43339. @see Font, Graphics::drawFittedText, GlyphArrangement
  43340. */
  43341. class JUCE_API TextLayout
  43342. {
  43343. public:
  43344. /** Creates an empty text layout.
  43345. Text can then be appended using the appendText() method.
  43346. */
  43347. TextLayout();
  43348. /** Creates a copy of another layout object. */
  43349. TextLayout (const TextLayout& other);
  43350. /** Creates a text layout from an initial string and font. */
  43351. TextLayout (const String& text, const Font& font);
  43352. /** Destructor. */
  43353. ~TextLayout();
  43354. /** Copies another layout onto this one. */
  43355. TextLayout& operator= (const TextLayout& layoutToCopy);
  43356. /** Clears the layout, removing all its text. */
  43357. void clear();
  43358. /** Adds a string to the end of the arrangement.
  43359. The string will be broken onto new lines wherever it contains
  43360. carriage-returns or linefeeds. After adding it, you can call layout()
  43361. to wrap long lines into a paragraph and justify it.
  43362. */
  43363. void appendText (const String& textToAppend,
  43364. const Font& fontToUse);
  43365. /** Replaces all the text with a new string.
  43366. This is equivalent to calling clear() followed by appendText().
  43367. */
  43368. void setText (const String& newText,
  43369. const Font& fontToUse);
  43370. /** Returns true if the layout has not had any text added yet. */
  43371. bool isEmpty() const;
  43372. /** Breaks the text up to form a paragraph with the given width.
  43373. @param maximumWidth any text wider than this will be split
  43374. across multiple lines
  43375. @param justification how the lines are to be laid-out horizontally
  43376. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  43377. width that keeps all the lines of text at a
  43378. similar length - this is good when you're displaying
  43379. a short message and don't want it to get split
  43380. onto two lines with only a couple of words on
  43381. the second line, which looks untidy.
  43382. */
  43383. void layout (int maximumWidth,
  43384. const Justification& justification,
  43385. bool attemptToBalanceLineLengths);
  43386. /** Returns the overall width of the entire text layout. */
  43387. int getWidth() const;
  43388. /** Returns the overall height of the entire text layout. */
  43389. int getHeight() const;
  43390. /** Returns the total number of lines of text. */
  43391. int getNumLines() const { return totalLines; }
  43392. /** Returns the width of a particular line of text.
  43393. @param lineNumber the line, from 0 to (getNumLines() - 1)
  43394. */
  43395. int getLineWidth (int lineNumber) const;
  43396. /** Renders the text at a specified position using a graphics context.
  43397. */
  43398. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  43399. /** Renders the text within a specified rectangle using a graphics context.
  43400. The justification flags dictate how the block of text should be positioned
  43401. within the rectangle.
  43402. */
  43403. void drawWithin (Graphics& g,
  43404. int x, int y, int w, int h,
  43405. const Justification& layoutFlags) const;
  43406. private:
  43407. class Token;
  43408. friend class OwnedArray <Token>;
  43409. OwnedArray <Token> tokens;
  43410. int totalLines;
  43411. JUCE_LEAK_DETECTOR (TextLayout);
  43412. };
  43413. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  43414. /*** End of inlined file: juce_TextLayout.h ***/
  43415. /** A window that displays a message and has buttons for the user to react to it.
  43416. For simple dialog boxes with just a couple of buttons on them, there are
  43417. some static methods for running these.
  43418. For more complex dialogs, an AlertWindow can be created, then it can have some
  43419. buttons and components added to it, and its runModalLoop() method is then used to
  43420. show it. The value returned by runModalLoop() shows which button the
  43421. user pressed to dismiss the box.
  43422. @see ThreadWithProgressWindow
  43423. */
  43424. class JUCE_API AlertWindow : public TopLevelWindow,
  43425. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  43426. {
  43427. public:
  43428. /** The type of icon to show in the dialog box. */
  43429. enum AlertIconType
  43430. {
  43431. NoIcon, /**< No icon will be shown on the dialog box. */
  43432. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  43433. user to answer a question. */
  43434. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  43435. warning about something and shouldn't be ignored. */
  43436. InfoIcon /**< An icon that indicates that the dialog box is just
  43437. giving the user some information, which doesn't require
  43438. a response from them. */
  43439. };
  43440. /** Creates an AlertWindow.
  43441. @param title the headline to show at the top of the dialog box
  43442. @param message a longer, more descriptive message to show underneath the
  43443. headline
  43444. @param iconType the type of icon to display
  43445. @param associatedComponent if this is non-null, it specifies the component that the
  43446. alert window should be associated with. Depending on the look
  43447. and feel, this might be used for positioning of the alert window.
  43448. */
  43449. AlertWindow (const String& title,
  43450. const String& message,
  43451. AlertIconType iconType,
  43452. Component* associatedComponent = nullptr);
  43453. /** Destroys the AlertWindow */
  43454. ~AlertWindow();
  43455. /** Returns the type of alert icon that was specified when the window
  43456. was created. */
  43457. AlertIconType getAlertType() const noexcept { return alertIconType; }
  43458. /** Changes the dialog box's message.
  43459. This will also resize the window to fit the new message if required.
  43460. */
  43461. void setMessage (const String& message);
  43462. /** Adds a button to the window.
  43463. @param name the text to show on the button
  43464. @param returnValue the value that should be returned from runModalLoop()
  43465. if this is the button that the user presses.
  43466. @param shortcutKey1 an optional key that can be pressed to trigger this button
  43467. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  43468. */
  43469. void addButton (const String& name,
  43470. int returnValue,
  43471. const KeyPress& shortcutKey1 = KeyPress(),
  43472. const KeyPress& shortcutKey2 = KeyPress());
  43473. /** Returns the number of buttons that the window currently has. */
  43474. int getNumButtons() const;
  43475. /** Invokes a click of one of the buttons. */
  43476. void triggerButtonClick (const String& buttonName);
  43477. /** Adds a textbox to the window for entering strings.
  43478. @param name an internal name for the text-box. This is the name to pass to
  43479. the getTextEditorContents() method to find out what the
  43480. user typed-in.
  43481. @param initialContents a string to show in the text box when it's first shown
  43482. @param onScreenLabel if this is non-empty, it will be displayed next to the
  43483. text-box to label it.
  43484. @param isPasswordBox if true, the text editor will display asterisks instead of
  43485. the actual text
  43486. @see getTextEditorContents
  43487. */
  43488. void addTextEditor (const String& name,
  43489. const String& initialContents,
  43490. const String& onScreenLabel = String::empty,
  43491. bool isPasswordBox = false);
  43492. /** Returns the contents of a named textbox.
  43493. After showing an AlertWindow that contains a text editor, this can be
  43494. used to find out what the user has typed into it.
  43495. @param nameOfTextEditor the name of the text box that you're interested in
  43496. @see addTextEditor
  43497. */
  43498. const String getTextEditorContents (const String& nameOfTextEditor) const;
  43499. /** Returns a pointer to a textbox that was added with addTextEditor(). */
  43500. TextEditor* getTextEditor (const String& nameOfTextEditor) const;
  43501. /** Adds a drop-down list of choices to the box.
  43502. After the box has been shown, the getComboBoxComponent() method can
  43503. be used to find out which item the user picked.
  43504. @param name the label to use for the drop-down list
  43505. @param items the list of items to show in it
  43506. @param onScreenLabel if this is non-empty, it will be displayed next to the
  43507. combo-box to label it.
  43508. @see getComboBoxComponent
  43509. */
  43510. void addComboBox (const String& name,
  43511. const StringArray& items,
  43512. const String& onScreenLabel = String::empty);
  43513. /** Returns a drop-down list that was added to the AlertWindow.
  43514. @param nameOfList the name that was passed into the addComboBox() method
  43515. when creating the drop-down
  43516. @returns the ComboBox component, or 0 if none was found for the given name.
  43517. */
  43518. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  43519. /** Adds a block of text.
  43520. This is handy for adding a multi-line note next to a textbox or combo-box,
  43521. to provide more details about what's going on.
  43522. */
  43523. void addTextBlock (const String& text);
  43524. /** Adds a progress-bar to the window.
  43525. @param progressValue a variable that will be repeatedly checked while the
  43526. dialog box is visible, to see how far the process has
  43527. got. The value should be in the range 0 to 1.0
  43528. */
  43529. void addProgressBarComponent (double& progressValue);
  43530. /** Adds a user-defined component to the dialog box.
  43531. @param component the component to add - its size should be set up correctly
  43532. before it is passed in. The caller is responsible for deleting
  43533. the component later on - the AlertWindow won't delete it.
  43534. */
  43535. void addCustomComponent (Component* component);
  43536. /** Returns the number of custom components in the dialog box.
  43537. @see getCustomComponent, addCustomComponent
  43538. */
  43539. int getNumCustomComponents() const;
  43540. /** Returns one of the custom components in the dialog box.
  43541. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  43542. will return 0
  43543. @see getNumCustomComponents, addCustomComponent
  43544. */
  43545. Component* getCustomComponent (int index) const;
  43546. /** Removes one of the custom components in the dialog box.
  43547. Note that this won't delete it, it just removes the component from the window
  43548. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  43549. will return 0
  43550. @returns the component that was removed (or null)
  43551. @see getNumCustomComponents, addCustomComponent
  43552. */
  43553. Component* removeCustomComponent (int index);
  43554. /** Returns true if the window contains any components other than just buttons.*/
  43555. bool containsAnyExtraComponents() const;
  43556. // easy-to-use message box functions:
  43557. /** Shows a dialog box that just has a message and a single button to get rid of it.
  43558. If the callback parameter is null, the box is shown modally, and the method will
  43559. block until the user has clicked the button (or pressed the escape or return keys).
  43560. If the callback parameter is non-null, the box will be displayed and placed into a
  43561. modal state, but this method will return immediately, and the callback will be invoked
  43562. later when the user dismisses the box.
  43563. @param iconType the type of icon to show
  43564. @param title the headline to show at the top of the box
  43565. @param message a longer, more descriptive message to show underneath the
  43566. headline
  43567. @param buttonText the text to show in the button - if this string is empty, the
  43568. default string "ok" (or a localised version) will be used.
  43569. @param associatedComponent if this is non-null, it specifies the component that the
  43570. alert window should be associated with. Depending on the look
  43571. and feel, this might be used for positioning of the alert window.
  43572. */
  43573. #if JUCE_MODAL_LOOPS_PERMITTED
  43574. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  43575. const String& title,
  43576. const String& message,
  43577. const String& buttonText = String::empty,
  43578. Component* associatedComponent = nullptr);
  43579. #endif
  43580. /** Shows a dialog box that just has a message and a single button to get rid of it.
  43581. If the callback parameter is null, the box is shown modally, and the method will
  43582. block until the user has clicked the button (or pressed the escape or return keys).
  43583. If the callback parameter is non-null, the box will be displayed and placed into a
  43584. modal state, but this method will return immediately, and the callback will be invoked
  43585. later when the user dismisses the box.
  43586. @param iconType the type of icon to show
  43587. @param title the headline to show at the top of the box
  43588. @param message a longer, more descriptive message to show underneath the
  43589. headline
  43590. @param buttonText the text to show in the button - if this string is empty, the
  43591. default string "ok" (or a localised version) will be used.
  43592. @param associatedComponent if this is non-null, it specifies the component that the
  43593. alert window should be associated with. Depending on the look
  43594. and feel, this might be used for positioning of the alert window.
  43595. */
  43596. static void JUCE_CALLTYPE showMessageBoxAsync (AlertIconType iconType,
  43597. const String& title,
  43598. const String& message,
  43599. const String& buttonText = String::empty,
  43600. Component* associatedComponent = nullptr);
  43601. /** Shows a dialog box with two buttons.
  43602. Ideal for ok/cancel or yes/no choices. The return key can also be used
  43603. to trigger the first button, and the escape key for the second button.
  43604. If the callback parameter is null, the box is shown modally, and the method will
  43605. block until the user has clicked the button (or pressed the escape or return keys).
  43606. If the callback parameter is non-null, the box will be displayed and placed into a
  43607. modal state, but this method will return immediately, and the callback will be invoked
  43608. later when the user dismisses the box.
  43609. @param iconType the type of icon to show
  43610. @param title the headline to show at the top of the box
  43611. @param message a longer, more descriptive message to show underneath the
  43612. headline
  43613. @param button1Text the text to show in the first button - if this string is
  43614. empty, the default string "ok" (or a localised version of it)
  43615. will be used.
  43616. @param button2Text the text to show in the second button - if this string is
  43617. empty, the default string "cancel" (or a localised version of it)
  43618. will be used.
  43619. @param associatedComponent if this is non-null, it specifies the component that the
  43620. alert window should be associated with. Depending on the look
  43621. and feel, this might be used for positioning of the alert window.
  43622. @param callback if this is non-null, the menu will be launched asynchronously,
  43623. returning immediately, and the callback will receive a call to its
  43624. modalStateFinished() when the box is dismissed, with its parameter
  43625. being 1 if the ok button was pressed, or 0 for cancel, The callback object
  43626. will be owned and deleted by the system, so make sure that it works
  43627. safely and doesn't keep any references to objects that might be deleted
  43628. before it gets called.
  43629. @returns true if button 1 was clicked, false if it was button 2. If the callback parameter
  43630. is not null, the method always returns false, and the user's choice is delivered
  43631. later by the callback.
  43632. */
  43633. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  43634. const String& title,
  43635. const String& message,
  43636. #if JUCE_MODAL_LOOPS_PERMITTED
  43637. const String& button1Text = String::empty,
  43638. const String& button2Text = String::empty,
  43639. Component* associatedComponent = nullptr,
  43640. ModalComponentManager::Callback* callback = nullptr);
  43641. #else
  43642. const String& button1Text,
  43643. const String& button2Text,
  43644. Component* associatedComponent,
  43645. ModalComponentManager::Callback* callback);
  43646. #endif
  43647. /** Shows a dialog box with three buttons.
  43648. Ideal for yes/no/cancel boxes.
  43649. The escape key can be used to trigger the third button.
  43650. If the callback parameter is null, the box is shown modally, and the method will
  43651. block until the user has clicked the button (or pressed the escape or return keys).
  43652. If the callback parameter is non-null, the box will be displayed and placed into a
  43653. modal state, but this method will return immediately, and the callback will be invoked
  43654. later when the user dismisses the box.
  43655. @param iconType the type of icon to show
  43656. @param title the headline to show at the top of the box
  43657. @param message a longer, more descriptive message to show underneath the
  43658. headline
  43659. @param button1Text the text to show in the first button - if an empty string, then
  43660. "yes" will be used (or a localised version of it)
  43661. @param button2Text the text to show in the first button - if an empty string, then
  43662. "no" will be used (or a localised version of it)
  43663. @param button3Text the text to show in the first button - if an empty string, then
  43664. "cancel" will be used (or a localised version of it)
  43665. @param associatedComponent if this is non-null, it specifies the component that the
  43666. alert window should be associated with. Depending on the look
  43667. and feel, this might be used for positioning of the alert window.
  43668. @param callback if this is non-null, the menu will be launched asynchronously,
  43669. returning immediately, and the callback will receive a call to its
  43670. modalStateFinished() when the box is dismissed, with its parameter
  43671. being 1 if the "yes" button was pressed, 2 for the "no" button, or 0
  43672. if it was cancelled, The callback object will be owned and deleted by the
  43673. system, so make sure that it works safely and doesn't keep any references
  43674. to objects that might be deleted before it gets called.
  43675. @returns If the callback parameter has been set, this returns 0. Otherwise, it
  43676. returns one of the following values:
  43677. - 0 if the third button was pressed (normally used for 'cancel')
  43678. - 1 if the first button was pressed (normally used for 'yes')
  43679. - 2 if the middle button was pressed (normally used for 'no')
  43680. */
  43681. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  43682. const String& title,
  43683. const String& message,
  43684. #if JUCE_MODAL_LOOPS_PERMITTED
  43685. const String& button1Text = String::empty,
  43686. const String& button2Text = String::empty,
  43687. const String& button3Text = String::empty,
  43688. Component* associatedComponent = nullptr,
  43689. ModalComponentManager::Callback* callback = nullptr);
  43690. #else
  43691. const String& button1Text,
  43692. const String& button2Text,
  43693. const String& button3Text,
  43694. Component* associatedComponent,
  43695. ModalComponentManager::Callback* callback);
  43696. #endif
  43697. /** Shows an operating-system native dialog box.
  43698. @param title the title to use at the top
  43699. @param bodyText the longer message to show
  43700. @param isOkCancel if true, this will show an ok/cancel box, if false,
  43701. it'll show a box with just an ok button
  43702. @returns true if the ok button was pressed, false if they pressed cancel.
  43703. */
  43704. #if JUCE_MODAL_LOOPS_PERMITTED
  43705. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  43706. const String& bodyText,
  43707. bool isOkCancel);
  43708. #endif
  43709. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  43710. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43711. methods.
  43712. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43713. */
  43714. enum ColourIds
  43715. {
  43716. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  43717. textColourId = 0x1001810, /**< The colour for the text. */
  43718. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  43719. };
  43720. protected:
  43721. /** @internal */
  43722. void paint (Graphics& g);
  43723. /** @internal */
  43724. void mouseDown (const MouseEvent& e);
  43725. /** @internal */
  43726. void mouseDrag (const MouseEvent& e);
  43727. /** @internal */
  43728. bool keyPressed (const KeyPress& key);
  43729. /** @internal */
  43730. void buttonClicked (Button* button);
  43731. /** @internal */
  43732. void lookAndFeelChanged();
  43733. /** @internal */
  43734. void userTriedToCloseWindow();
  43735. /** @internal */
  43736. int getDesktopWindowStyleFlags() const;
  43737. private:
  43738. String text;
  43739. TextLayout textLayout;
  43740. AlertIconType alertIconType;
  43741. ComponentBoundsConstrainer constrainer;
  43742. ComponentDragger dragger;
  43743. Rectangle<int> textArea;
  43744. OwnedArray<TextButton> buttons;
  43745. OwnedArray<TextEditor> textBoxes;
  43746. OwnedArray<ComboBox> comboBoxes;
  43747. OwnedArray<ProgressBar> progressBars;
  43748. Array<Component*> customComps;
  43749. OwnedArray<Component> textBlocks;
  43750. Array<Component*> allComps;
  43751. StringArray textboxNames, comboBoxNames;
  43752. Font font;
  43753. Component* associatedComponent;
  43754. void updateLayout (bool onlyIncreaseSize);
  43755. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AlertWindow);
  43756. };
  43757. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  43758. /*** End of inlined file: juce_AlertWindow.h ***/
  43759. /**
  43760. A file open/save dialog box.
  43761. This is a Juce-based file dialog box; to use a native file chooser, see the
  43762. FileChooser class.
  43763. To use one of these, create it and call its show() method. e.g.
  43764. @code
  43765. {
  43766. WildcardFileFilter wildcardFilter ("*.foo", "Foo files");
  43767. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  43768. File::nonexistent,
  43769. &wildcardFilter,
  43770. 0);
  43771. FileChooserDialogBox dialogBox ("Open some kind of file",
  43772. "Please choose some kind of file that you want to open...",
  43773. browser,
  43774. getLookAndFeel().alertWindowBackground);
  43775. if (dialogBox.show())
  43776. {
  43777. File selectedFile = browser.getCurrentFile();
  43778. ...
  43779. }
  43780. }
  43781. @endcode
  43782. @see FileChooser
  43783. */
  43784. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  43785. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  43786. public FileBrowserListener
  43787. {
  43788. public:
  43789. /** Creates a file chooser box.
  43790. @param title the main title to show at the top of the box
  43791. @param instructions an optional longer piece of text to show below the title in
  43792. a smaller font, describing in more detail what's required.
  43793. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  43794. box. Make sure you delete this after (but not before!) the
  43795. dialog box has been deleted.
  43796. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  43797. if they try to select a file that already exists. (This
  43798. flag is only used when saving files)
  43799. @param backgroundColour the background colour for the top level window
  43800. @see FileBrowserComponent, FilePreviewComponent
  43801. */
  43802. FileChooserDialogBox (const String& title,
  43803. const String& instructions,
  43804. FileBrowserComponent& browserComponent,
  43805. bool warnAboutOverwritingExistingFiles,
  43806. const Colour& backgroundColour);
  43807. /** Destructor. */
  43808. ~FileChooserDialogBox();
  43809. #if JUCE_MODAL_LOOPS_PERMITTED
  43810. /** Displays and runs the dialog box modally.
  43811. This will show the box with the specified size, returning true if the user
  43812. pressed 'ok', or false if they cancelled.
  43813. Leave the width or height as 0 to use the default size
  43814. */
  43815. bool show (int width = 0, int height = 0);
  43816. /** Displays and runs the dialog box modally.
  43817. This will show the box with the specified size at the specified location,
  43818. returning true if the user pressed 'ok', or false if they cancelled.
  43819. Leave the width or height as 0 to use the default size.
  43820. */
  43821. bool showAt (int x, int y, int width, int height);
  43822. #endif
  43823. /** Sets the size of this dialog box to its default and positions it either in the
  43824. centre of the screen, or centred around a component that is provided.
  43825. */
  43826. void centreWithDefaultSize (Component* componentToCentreAround = 0);
  43827. /** A set of colour IDs to use to change the colour of various aspects of the box.
  43828. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43829. methods.
  43830. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43831. */
  43832. enum ColourIds
  43833. {
  43834. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  43835. };
  43836. /** @internal */
  43837. void buttonClicked (Button* button);
  43838. /** @internal */
  43839. void closeButtonPressed();
  43840. /** @internal */
  43841. void selectionChanged();
  43842. /** @internal */
  43843. void fileClicked (const File& file, const MouseEvent& e);
  43844. /** @internal */
  43845. void fileDoubleClicked (const File& file);
  43846. private:
  43847. class ContentComponent;
  43848. ContentComponent* content;
  43849. const bool warnAboutOverwritingExistingFiles;
  43850. void okButtonPressed();
  43851. void createNewFolder();
  43852. void createNewFolderConfirmed (const String& name);
  43853. static void okToOverwriteFileCallback (int result, FileChooserDialogBox*);
  43854. static void createNewFolderCallback (int result, FileChooserDialogBox*, Component::SafePointer<AlertWindow>);
  43855. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileChooserDialogBox);
  43856. };
  43857. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  43858. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  43859. #endif
  43860. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  43861. #endif
  43862. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43863. /*** Start of inlined file: juce_FileListComponent.h ***/
  43864. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43865. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43866. /**
  43867. A component that displays the files in a directory as a listbox.
  43868. This implements the DirectoryContentsDisplayComponent base class so that
  43869. it can be used in a FileBrowserComponent.
  43870. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  43871. class and the FileBrowserListener class.
  43872. @see DirectoryContentsList, FileTreeComponent
  43873. */
  43874. class JUCE_API FileListComponent : public ListBox,
  43875. public DirectoryContentsDisplayComponent,
  43876. private ListBoxModel,
  43877. private ChangeListener
  43878. {
  43879. public:
  43880. /** Creates a listbox to show the contents of a specified directory.
  43881. */
  43882. FileListComponent (DirectoryContentsList& listToShow);
  43883. /** Destructor. */
  43884. ~FileListComponent();
  43885. /** Returns the number of files the user has got selected.
  43886. @see getSelectedFile
  43887. */
  43888. int getNumSelectedFiles() const;
  43889. /** Returns one of the files that the user has currently selected.
  43890. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  43891. @see getNumSelectedFiles
  43892. */
  43893. const File getSelectedFile (int index = 0) const;
  43894. /** Deselects any files that are currently selected. */
  43895. void deselectAllFiles();
  43896. /** Scrolls to the top of the list. */
  43897. void scrollToTop();
  43898. /** @internal */
  43899. void changeListenerCallback (ChangeBroadcaster*);
  43900. /** @internal */
  43901. int getNumRows();
  43902. /** @internal */
  43903. void paintListBoxItem (int, Graphics&, int, int, bool);
  43904. /** @internal */
  43905. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  43906. /** @internal */
  43907. void selectedRowsChanged (int lastRowSelected);
  43908. /** @internal */
  43909. void deleteKeyPressed (int currentSelectedRow);
  43910. /** @internal */
  43911. void returnKeyPressed (int currentSelectedRow);
  43912. private:
  43913. File lastDirectory;
  43914. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListComponent);
  43915. };
  43916. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43917. /*** End of inlined file: juce_FileListComponent.h ***/
  43918. #endif
  43919. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43920. /*** Start of inlined file: juce_FilenameComponent.h ***/
  43921. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43922. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43923. class FilenameComponent;
  43924. /**
  43925. Listens for events happening to a FilenameComponent.
  43926. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  43927. register one of these objects for event callbacks when the filename is changed.
  43928. @see FilenameComponent
  43929. */
  43930. class JUCE_API FilenameComponentListener
  43931. {
  43932. public:
  43933. /** Destructor. */
  43934. virtual ~FilenameComponentListener() {}
  43935. /** This method is called after the FilenameComponent's file has been changed. */
  43936. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  43937. };
  43938. /**
  43939. Shows a filename as an editable text box, with a 'browse' button and a
  43940. drop-down list for recently selected files.
  43941. A handy component for dialogue boxes where you want the user to be able to
  43942. select a file or directory.
  43943. Attach an FilenameComponentListener using the addListener() method, and it will
  43944. get called each time the user changes the filename, either by browsing for a file
  43945. and clicking 'ok', or by typing a new filename into the box and pressing return.
  43946. @see FileChooser, ComboBox
  43947. */
  43948. class JUCE_API FilenameComponent : public Component,
  43949. public SettableTooltipClient,
  43950. public FileDragAndDropTarget,
  43951. private AsyncUpdater,
  43952. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  43953. private ComboBoxListener
  43954. {
  43955. public:
  43956. /** Creates a FilenameComponent.
  43957. @param name the name for this component.
  43958. @param currentFile the file to initially show in the box
  43959. @param canEditFilename if true, the user can manually edit the filename; if false,
  43960. they can only change it by browsing for a new file
  43961. @param isDirectory if true, the file will be treated as a directory, and
  43962. an appropriate directory browser used
  43963. @param isForSaving if true, the file browser will allow non-existent files to
  43964. be picked, as the file is assumed to be used for saving rather
  43965. than loading
  43966. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  43967. If an empty string is passed in, then the pattern is assumed to be "*"
  43968. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  43969. to any filenames that are entered or chosen
  43970. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  43971. will only appear if the initial file isn't valid)
  43972. */
  43973. FilenameComponent (const String& name,
  43974. const File& currentFile,
  43975. bool canEditFilename,
  43976. bool isDirectory,
  43977. bool isForSaving,
  43978. const String& fileBrowserWildcard,
  43979. const String& enforcedSuffix,
  43980. const String& textWhenNothingSelected);
  43981. /** Destructor. */
  43982. ~FilenameComponent();
  43983. /** Returns the currently displayed filename. */
  43984. const File getCurrentFile() const;
  43985. /** Changes the current filename.
  43986. If addToRecentlyUsedList is true, the filename will also be added to the
  43987. drop-down list of recent files.
  43988. If sendChangeNotification is false, then the listeners won't be told of the
  43989. change.
  43990. */
  43991. void setCurrentFile (File newFile,
  43992. bool addToRecentlyUsedList,
  43993. bool sendChangeNotification = true);
  43994. /** Changes whether the use can type into the filename box.
  43995. */
  43996. void setFilenameIsEditable (bool shouldBeEditable);
  43997. /** Sets a file or directory to be the default starting point for the browser to show.
  43998. This is only used if the current file hasn't been set.
  43999. */
  44000. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  44001. /** Returns all the entries on the recent files list.
  44002. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  44003. state of this list.
  44004. @see setRecentlyUsedFilenames
  44005. */
  44006. const StringArray getRecentlyUsedFilenames() const;
  44007. /** Sets all the entries on the recent files list.
  44008. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  44009. state of this list.
  44010. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  44011. */
  44012. void setRecentlyUsedFilenames (const StringArray& filenames);
  44013. /** Adds an entry to the recently-used files dropdown list.
  44014. If the file is already in the list, it will be moved to the top. A limit
  44015. is also placed on the number of items that are kept in the list.
  44016. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  44017. */
  44018. void addRecentlyUsedFile (const File& file);
  44019. /** Changes the limit for the number of files that will be stored in the recent-file list.
  44020. */
  44021. void setMaxNumberOfRecentFiles (int newMaximum);
  44022. /** Changes the text shown on the 'browse' button.
  44023. By default this button just says "..." but you can change it. The button itself
  44024. can be changed using the look-and-feel classes, so it might not actually have any
  44025. text on it.
  44026. */
  44027. void setBrowseButtonText (const String& browseButtonText);
  44028. /** Adds a listener that will be called when the selected file is changed. */
  44029. void addListener (FilenameComponentListener* listener);
  44030. /** Removes a previously-registered listener. */
  44031. void removeListener (FilenameComponentListener* listener);
  44032. /** Gives the component a tooltip. */
  44033. void setTooltip (const String& newTooltip);
  44034. /** @internal */
  44035. void paintOverChildren (Graphics& g);
  44036. /** @internal */
  44037. void resized();
  44038. /** @internal */
  44039. void lookAndFeelChanged();
  44040. /** @internal */
  44041. bool isInterestedInFileDrag (const StringArray& files);
  44042. /** @internal */
  44043. void filesDropped (const StringArray& files, int, int);
  44044. /** @internal */
  44045. void fileDragEnter (const StringArray& files, int, int);
  44046. /** @internal */
  44047. void fileDragExit (const StringArray& files);
  44048. private:
  44049. ComboBox filenameBox;
  44050. String lastFilename;
  44051. ScopedPointer<Button> browseButton;
  44052. int maxRecentFiles;
  44053. bool isDir, isSaving, isFileDragOver;
  44054. String wildcard, enforcedSuffix, browseButtonText;
  44055. ListenerList <FilenameComponentListener> listeners;
  44056. File defaultBrowseFile;
  44057. void comboBoxChanged (ComboBox*);
  44058. void buttonClicked (Button* button);
  44059. void handleAsyncUpdate();
  44060. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilenameComponent);
  44061. };
  44062. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  44063. /*** End of inlined file: juce_FilenameComponent.h ***/
  44064. #endif
  44065. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  44066. #endif
  44067. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44068. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  44069. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44070. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44071. /**
  44072. Shows a set of file paths in a list, allowing them to be added, removed or
  44073. re-ordered.
  44074. @see FileSearchPath
  44075. */
  44076. class JUCE_API FileSearchPathListComponent : public Component,
  44077. public SettableTooltipClient,
  44078. public FileDragAndDropTarget,
  44079. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  44080. private ListBoxModel
  44081. {
  44082. public:
  44083. /** Creates an empty FileSearchPathListComponent. */
  44084. FileSearchPathListComponent();
  44085. /** Destructor. */
  44086. ~FileSearchPathListComponent();
  44087. /** Returns the path as it is currently shown. */
  44088. const FileSearchPath& getPath() const noexcept { return path; }
  44089. /** Changes the current path. */
  44090. void setPath (const FileSearchPath& newPath);
  44091. /** Sets a file or directory to be the default starting point for the browser to show.
  44092. This is only used if the current file hasn't been set.
  44093. */
  44094. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  44095. /** A set of colour IDs to use to change the colour of various aspects of the label.
  44096. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44097. methods.
  44098. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44099. */
  44100. enum ColourIds
  44101. {
  44102. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  44103. Make this transparent if you don't want the background to be filled. */
  44104. };
  44105. /** @internal */
  44106. int getNumRows();
  44107. /** @internal */
  44108. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  44109. /** @internal */
  44110. void deleteKeyPressed (int lastRowSelected);
  44111. /** @internal */
  44112. void returnKeyPressed (int lastRowSelected);
  44113. /** @internal */
  44114. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  44115. /** @internal */
  44116. void selectedRowsChanged (int lastRowSelected);
  44117. /** @internal */
  44118. void resized();
  44119. /** @internal */
  44120. void paint (Graphics& g);
  44121. /** @internal */
  44122. bool isInterestedInFileDrag (const StringArray& files);
  44123. /** @internal */
  44124. void filesDropped (const StringArray& files, int, int);
  44125. /** @internal */
  44126. void buttonClicked (Button* button);
  44127. private:
  44128. FileSearchPath path;
  44129. File defaultBrowseTarget;
  44130. ListBox listBox;
  44131. TextButton addButton, removeButton, changeButton;
  44132. DrawableButton upButton, downButton;
  44133. void changed();
  44134. void updateButtons();
  44135. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileSearchPathListComponent);
  44136. };
  44137. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44138. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  44139. #endif
  44140. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44141. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  44142. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44143. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44144. /**
  44145. A component that displays the files in a directory as a treeview.
  44146. This implements the DirectoryContentsDisplayComponent base class so that
  44147. it can be used in a FileBrowserComponent.
  44148. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  44149. class and the FileBrowserListener class.
  44150. @see DirectoryContentsList, FileListComponent
  44151. */
  44152. class JUCE_API FileTreeComponent : public TreeView,
  44153. public DirectoryContentsDisplayComponent
  44154. {
  44155. public:
  44156. /** Creates a listbox to show the contents of a specified directory.
  44157. */
  44158. FileTreeComponent (DirectoryContentsList& listToShow);
  44159. /** Destructor. */
  44160. ~FileTreeComponent();
  44161. /** Returns the number of files the user has got selected.
  44162. @see getSelectedFile
  44163. */
  44164. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  44165. /** Returns one of the files that the user has currently selected.
  44166. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  44167. @see getNumSelectedFiles
  44168. */
  44169. const File getSelectedFile (int index = 0) const;
  44170. /** Deselects any files that are currently selected. */
  44171. void deselectAllFiles();
  44172. /** Scrolls the list to the top. */
  44173. void scrollToTop();
  44174. /** Setting a name for this allows tree items to be dragged.
  44175. The string that you pass in here will be returned by the getDragSourceDescription()
  44176. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  44177. */
  44178. void setDragAndDropDescription (const String& description);
  44179. /** Returns the last value that was set by setDragAndDropDescription().
  44180. */
  44181. const String& getDragAndDropDescription() const noexcept { return dragAndDropDescription; }
  44182. private:
  44183. String dragAndDropDescription;
  44184. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileTreeComponent);
  44185. };
  44186. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44187. /*** End of inlined file: juce_FileTreeComponent.h ***/
  44188. #endif
  44189. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44190. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  44191. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44192. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44193. /**
  44194. A simple preview component that shows thumbnails of image files.
  44195. @see FileChooserDialogBox, FilePreviewComponent
  44196. */
  44197. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  44198. private Timer
  44199. {
  44200. public:
  44201. /** Creates an ImagePreviewComponent. */
  44202. ImagePreviewComponent();
  44203. /** Destructor. */
  44204. ~ImagePreviewComponent();
  44205. /** @internal */
  44206. void selectedFileChanged (const File& newSelectedFile);
  44207. /** @internal */
  44208. void paint (Graphics& g);
  44209. /** @internal */
  44210. void timerCallback();
  44211. private:
  44212. File fileToLoad;
  44213. Image currentThumbnail;
  44214. String currentDetails;
  44215. void getThumbSize (int& w, int& h) const;
  44216. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImagePreviewComponent);
  44217. };
  44218. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44219. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  44220. #endif
  44221. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44222. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  44223. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44224. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44225. /**
  44226. A type of FileFilter that works by wildcard pattern matching.
  44227. This filter only allows files that match one of the specified patterns, but
  44228. allows all directories through.
  44229. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  44230. */
  44231. class JUCE_API WildcardFileFilter : public FileFilter
  44232. {
  44233. public:
  44234. /**
  44235. Creates a wildcard filter for one or more patterns.
  44236. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  44237. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  44238. or .aiff.
  44239. The description is a name to show the user in a list of possible patterns, so
  44240. for the wav/aiff example, your description might be "audio files".
  44241. */
  44242. WildcardFileFilter (const String& fileWildcardPatterns,
  44243. const String& directoryWildcardPatterns,
  44244. const String& description);
  44245. /** Destructor. */
  44246. ~WildcardFileFilter();
  44247. /** Returns true if the filename matches one of the patterns specified. */
  44248. bool isFileSuitable (const File& file) const;
  44249. /** This always returns true. */
  44250. bool isDirectorySuitable (const File& file) const;
  44251. private:
  44252. StringArray fileWildcards, directoryWildcards;
  44253. static void parse (const String& pattern, StringArray& result);
  44254. static bool match (const File& file, const StringArray& wildcards);
  44255. JUCE_LEAK_DETECTOR (WildcardFileFilter);
  44256. };
  44257. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44258. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  44259. #endif
  44260. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  44261. #endif
  44262. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  44263. #endif
  44264. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  44265. #endif
  44266. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  44267. #endif
  44268. #ifndef __JUCE_CARETCOMPONENT_JUCEHEADER__
  44269. #endif
  44270. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  44271. #endif
  44272. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  44273. #endif
  44274. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44275. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  44276. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44277. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44278. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  44279. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44280. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44281. /**
  44282. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  44283. command in a ApplicationCommandManager.
  44284. Normally, you won't actually create a KeyPressMappingSet directly, because
  44285. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  44286. you'd create yourself an ApplicationCommandManager, and call its
  44287. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  44288. KeyPressMappingSet.
  44289. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  44290. to the top-level component for which you want to handle keystrokes. So for example:
  44291. @code
  44292. class MyMainWindow : public Component
  44293. {
  44294. ApplicationCommandManager* myCommandManager;
  44295. public:
  44296. MyMainWindow()
  44297. {
  44298. myCommandManager = new ApplicationCommandManager();
  44299. // first, make sure the command manager has registered all the commands that its
  44300. // targets can perform..
  44301. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  44302. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  44303. // this will use the command manager to initialise the KeyPressMappingSet with
  44304. // the default keypresses that were specified when the targets added their commands
  44305. // to the manager.
  44306. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  44307. // having set up the default key-mappings, you might now want to load the last set
  44308. // of mappings that the user configured.
  44309. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  44310. // Now tell our top-level window to send any keypresses that arrive to the
  44311. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  44312. addKeyListener (myCommandManager->getKeyMappings());
  44313. }
  44314. ...
  44315. }
  44316. @endcode
  44317. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  44318. register to be told when a command or mapping is added, removed, etc.
  44319. There's also a UI component called KeyMappingEditorComponent that can be used
  44320. to easily edit the key mappings.
  44321. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  44322. */
  44323. class JUCE_API KeyPressMappingSet : public KeyListener,
  44324. public ChangeBroadcaster,
  44325. public FocusChangeListener
  44326. {
  44327. public:
  44328. /** Creates a KeyPressMappingSet for a given command manager.
  44329. Normally, you won't actually create a KeyPressMappingSet directly, because
  44330. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  44331. best thing to do is to create your ApplicationCommandManager, and use the
  44332. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  44333. When a suitable keypress happens, the manager's invoke() method will be
  44334. used to invoke the appropriate command.
  44335. @see ApplicationCommandManager
  44336. */
  44337. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  44338. /** Creates an copy of a KeyPressMappingSet. */
  44339. KeyPressMappingSet (const KeyPressMappingSet& other);
  44340. /** Destructor. */
  44341. ~KeyPressMappingSet();
  44342. ApplicationCommandManager* getCommandManager() const noexcept { return commandManager; }
  44343. /** Returns a list of keypresses that are assigned to a particular command.
  44344. @param commandID the command's ID
  44345. */
  44346. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  44347. /** Assigns a keypress to a command.
  44348. If the keypress is already assigned to a different command, it will first be
  44349. removed from that command, to avoid it triggering multiple functions.
  44350. @param commandID the ID of the command that you want to add a keypress to. If
  44351. this is 0, the keypress will be removed from anything that it
  44352. was previously assigned to, but not re-assigned
  44353. @param newKeyPress the new key-press
  44354. @param insertIndex if this is less than zero, the key will be appended to the
  44355. end of the list of keypresses; otherwise the new keypress will
  44356. be inserted into the existing list at this index
  44357. */
  44358. void addKeyPress (CommandID commandID,
  44359. const KeyPress& newKeyPress,
  44360. int insertIndex = -1);
  44361. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  44362. @see resetToDefaultMapping
  44363. */
  44364. void resetToDefaultMappings();
  44365. /** Resets all key-mappings to the defaults for a particular command.
  44366. @see resetToDefaultMappings
  44367. */
  44368. void resetToDefaultMapping (CommandID commandID);
  44369. /** Removes all keypresses that are assigned to any commands. */
  44370. void clearAllKeyPresses();
  44371. /** Removes all keypresses that are assigned to a particular command. */
  44372. void clearAllKeyPresses (CommandID commandID);
  44373. /** Removes one of the keypresses that are assigned to a command.
  44374. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  44375. which the keyPressIndex refers.
  44376. */
  44377. void removeKeyPress (CommandID commandID, int keyPressIndex);
  44378. /** Removes a keypress from any command that it may be assigned to.
  44379. */
  44380. void removeKeyPress (const KeyPress& keypress);
  44381. /** Returns true if the given command is linked to this key. */
  44382. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const noexcept;
  44383. /** Looks for a command that corresponds to a keypress.
  44384. @returns the UID of the command or 0 if none was found
  44385. */
  44386. CommandID findCommandForKeyPress (const KeyPress& keyPress) const noexcept;
  44387. /** Tries to recreate the mappings from a previously stored state.
  44388. The XML passed in must have been created by the createXml() method.
  44389. If the stored state makes any reference to commands that aren't
  44390. currently available, these will be ignored.
  44391. If the set of mappings being loaded was a set of differences (using createXml (true)),
  44392. then this will call resetToDefaultMappings() and then merge the saved mappings
  44393. on top. If the saved set was created with createXml (false), then this method
  44394. will first clear all existing mappings and load the saved ones as a complete set.
  44395. @returns true if it manages to load the XML correctly
  44396. @see createXml
  44397. */
  44398. bool restoreFromXml (const XmlElement& xmlVersion);
  44399. /** Creates an XML representation of the current mappings.
  44400. This will produce a lump of XML that can be later reloaded using
  44401. restoreFromXml() to recreate the current mapping state.
  44402. The object that is returned must be deleted by the caller.
  44403. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  44404. will be saved into the XML. If it's true, then the XML will
  44405. only store the differences between the current mappings and
  44406. the default mappings you'd get from calling resetToDefaultMappings().
  44407. The advantage of saving a set of differences from the default is that
  44408. if you change the default mappings (in a new version of your app, for
  44409. example), then these will be merged into a user's saved preferences.
  44410. @see restoreFromXml
  44411. */
  44412. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  44413. /** @internal */
  44414. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  44415. /** @internal */
  44416. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  44417. /** @internal */
  44418. void globalFocusChanged (Component* focusedComponent);
  44419. private:
  44420. ApplicationCommandManager* commandManager;
  44421. struct CommandMapping
  44422. {
  44423. CommandID commandID;
  44424. Array <KeyPress> keypresses;
  44425. bool wantsKeyUpDownCallbacks;
  44426. };
  44427. OwnedArray <CommandMapping> mappings;
  44428. struct KeyPressTime
  44429. {
  44430. KeyPress key;
  44431. uint32 timeWhenPressed;
  44432. };
  44433. OwnedArray <KeyPressTime> keysDown;
  44434. void handleMessage (const Message& message);
  44435. void invokeCommand (const CommandID commandID,
  44436. const KeyPress& keyPress,
  44437. const bool isKeyDown,
  44438. const int millisecsSinceKeyPressed,
  44439. Component* const originatingComponent) const;
  44440. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  44441. JUCE_LEAK_DETECTOR (KeyPressMappingSet);
  44442. };
  44443. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44444. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  44445. /**
  44446. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  44447. object.
  44448. @see KeyPressMappingSet
  44449. */
  44450. class JUCE_API KeyMappingEditorComponent : public Component
  44451. {
  44452. public:
  44453. /** Creates a KeyMappingEditorComponent.
  44454. @param mappingSet this is the set of mappings to display and edit. Make sure the
  44455. mappings object is not deleted before this component!
  44456. @param showResetToDefaultButton if true, then at the bottom of the list, the
  44457. component will include a 'reset to defaults' button.
  44458. */
  44459. KeyMappingEditorComponent (KeyPressMappingSet& mappingSet,
  44460. bool showResetToDefaultButton);
  44461. /** Destructor. */
  44462. virtual ~KeyMappingEditorComponent();
  44463. /** Sets up the colours to use for parts of the component.
  44464. @param mainBackground colour to use for most of the background
  44465. @param textColour colour to use for the text
  44466. */
  44467. void setColours (const Colour& mainBackground,
  44468. const Colour& textColour);
  44469. /** Returns the KeyPressMappingSet that this component is acting upon. */
  44470. KeyPressMappingSet& getMappings() const noexcept { return mappings; }
  44471. /** Can be overridden if some commands need to be excluded from the list.
  44472. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  44473. method to decide what to return, but you can override it to handle special cases.
  44474. */
  44475. virtual bool shouldCommandBeIncluded (CommandID commandID);
  44476. /** Can be overridden to indicate that some commands are shown as read-only.
  44477. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  44478. method to decide what to return, but you can override it to handle special cases.
  44479. */
  44480. virtual bool isCommandReadOnly (CommandID commandID);
  44481. /** This can be overridden to let you change the format of the string used
  44482. to describe a keypress.
  44483. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  44484. keys that are triggered by something else externally. If you override the
  44485. method, be sure to let the base class's method handle keys you're not
  44486. interested in.
  44487. */
  44488. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  44489. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  44490. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44491. methods.
  44492. To change the colours of the menu that pops up
  44493. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44494. */
  44495. enum ColourIds
  44496. {
  44497. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  44498. textColourId = 0x100ad01, /**< The colour for the text. */
  44499. };
  44500. /** @internal */
  44501. void parentHierarchyChanged();
  44502. /** @internal */
  44503. void resized();
  44504. private:
  44505. KeyPressMappingSet& mappings;
  44506. TreeView tree;
  44507. TextButton resetButton;
  44508. class TopLevelItem;
  44509. class ChangeKeyButton;
  44510. class MappingItem;
  44511. class CategoryItem;
  44512. class ItemComponent;
  44513. friend class TopLevelItem;
  44514. friend class OwnedArray <ChangeKeyButton>;
  44515. friend class ScopedPointer<TopLevelItem>;
  44516. ScopedPointer<TopLevelItem> treeItem;
  44517. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KeyMappingEditorComponent);
  44518. };
  44519. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44520. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  44521. #endif
  44522. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  44523. #endif
  44524. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44525. #endif
  44526. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  44527. #endif
  44528. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  44529. #endif
  44530. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  44531. #endif
  44532. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  44533. #endif
  44534. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  44535. #endif
  44536. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  44537. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  44538. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  44539. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  44540. /** An object that watches for any movement of a component or any of its parent components.
  44541. This makes it easy to check when a component is moved relative to its top-level
  44542. peer window. The normal Component::moved() method is only called when a component
  44543. moves relative to its immediate parent, and sometimes you want to know if any of
  44544. components higher up the tree have moved (which of course will affect the overall
  44545. position of all their sub-components).
  44546. It also includes a callback that lets you know when the top-level peer is changed.
  44547. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  44548. because they need to keep their custom windows in the right place and respond to
  44549. changes in the peer.
  44550. */
  44551. class JUCE_API ComponentMovementWatcher : public ComponentListener
  44552. {
  44553. public:
  44554. /** Creates a ComponentMovementWatcher to watch a given target component. */
  44555. ComponentMovementWatcher (Component* component);
  44556. /** Destructor. */
  44557. ~ComponentMovementWatcher();
  44558. /** This callback happens when the component that is being watched is moved
  44559. relative to its top-level peer window, or when it is resized. */
  44560. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  44561. /** This callback happens when the component's top-level peer is changed. */
  44562. virtual void componentPeerChanged() = 0;
  44563. /** This callback happens when the component's visibility state changes, possibly due to
  44564. one of its parents being made visible or invisible.
  44565. */
  44566. virtual void componentVisibilityChanged() = 0;
  44567. /** @internal */
  44568. void componentParentHierarchyChanged (Component& component);
  44569. /** @internal */
  44570. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  44571. /** @internal */
  44572. void componentBeingDeleted (Component& component);
  44573. /** @internal */
  44574. void componentVisibilityChanged (Component& component);
  44575. private:
  44576. WeakReference<Component> component;
  44577. ComponentPeer* lastPeer;
  44578. Array <Component*> registeredParentComps;
  44579. bool reentrant, wasShowing;
  44580. Rectangle<int> lastBounds;
  44581. void unregister();
  44582. void registerWithParentComps();
  44583. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentMovementWatcher);
  44584. };
  44585. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  44586. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  44587. #endif
  44588. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  44589. /*** Start of inlined file: juce_GroupComponent.h ***/
  44590. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  44591. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  44592. /**
  44593. A component that draws an outline around itself and has an optional title at
  44594. the top, for drawing an outline around a group of controls.
  44595. */
  44596. class JUCE_API GroupComponent : public Component
  44597. {
  44598. public:
  44599. /** Creates a GroupComponent.
  44600. @param componentName the name to give the component
  44601. @param labelText the text to show at the top of the outline
  44602. */
  44603. GroupComponent (const String& componentName = String::empty,
  44604. const String& labelText = String::empty);
  44605. /** Destructor. */
  44606. ~GroupComponent();
  44607. /** Changes the text that's shown at the top of the component. */
  44608. void setText (const String& newText);
  44609. /** Returns the currently displayed text label. */
  44610. const String getText() const;
  44611. /** Sets the positioning of the text label.
  44612. (The default is Justification::left)
  44613. @see getTextLabelPosition
  44614. */
  44615. void setTextLabelPosition (const Justification& justification);
  44616. /** Returns the current text label position.
  44617. @see setTextLabelPosition
  44618. */
  44619. const Justification getTextLabelPosition() const noexcept { return justification; }
  44620. /** A set of colour IDs to use to change the colour of various aspects of the component.
  44621. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44622. methods.
  44623. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44624. */
  44625. enum ColourIds
  44626. {
  44627. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  44628. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  44629. };
  44630. /** @internal */
  44631. void paint (Graphics& g);
  44632. /** @internal */
  44633. void enablementChanged();
  44634. /** @internal */
  44635. void colourChanged();
  44636. private:
  44637. String text;
  44638. Justification justification;
  44639. JUCE_DECLARE_NON_COPYABLE (GroupComponent);
  44640. };
  44641. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  44642. /*** End of inlined file: juce_GroupComponent.h ***/
  44643. #endif
  44644. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  44645. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  44646. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  44647. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  44648. /*** Start of inlined file: juce_TabbedComponent.h ***/
  44649. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  44650. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  44651. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  44652. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  44653. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  44654. class TabbedButtonBar;
  44655. /** In a TabbedButtonBar, this component is used for each of the buttons.
  44656. If you want to create a TabbedButtonBar with custom tab components, derive
  44657. your component from this class, and override the TabbedButtonBar::createTabButton()
  44658. method to create it instead of the default one.
  44659. @see TabbedButtonBar
  44660. */
  44661. class JUCE_API TabBarButton : public Button
  44662. {
  44663. public:
  44664. /** Creates the tab button. */
  44665. TabBarButton (const String& name, TabbedButtonBar& ownerBar);
  44666. /** Destructor. */
  44667. ~TabBarButton();
  44668. /** Chooses the best length for the tab, given the specified depth.
  44669. If the tab is horizontal, this should return its width, and the depth
  44670. specifies its height. If it's vertical, it should return the height, and
  44671. the depth is actually its width.
  44672. */
  44673. virtual int getBestTabLength (int depth);
  44674. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  44675. void clicked (const ModifierKeys& mods);
  44676. bool hitTest (int x, int y);
  44677. protected:
  44678. friend class TabbedButtonBar;
  44679. TabbedButtonBar& owner;
  44680. int overlapPixels;
  44681. DropShadowEffect shadow;
  44682. /** Returns an area of the component that's safe to draw in.
  44683. This deals with the orientation of the tabs, which affects which side is
  44684. touching the tabbed box's content component.
  44685. */
  44686. const Rectangle<int> getActiveArea();
  44687. /** Returns this tab's index in its tab bar. */
  44688. int getIndex() const;
  44689. private:
  44690. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabBarButton);
  44691. };
  44692. /**
  44693. A vertical or horizontal bar containing tabs that you can select.
  44694. You can use one of these to generate things like a dialog box that has
  44695. tabbed pages you can flip between. Attach a ChangeListener to the
  44696. button bar to be told when the user changes the page.
  44697. An easier method than doing this is to use a TabbedComponent, which
  44698. contains its own TabbedButtonBar and which takes care of the layout
  44699. and other housekeeping.
  44700. @see TabbedComponent
  44701. */
  44702. class JUCE_API TabbedButtonBar : public Component,
  44703. public ChangeBroadcaster
  44704. {
  44705. public:
  44706. /** The placement of the tab-bar
  44707. @see setOrientation, getOrientation
  44708. */
  44709. enum Orientation
  44710. {
  44711. TabsAtTop,
  44712. TabsAtBottom,
  44713. TabsAtLeft,
  44714. TabsAtRight
  44715. };
  44716. /** Creates a TabbedButtonBar with a given placement.
  44717. You can change the orientation later if you need to.
  44718. */
  44719. TabbedButtonBar (Orientation orientation);
  44720. /** Destructor. */
  44721. ~TabbedButtonBar();
  44722. /** Changes the bar's orientation.
  44723. This won't change the bar's actual size - you'll need to do that yourself,
  44724. but this determines which direction the tabs go in, and which side they're
  44725. stuck to.
  44726. */
  44727. void setOrientation (Orientation orientation);
  44728. /** Returns the current orientation.
  44729. @see setOrientation
  44730. */
  44731. Orientation getOrientation() const noexcept { return orientation; }
  44732. /** Changes the minimum scale factor to which the tabs can be compressed when trying to
  44733. fit a lot of tabs on-screen.
  44734. */
  44735. void setMinimumTabScaleFactor (double newMinimumScale);
  44736. /** Deletes all the tabs from the bar.
  44737. @see addTab
  44738. */
  44739. void clearTabs();
  44740. /** Adds a tab to the bar.
  44741. Tabs are added in left-to-right reading order.
  44742. If this is the first tab added, it'll also be automatically selected.
  44743. */
  44744. void addTab (const String& tabName,
  44745. const Colour& tabBackgroundColour,
  44746. int insertIndex = -1);
  44747. /** Changes the name of one of the tabs. */
  44748. void setTabName (int tabIndex,
  44749. const String& newName);
  44750. /** Gets rid of one of the tabs. */
  44751. void removeTab (int tabIndex);
  44752. /** Moves a tab to a new index in the list.
  44753. Pass -1 as the index to move it to the end of the list.
  44754. */
  44755. void moveTab (int currentIndex, int newIndex);
  44756. /** Returns the number of tabs in the bar. */
  44757. int getNumTabs() const;
  44758. /** Returns a list of all the tab names in the bar. */
  44759. const StringArray getTabNames() const;
  44760. /** Changes the currently selected tab.
  44761. This will send a change message and cause a synchronous callback to
  44762. the currentTabChanged() method. (But if the given tab is already selected,
  44763. nothing will be done).
  44764. To deselect all the tabs, use an index of -1.
  44765. */
  44766. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  44767. /** Returns the name of the currently selected tab.
  44768. This could be an empty string if none are selected.
  44769. */
  44770. const String getCurrentTabName() const;
  44771. /** Returns the index of the currently selected tab.
  44772. This could return -1 if none are selected.
  44773. */
  44774. int getCurrentTabIndex() const noexcept { return currentTabIndex; }
  44775. /** Returns the button for a specific tab.
  44776. The button that is returned may be deleted later by this component, so don't hang
  44777. on to the pointer that is returned. A null pointer may be returned if the index is
  44778. out of range.
  44779. */
  44780. TabBarButton* getTabButton (int index) const;
  44781. /** Returns the index of a TabBarButton if it belongs to this bar. */
  44782. int indexOfTabButton (const TabBarButton* button) const;
  44783. /** Callback method to indicate the selected tab has been changed.
  44784. @see setCurrentTabIndex
  44785. */
  44786. virtual void currentTabChanged (int newCurrentTabIndex,
  44787. const String& newCurrentTabName);
  44788. /** Callback method to indicate that the user has right-clicked on a tab.
  44789. (Or ctrl-clicked on the Mac)
  44790. */
  44791. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  44792. /** Returns the colour of a tab.
  44793. This is the colour that was specified in addTab().
  44794. */
  44795. const Colour getTabBackgroundColour (int tabIndex);
  44796. /** Changes the background colour of a tab.
  44797. @see addTab, getTabBackgroundColour
  44798. */
  44799. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  44800. /** A set of colour IDs to use to change the colour of various aspects of the component.
  44801. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44802. methods.
  44803. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44804. */
  44805. enum ColourIds
  44806. {
  44807. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  44808. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  44809. the look and feel will choose an appropriate colour. */
  44810. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  44811. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  44812. this isn't specified, the look and feel will choose an appropriate
  44813. colour. */
  44814. };
  44815. /** @internal */
  44816. void resized();
  44817. /** @internal */
  44818. void lookAndFeelChanged();
  44819. protected:
  44820. /** This creates one of the tabs.
  44821. If you need to use custom tab components, you can override this method and
  44822. return your own class instead of the default.
  44823. */
  44824. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  44825. private:
  44826. Orientation orientation;
  44827. struct TabInfo
  44828. {
  44829. ScopedPointer<TabBarButton> component;
  44830. String name;
  44831. Colour colour;
  44832. };
  44833. OwnedArray <TabInfo> tabs;
  44834. double minimumScale;
  44835. int currentTabIndex;
  44836. class BehindFrontTabComp;
  44837. friend class BehindFrontTabComp;
  44838. friend class ScopedPointer<BehindFrontTabComp>;
  44839. ScopedPointer<BehindFrontTabComp> behindFrontTab;
  44840. ScopedPointer<Button> extraTabsButton;
  44841. void showExtraItemsMenu();
  44842. static void extraItemsMenuCallback (int, TabbedButtonBar*);
  44843. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedButtonBar);
  44844. };
  44845. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  44846. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  44847. /**
  44848. A component with a TabbedButtonBar along one of its sides.
  44849. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  44850. with addTab(), and this will take care of showing the pages for you when the
  44851. user clicks on a different tab.
  44852. @see TabbedButtonBar
  44853. */
  44854. class JUCE_API TabbedComponent : public Component
  44855. {
  44856. public:
  44857. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  44858. Once created, add some tabs with the addTab() method.
  44859. */
  44860. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  44861. /** Destructor. */
  44862. ~TabbedComponent();
  44863. /** Changes the placement of the tabs.
  44864. This will rearrange the layout to place the tabs along the appropriate
  44865. side of this component, and will shift the content component accordingly.
  44866. @see TabbedButtonBar::setOrientation
  44867. */
  44868. void setOrientation (TabbedButtonBar::Orientation orientation);
  44869. /** Returns the current tab placement.
  44870. @see setOrientation, TabbedButtonBar::getOrientation
  44871. */
  44872. TabbedButtonBar::Orientation getOrientation() const noexcept;
  44873. /** Specifies how many pixels wide or high the tab-bar should be.
  44874. If the tabs are placed along the top or bottom, this specified the height
  44875. of the bar; if they're along the left or right edges, it'll be the width
  44876. of the bar.
  44877. */
  44878. void setTabBarDepth (int newDepth);
  44879. /** Returns the current thickness of the tab bar.
  44880. @see setTabBarDepth
  44881. */
  44882. int getTabBarDepth() const noexcept { return tabDepth; }
  44883. /** Specifies the thickness of an outline that should be drawn around the content component.
  44884. If this thickness is > 0, a line will be drawn around the three sides of the content
  44885. component which don't touch the tab-bar, and the content component will be inset by this amount.
  44886. To set the colour of the line, use setColour (outlineColourId, ...).
  44887. */
  44888. void setOutline (int newThickness);
  44889. /** Specifies a gap to leave around the edge of the content component.
  44890. Each edge of the content component will be indented by the given number of pixels.
  44891. */
  44892. void setIndent (int indentThickness);
  44893. /** Removes all the tabs from the bar.
  44894. @see TabbedButtonBar::clearTabs
  44895. */
  44896. void clearTabs();
  44897. /** Adds a tab to the tab-bar.
  44898. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  44899. is true, it will be deleted when the tab is removed or when this object is
  44900. deleted.
  44901. @see TabbedButtonBar::addTab
  44902. */
  44903. void addTab (const String& tabName,
  44904. const Colour& tabBackgroundColour,
  44905. Component* contentComponent,
  44906. bool deleteComponentWhenNotNeeded,
  44907. int insertIndex = -1);
  44908. /** Changes the name of one of the tabs. */
  44909. void setTabName (int tabIndex, const String& newName);
  44910. /** Gets rid of one of the tabs. */
  44911. void removeTab (int tabIndex);
  44912. /** Returns the number of tabs in the bar. */
  44913. int getNumTabs() const;
  44914. /** Returns a list of all the tab names in the bar. */
  44915. const StringArray getTabNames() const;
  44916. /** Returns the content component that was added for the given index.
  44917. Be sure not to use or delete the components that are returned, as this may interfere
  44918. with the TabbedComponent's use of them.
  44919. */
  44920. Component* getTabContentComponent (int tabIndex) const noexcept;
  44921. /** Returns the colour of one of the tabs. */
  44922. const Colour getTabBackgroundColour (int tabIndex) const noexcept;
  44923. /** Changes the background colour of one of the tabs. */
  44924. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  44925. /** Changes the currently-selected tab.
  44926. To deselect all the tabs, pass -1 as the index.
  44927. @see TabbedButtonBar::setCurrentTabIndex
  44928. */
  44929. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  44930. /** Returns the index of the currently selected tab.
  44931. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  44932. */
  44933. int getCurrentTabIndex() const;
  44934. /** Returns the name of the currently selected tab.
  44935. @see addTab, TabbedButtonBar::getCurrentTabName()
  44936. */
  44937. const String getCurrentTabName() const;
  44938. /** Returns the current component that's filling the panel.
  44939. This will return 0 if there isn't one.
  44940. */
  44941. Component* getCurrentContentComponent() const noexcept { return panelComponent; }
  44942. /** Callback method to indicate the selected tab has been changed.
  44943. @see setCurrentTabIndex
  44944. */
  44945. virtual void currentTabChanged (int newCurrentTabIndex,
  44946. const String& newCurrentTabName);
  44947. /** Callback method to indicate that the user has right-clicked on a tab.
  44948. (Or ctrl-clicked on the Mac)
  44949. */
  44950. virtual void popupMenuClickOnTab (int tabIndex,
  44951. const String& tabName);
  44952. /** Returns the tab button bar component that is being used.
  44953. */
  44954. TabbedButtonBar& getTabbedButtonBar() const noexcept { return *tabs; }
  44955. /** A set of colour IDs to use to change the colour of various aspects of the component.
  44956. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44957. methods.
  44958. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44959. */
  44960. enum ColourIds
  44961. {
  44962. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  44963. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  44964. (See setOutline) */
  44965. };
  44966. /** @internal */
  44967. void paint (Graphics& g);
  44968. /** @internal */
  44969. void resized();
  44970. /** @internal */
  44971. void lookAndFeelChanged();
  44972. protected:
  44973. /** This creates one of the tab buttons.
  44974. If you need to use custom tab components, you can override this method and
  44975. return your own class instead of the default.
  44976. */
  44977. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  44978. /** @internal */
  44979. ScopedPointer<TabbedButtonBar> tabs;
  44980. private:
  44981. Array <WeakReference<Component> > contentComponents;
  44982. WeakReference<Component> panelComponent;
  44983. int tabDepth;
  44984. int outlineThickness, edgeIndent;
  44985. class ButtonBar;
  44986. friend class ButtonBar;
  44987. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  44988. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedComponent);
  44989. };
  44990. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  44991. /*** End of inlined file: juce_TabbedComponent.h ***/
  44992. /*** Start of inlined file: juce_DocumentWindow.h ***/
  44993. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  44994. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  44995. /*** Start of inlined file: juce_MenuBarModel.h ***/
  44996. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  44997. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  44998. /**
  44999. A class for controlling MenuBar components.
  45000. This class is used to tell a MenuBar what menus to show, and to respond
  45001. to a menu being selected.
  45002. @see MenuBarModel::Listener, MenuBarComponent, PopupMenu
  45003. */
  45004. class JUCE_API MenuBarModel : private AsyncUpdater,
  45005. private ApplicationCommandManagerListener
  45006. {
  45007. public:
  45008. MenuBarModel() noexcept;
  45009. /** Destructor. */
  45010. virtual ~MenuBarModel();
  45011. /** Call this when some of your menu items have changed.
  45012. This method will cause a callback to any MenuBarListener objects that
  45013. are registered with this model.
  45014. If this model is displaying items from an ApplicationCommandManager, you
  45015. can use the setApplicationCommandManagerToWatch() method to cause
  45016. change messages to be sent automatically when the ApplicationCommandManager
  45017. is changed.
  45018. @see addListener, removeListener, MenuBarListener
  45019. */
  45020. void menuItemsChanged();
  45021. /** Tells the menu bar to listen to the specified command manager, and to update
  45022. itself when the commands change.
  45023. This will also allow it to flash a menu name when a command from that menu
  45024. is invoked using a keystroke.
  45025. */
  45026. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) noexcept;
  45027. /** A class to receive callbacks when a MenuBarModel changes.
  45028. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  45029. */
  45030. class JUCE_API Listener
  45031. {
  45032. public:
  45033. /** Destructor. */
  45034. virtual ~Listener() {}
  45035. /** This callback is made when items are changed in the menu bar model.
  45036. */
  45037. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  45038. /** This callback is made when an application command is invoked that
  45039. is represented by one of the items in the menu bar model.
  45040. */
  45041. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  45042. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  45043. };
  45044. /** Registers a listener for callbacks when the menu items in this model change.
  45045. The listener object will get callbacks when this object's menuItemsChanged()
  45046. method is called.
  45047. @see removeListener
  45048. */
  45049. void addListener (Listener* listenerToAdd) noexcept;
  45050. /** Removes a listener.
  45051. @see addListener
  45052. */
  45053. void removeListener (Listener* listenerToRemove) noexcept;
  45054. /** This method must return a list of the names of the menus. */
  45055. virtual const StringArray getMenuBarNames() = 0;
  45056. /** This should return the popup menu to display for a given top-level menu.
  45057. @param topLevelMenuIndex the index of the top-level menu to show
  45058. @param menuName the name of the top-level menu item to show
  45059. */
  45060. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  45061. const String& menuName) = 0;
  45062. /** This is called when a menu item has been clicked on.
  45063. @param menuItemID the item ID of the PopupMenu item that was selected
  45064. @param topLevelMenuIndex the index of the top-level menu from which the item was
  45065. chosen (just in case you've used duplicate ID numbers
  45066. on more than one of the popup menus)
  45067. */
  45068. virtual void menuItemSelected (int menuItemID,
  45069. int topLevelMenuIndex) = 0;
  45070. #if JUCE_MAC || DOXYGEN
  45071. /** MAC ONLY - Sets the model that is currently being shown as the main
  45072. menu bar at the top of the screen on the Mac.
  45073. You can pass 0 to stop the current model being displayed. Be careful
  45074. not to delete a model while it is being used.
  45075. An optional extra menu can be specified, containing items to add to the top of
  45076. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  45077. an apple, it's the one next to it, with your application's name at the top
  45078. and the services menu etc on it). When one of these items is selected, the
  45079. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  45080. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  45081. object then newMenuBarModel must be non-null.
  45082. */
  45083. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  45084. const PopupMenu* extraAppleMenuItems = nullptr);
  45085. /** MAC ONLY - Returns the menu model that is currently being shown as
  45086. the main menu bar.
  45087. */
  45088. static MenuBarModel* getMacMainMenu();
  45089. #endif
  45090. /** @internal */
  45091. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  45092. /** @internal */
  45093. void applicationCommandListChanged();
  45094. /** @internal */
  45095. void handleAsyncUpdate();
  45096. private:
  45097. ApplicationCommandManager* manager;
  45098. ListenerList <Listener> listeners;
  45099. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarModel);
  45100. };
  45101. /** This typedef is just for compatibility with old code - newer code should use the MenuBarModel::Listener class directly. */
  45102. typedef MenuBarModel::Listener MenuBarModelListener;
  45103. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  45104. /*** End of inlined file: juce_MenuBarModel.h ***/
  45105. /**
  45106. A resizable window with a title bar and maximise, minimise and close buttons.
  45107. This subclass of ResizableWindow creates a fairly standard type of window with
  45108. a title bar and various buttons. The name of the component is shown in the
  45109. title bar, and an icon can optionally be specified with setIcon().
  45110. All the methods available to a ResizableWindow are also available to this,
  45111. so it can easily be made resizable, minimised, maximised, etc.
  45112. It's not advisable to add child components directly to a DocumentWindow: put them
  45113. inside your content component instead. And overriding methods like resized(), moved(), etc
  45114. is also not recommended - instead override these methods for your content component.
  45115. (If for some obscure reason you do need to override these methods, always remember to
  45116. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  45117. decorations correctly).
  45118. You can also automatically add a menu bar to the window, using the setMenuBar()
  45119. method.
  45120. @see ResizableWindow, DialogWindow
  45121. */
  45122. class JUCE_API DocumentWindow : public ResizableWindow
  45123. {
  45124. public:
  45125. /** The set of available button-types that can be put on the title bar.
  45126. @see setTitleBarButtonsRequired
  45127. */
  45128. enum TitleBarButtons
  45129. {
  45130. minimiseButton = 1,
  45131. maximiseButton = 2,
  45132. closeButton = 4,
  45133. /** A combination of all the buttons above. */
  45134. allButtons = 7
  45135. };
  45136. /** Creates a DocumentWindow.
  45137. @param name the name to give the component - this is also
  45138. the title shown at the top of the window. To change
  45139. this later, use setName()
  45140. @param backgroundColour the colour to use for filling the window's background.
  45141. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  45142. should be shown on the title bar. This value is a bitwise
  45143. combination of values from the TitleBarButtons enum. Note
  45144. that it can be "allButtons" to get them all. You
  45145. can change this later with the setTitleBarButtonsRequired()
  45146. method, which can also specify where they are positioned.
  45147. @param addToDesktop if true, the window will be automatically added to the
  45148. desktop; if false, you can use it as a child component
  45149. @see TitleBarButtons
  45150. */
  45151. DocumentWindow (const String& name,
  45152. const Colour& backgroundColour,
  45153. int requiredButtons,
  45154. bool addToDesktop = true);
  45155. /** Destructor.
  45156. If a content component has been set with setContentOwned(), it will be deleted.
  45157. */
  45158. ~DocumentWindow();
  45159. /** Changes the component's name.
  45160. (This is overridden from Component::setName() to cause a repaint, as
  45161. the name is what gets drawn across the window's title bar).
  45162. */
  45163. void setName (const String& newName);
  45164. /** Sets an icon to show in the title bar, next to the title.
  45165. A copy is made internally of the image, so the caller can delete the
  45166. image after calling this. If 0 is passed-in, any existing icon will be
  45167. removed.
  45168. */
  45169. void setIcon (const Image& imageToUse);
  45170. /** Changes the height of the title-bar. */
  45171. void setTitleBarHeight (int newHeight);
  45172. /** Returns the current title bar height. */
  45173. int getTitleBarHeight() const;
  45174. /** Changes the set of title-bar buttons being shown.
  45175. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  45176. should be shown on the title bar. This value is a bitwise
  45177. combination of values from the TitleBarButtons enum. Note
  45178. that it can be "allButtons" to get them all.
  45179. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  45180. left side of the bar; if false, they'll be placed at the right
  45181. */
  45182. void setTitleBarButtonsRequired (int requiredButtons,
  45183. bool positionTitleBarButtonsOnLeft);
  45184. /** Sets whether the title should be centred within the window.
  45185. If true, the title text is shown in the middle of the title-bar; if false,
  45186. it'll be shown at the left of the bar.
  45187. */
  45188. void setTitleBarTextCentred (bool textShouldBeCentred);
  45189. /** Creates a menu inside this window.
  45190. @param menuBarModel this specifies a MenuBarModel that should be used to
  45191. generate the contents of a menu bar that will be placed
  45192. just below the title bar, and just above any content
  45193. component. If this value is zero, any existing menu bar
  45194. will be removed from the component; if non-zero, one will
  45195. be added if it's required.
  45196. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  45197. or less to use the look-and-feel's default size.
  45198. */
  45199. void setMenuBar (MenuBarModel* menuBarModel,
  45200. int menuBarHeight = 0);
  45201. /** Returns the current menu bar component, or null if there isn't one.
  45202. This is probably a MenuBarComponent, unless a custom one has been set using
  45203. setMenuBarComponent().
  45204. */
  45205. Component* getMenuBarComponent() const noexcept;
  45206. /** Replaces the current menu bar with a custom component.
  45207. The component will be owned and deleted by the document window.
  45208. */
  45209. void setMenuBarComponent (Component* newMenuBarComponent);
  45210. /** This method is called when the user tries to close the window.
  45211. This is triggered by the user clicking the close button, or using some other
  45212. OS-specific key shortcut or OS menu for getting rid of a window.
  45213. If the window is just a pop-up, you should override this closeButtonPressed()
  45214. method and make it delete the window in whatever way is appropriate for your
  45215. app. E.g. you might just want to call "delete this".
  45216. If your app is centred around this window such that the whole app should quit when
  45217. the window is closed, then you will probably want to use this method as an opportunity
  45218. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  45219. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  45220. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  45221. or closing it via the taskbar icon on Windows).
  45222. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  45223. redirects it to call this method, so any methods of closing the window that are
  45224. caught by userTriedToCloseWindow() will also end up here).
  45225. */
  45226. virtual void closeButtonPressed();
  45227. /** Callback that is triggered when the minimise button is pressed.
  45228. The default implementation of this calls ResizableWindow::setMinimised(), but
  45229. you can override it to do more customised behaviour.
  45230. */
  45231. virtual void minimiseButtonPressed();
  45232. /** Callback that is triggered when the maximise button is pressed, or when the
  45233. title-bar is double-clicked.
  45234. The default implementation of this calls ResizableWindow::setFullScreen(), but
  45235. you can override it to do more customised behaviour.
  45236. */
  45237. virtual void maximiseButtonPressed();
  45238. /** Returns the close button, (or 0 if there isn't one). */
  45239. Button* getCloseButton() const noexcept;
  45240. /** Returns the minimise button, (or 0 if there isn't one). */
  45241. Button* getMinimiseButton() const noexcept;
  45242. /** Returns the maximise button, (or 0 if there isn't one). */
  45243. Button* getMaximiseButton() const noexcept;
  45244. /** A set of colour IDs to use to change the colour of various aspects of the window.
  45245. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45246. methods.
  45247. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45248. */
  45249. enum ColourIds
  45250. {
  45251. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  45252. and feel class how this is used. */
  45253. };
  45254. #ifndef DOXYGEN
  45255. /** @internal */
  45256. void paint (Graphics& g);
  45257. /** @internal */
  45258. void resized();
  45259. /** @internal */
  45260. void lookAndFeelChanged();
  45261. /** @internal */
  45262. const BorderSize<int> getBorderThickness();
  45263. /** @internal */
  45264. const BorderSize<int> getContentComponentBorder();
  45265. /** @internal */
  45266. void mouseDoubleClick (const MouseEvent& e);
  45267. /** @internal */
  45268. void userTriedToCloseWindow();
  45269. /** @internal */
  45270. void activeWindowStatusChanged();
  45271. /** @internal */
  45272. int getDesktopWindowStyleFlags() const;
  45273. /** @internal */
  45274. void parentHierarchyChanged();
  45275. /** @internal */
  45276. const Rectangle<int> getTitleBarArea();
  45277. #endif
  45278. private:
  45279. int titleBarHeight, menuBarHeight, requiredButtons;
  45280. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  45281. ScopedPointer <Button> titleBarButtons [3];
  45282. Image titleBarIcon;
  45283. ScopedPointer <Component> menuBar;
  45284. MenuBarModel* menuBarModel;
  45285. class ButtonListenerProxy;
  45286. friend class ScopedPointer <ButtonListenerProxy>;
  45287. ScopedPointer <ButtonListenerProxy> buttonListener;
  45288. void repaintTitleBar();
  45289. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DocumentWindow);
  45290. };
  45291. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  45292. /*** End of inlined file: juce_DocumentWindow.h ***/
  45293. class MultiDocumentPanel;
  45294. class MDITabbedComponentInternal;
  45295. /**
  45296. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  45297. component.
  45298. It's like a normal DocumentWindow but has some extra functionality to make sure
  45299. everything works nicely inside a MultiDocumentPanel.
  45300. @see MultiDocumentPanel
  45301. */
  45302. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  45303. {
  45304. public:
  45305. /**
  45306. */
  45307. MultiDocumentPanelWindow (const Colour& backgroundColour);
  45308. /** Destructor. */
  45309. ~MultiDocumentPanelWindow();
  45310. /** @internal */
  45311. void maximiseButtonPressed();
  45312. /** @internal */
  45313. void closeButtonPressed();
  45314. /** @internal */
  45315. void activeWindowStatusChanged();
  45316. /** @internal */
  45317. void broughtToFront();
  45318. private:
  45319. void updateOrder();
  45320. MultiDocumentPanel* getOwner() const noexcept;
  45321. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanelWindow);
  45322. };
  45323. /**
  45324. A component that contains a set of other components either in floating windows
  45325. or tabs.
  45326. This acts as a panel that can be used to hold a set of open document windows, with
  45327. different layout modes.
  45328. Use addDocument() and closeDocument() to add or remove components from the
  45329. panel - never use any of the Component methods to access the panel's child
  45330. components directly, as these are managed internally.
  45331. */
  45332. class JUCE_API MultiDocumentPanel : public Component,
  45333. private ComponentListener
  45334. {
  45335. public:
  45336. /** Creates an empty panel.
  45337. Use addDocument() and closeDocument() to add or remove components from the
  45338. panel - never use any of the Component methods to access the panel's child
  45339. components directly, as these are managed internally.
  45340. */
  45341. MultiDocumentPanel();
  45342. /** Destructor.
  45343. When deleted, this will call closeAllDocuments (false) to make sure all its
  45344. components are deleted. If you need to make sure all documents are saved
  45345. before closing, then you should call closeAllDocuments (true) and check that
  45346. it returns true before deleting the panel.
  45347. */
  45348. ~MultiDocumentPanel();
  45349. /** Tries to close all the documents.
  45350. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  45351. be called for each open document, and any of these calls fails, this method
  45352. will stop and return false, leaving some documents still open.
  45353. If checkItsOkToCloseFirst is false, then all documents will be closed
  45354. unconditionally.
  45355. @see closeDocument
  45356. */
  45357. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  45358. /** Adds a document component to the panel.
  45359. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  45360. this will fail and return false. (If it does fail, the component passed-in will not be
  45361. deleted, even if deleteWhenRemoved was set to true).
  45362. The MultiDocumentPanel will deal with creating a window border to go around your component,
  45363. so just pass in the bare content component here, no need to give it a ResizableWindow
  45364. or DocumentWindow.
  45365. @param component the component to add
  45366. @param backgroundColour the background colour to use to fill the component's
  45367. window or tab
  45368. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  45369. or closeAllDocuments(), then it will be deleted. If false, then
  45370. the caller must handle the component's deletion
  45371. */
  45372. bool addDocument (Component* component,
  45373. const Colour& backgroundColour,
  45374. bool deleteWhenRemoved);
  45375. /** Closes one of the documents.
  45376. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  45377. be called, and if it fails, this method will return false without closing the
  45378. document.
  45379. If checkItsOkToCloseFirst is false, then the documents will be closed
  45380. unconditionally.
  45381. The component will be deleted if the deleteWhenRemoved parameter was set to
  45382. true when it was added with addDocument.
  45383. @see addDocument, closeAllDocuments
  45384. */
  45385. bool closeDocument (Component* component,
  45386. bool checkItsOkToCloseFirst);
  45387. /** Returns the number of open document windows.
  45388. @see getDocument
  45389. */
  45390. int getNumDocuments() const noexcept;
  45391. /** Returns one of the open documents.
  45392. The order of the documents in this array may change when they are added, removed
  45393. or moved around.
  45394. @see getNumDocuments
  45395. */
  45396. Component* getDocument (int index) const noexcept;
  45397. /** Returns the document component that is currently focused or on top.
  45398. If currently using floating windows, then this will be the component in the currently
  45399. active window, or the top component if none are active.
  45400. If it's currently in tabbed mode, then it'll return the component in the active tab.
  45401. @see setActiveDocument
  45402. */
  45403. Component* getActiveDocument() const noexcept;
  45404. /** Makes one of the components active and brings it to the top.
  45405. @see getActiveDocument
  45406. */
  45407. void setActiveDocument (Component* component);
  45408. /** Callback which gets invoked when the currently-active document changes. */
  45409. virtual void activeDocumentChanged();
  45410. /** Sets a limit on how many windows can be open at once.
  45411. If this is zero or less there's no limit (the default). addDocument() will fail
  45412. if this number is exceeded.
  45413. */
  45414. void setMaximumNumDocuments (int maximumNumDocuments);
  45415. /** Sets an option to make the document fullscreen if there's only one document open.
  45416. If set to true, then if there's only one document, it'll fill the whole of this
  45417. component without tabs or a window border. If false, then tabs or a window
  45418. will always be shown, even if there's only one document. If there's more than
  45419. one document open, then this option makes no difference.
  45420. */
  45421. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  45422. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  45423. */
  45424. bool isFullscreenWhenOneDocument() const noexcept;
  45425. /** The different layout modes available. */
  45426. enum LayoutMode
  45427. {
  45428. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  45429. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  45430. };
  45431. /** Changes the panel's mode.
  45432. @see LayoutMode, getLayoutMode
  45433. */
  45434. void setLayoutMode (LayoutMode newLayoutMode);
  45435. /** Returns the current layout mode. */
  45436. LayoutMode getLayoutMode() const noexcept { return mode; }
  45437. /** Sets the background colour for the whole panel.
  45438. Each document has its own background colour, but this is the one used to fill the areas
  45439. behind them.
  45440. */
  45441. void setBackgroundColour (const Colour& newBackgroundColour);
  45442. /** Returns the current background colour.
  45443. @see setBackgroundColour
  45444. */
  45445. const Colour& getBackgroundColour() const noexcept { return backgroundColour; }
  45446. /** A subclass must override this to say whether its currently ok for a document
  45447. to be closed.
  45448. This method is called by closeDocument() and closeAllDocuments() to indicate that
  45449. a document should be saved if possible, ready for it to be closed.
  45450. If this method returns true, then it means the document is ok and can be closed.
  45451. If it returns false, then it means that the closeDocument() method should stop
  45452. and not close.
  45453. Normally, you'd use this method to ask the user if they want to save any changes,
  45454. then return true if the save operation went ok. If the user cancelled the save
  45455. operation you could return false here to abort the close operation.
  45456. If your component is based on the FileBasedDocument class, then you'd probably want
  45457. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  45458. FileBasedDocument::savedOk
  45459. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  45460. */
  45461. virtual bool tryToCloseDocument (Component* component) = 0;
  45462. /** Creates a new window to be used for a document.
  45463. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  45464. but you might want to override it to return a custom component.
  45465. */
  45466. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  45467. /** @internal */
  45468. void paint (Graphics& g);
  45469. /** @internal */
  45470. void resized();
  45471. /** @internal */
  45472. void componentNameChanged (Component&);
  45473. private:
  45474. LayoutMode mode;
  45475. Array <Component*> components;
  45476. ScopedPointer<TabbedComponent> tabComponent;
  45477. Colour backgroundColour;
  45478. int maximumNumDocuments, numDocsBeforeTabsUsed;
  45479. friend class MultiDocumentPanelWindow;
  45480. friend class MDITabbedComponentInternal;
  45481. Component* getContainerComp (Component* c) const;
  45482. void updateOrder();
  45483. void addWindow (Component* component);
  45484. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanel);
  45485. };
  45486. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  45487. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  45488. #endif
  45489. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  45490. #endif
  45491. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  45492. #endif
  45493. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  45494. /*** Start of inlined file: juce_ResizableEdgeComponent.h ***/
  45495. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  45496. #define __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  45497. /**
  45498. A component that resizes its parent component when dragged.
  45499. This component forms a bar along one edge of a component, allowing it to
  45500. be dragged by that edges to resize it.
  45501. To use it, just add it to your component, positioning it along the appropriate
  45502. edge. Make sure you reposition the resizer component each time the parent's size
  45503. changes, to keep it in the correct position.
  45504. @see ResizbleBorderComponent, ResizableCornerComponent
  45505. */
  45506. class JUCE_API ResizableEdgeComponent : public Component
  45507. {
  45508. public:
  45509. enum Edge
  45510. {
  45511. leftEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's left-hand edge. */
  45512. rightEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's right-hand edge. */
  45513. topEdge, /**< Indicates a horizontal bar that can be dragged up/down to move the top of the component. */
  45514. bottomEdge /**< Indicates a horizontal bar that can be dragged up/down to move the bottom of the component. */
  45515. };
  45516. /** Creates a resizer bar.
  45517. Pass in the target component which you want to be resized when this one is
  45518. dragged. The target component will usually be this component's parent, but this
  45519. isn't mandatory.
  45520. Remember that when the target component is resized, it'll need to move and
  45521. resize this component to keep it in place, as this won't happen automatically.
  45522. If the constrainer parameter is non-zero, then this object will be used to enforce
  45523. limits on the size and position that the component can be stretched to. Make sure
  45524. that the constrainer isn't deleted while still in use by this object.
  45525. @see ComponentBoundsConstrainer
  45526. */
  45527. ResizableEdgeComponent (Component* componentToResize,
  45528. ComponentBoundsConstrainer* constrainer,
  45529. Edge edgeToResize);
  45530. /** Destructor. */
  45531. ~ResizableEdgeComponent();
  45532. bool isVertical() const noexcept;
  45533. protected:
  45534. /** @internal */
  45535. void paint (Graphics& g);
  45536. /** @internal */
  45537. void mouseDown (const MouseEvent& e);
  45538. /** @internal */
  45539. void mouseDrag (const MouseEvent& e);
  45540. /** @internal */
  45541. void mouseUp (const MouseEvent& e);
  45542. private:
  45543. WeakReference<Component> component;
  45544. ComponentBoundsConstrainer* constrainer;
  45545. Rectangle<int> originalBounds;
  45546. const Edge edge;
  45547. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableEdgeComponent);
  45548. };
  45549. #endif // __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  45550. /*** End of inlined file: juce_ResizableEdgeComponent.h ***/
  45551. #endif
  45552. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  45553. #endif
  45554. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  45555. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  45556. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  45557. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  45558. /**
  45559. For laying out a set of components, where the components have preferred sizes
  45560. and size limits, but where they are allowed to stretch to fill the available
  45561. space.
  45562. For example, if you have a component containing several other components, and
  45563. each one should be given a share of the total size, you could use one of these
  45564. to resize the child components when the parent component is resized. Then
  45565. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  45566. A StretchableLayoutManager operates only in one dimension, so if you have a set
  45567. of components stacked vertically on top of each other, you'd use one to manage their
  45568. heights. To build up complex arrangements of components, e.g. for applications
  45569. with multiple nested panels, you would use more than one StretchableLayoutManager.
  45570. E.g. by using two (one vertical, one horizontal), you could create a resizable
  45571. spreadsheet-style table.
  45572. E.g.
  45573. @code
  45574. class MyComp : public Component
  45575. {
  45576. StretchableLayoutManager myLayout;
  45577. MyComp()
  45578. {
  45579. myLayout.setItemLayout (0, // for item 0
  45580. 50, 100, // must be between 50 and 100 pixels in size
  45581. -0.6); // and its preferred size is 60% of the total available space
  45582. myLayout.setItemLayout (1, // for item 1
  45583. -0.2, -0.6, // size must be between 20% and 60% of the available space
  45584. 50); // and its preferred size is 50 pixels
  45585. }
  45586. void resized()
  45587. {
  45588. // make a list of two of our child components that we want to reposition
  45589. Component* comps[] = { myComp1, myComp2 };
  45590. // this will position the 2 components, one above the other, to fit
  45591. // vertically into the rectangle provided.
  45592. myLayout.layOutComponents (comps, 2,
  45593. 0, 0, getWidth(), getHeight(),
  45594. true);
  45595. }
  45596. };
  45597. @endcode
  45598. @see StretchableLayoutResizerBar
  45599. */
  45600. class JUCE_API StretchableLayoutManager
  45601. {
  45602. public:
  45603. /** Creates an empty layout.
  45604. You'll need to add some item properties to the layout before it can be used
  45605. to resize things - see setItemLayout().
  45606. */
  45607. StretchableLayoutManager();
  45608. /** Destructor. */
  45609. ~StretchableLayoutManager();
  45610. /** For a numbered item, this sets its size limits and preferred size.
  45611. @param itemIndex the index of the item to change.
  45612. @param minimumSize the minimum size that this item is allowed to be - a positive number
  45613. indicates an absolute size in pixels. A negative number indicates a
  45614. proportion of the available space (e.g -0.5 is 50%)
  45615. @param maximumSize the maximum size that this item is allowed to be - a positive number
  45616. indicates an absolute size in pixels. A negative number indicates a
  45617. proportion of the available space
  45618. @param preferredSize the size that this item would like to be, if there's enough room. A
  45619. positive number indicates an absolute size in pixels. A negative number
  45620. indicates a proportion of the available space
  45621. @see getItemLayout
  45622. */
  45623. void setItemLayout (int itemIndex,
  45624. double minimumSize,
  45625. double maximumSize,
  45626. double preferredSize);
  45627. /** For a numbered item, this returns its size limits and preferred size.
  45628. @param itemIndex the index of the item.
  45629. @param minimumSize the minimum size that this item is allowed to be - a positive number
  45630. indicates an absolute size in pixels. A negative number indicates a
  45631. proportion of the available space (e.g -0.5 is 50%)
  45632. @param maximumSize the maximum size that this item is allowed to be - a positive number
  45633. indicates an absolute size in pixels. A negative number indicates a
  45634. proportion of the available space
  45635. @param preferredSize the size that this item would like to be, if there's enough room. A
  45636. positive number indicates an absolute size in pixels. A negative number
  45637. indicates a proportion of the available space
  45638. @returns false if the item's properties hadn't been set
  45639. @see setItemLayout
  45640. */
  45641. bool getItemLayout (int itemIndex,
  45642. double& minimumSize,
  45643. double& maximumSize,
  45644. double& preferredSize) const;
  45645. /** Clears all the properties that have been set with setItemLayout() and resets
  45646. this object to its initial state.
  45647. */
  45648. void clearAllItems();
  45649. /** Takes a set of components that correspond to the layout's items, and positions
  45650. them to fill a space.
  45651. This will try to give each item its preferred size, whether that's a relative size
  45652. or an absolute one.
  45653. @param components an array of components that correspond to each of the
  45654. numbered items that the StretchableLayoutManager object
  45655. has been told about with setItemLayout()
  45656. @param numComponents the number of components in the array that is passed-in. This
  45657. should be the same as the number of items this object has been
  45658. told about.
  45659. @param x the left of the rectangle in which the components should
  45660. be laid out
  45661. @param y the top of the rectangle in which the components should
  45662. be laid out
  45663. @param width the width of the rectangle in which the components should
  45664. be laid out
  45665. @param height the height of the rectangle in which the components should
  45666. be laid out
  45667. @param vertically if true, the components will be positioned in a vertical stack,
  45668. so that they fill the height of the rectangle. If false, they
  45669. will be placed side-by-side in a horizontal line, filling the
  45670. available width
  45671. @param resizeOtherDimension if true, this means that the components will have their
  45672. other dimension resized to fit the space - i.e. if the 'vertically'
  45673. parameter is true, their x-positions and widths are adjusted to fit
  45674. the x and width parameters; if 'vertically' is false, their y-positions
  45675. and heights are adjusted to fit the y and height parameters.
  45676. */
  45677. void layOutComponents (Component** components,
  45678. int numComponents,
  45679. int x, int y, int width, int height,
  45680. bool vertically,
  45681. bool resizeOtherDimension);
  45682. /** Returns the current position of one of the items.
  45683. This is only a valid call after layOutComponents() has been called, as it
  45684. returns the last position that this item was placed at. If the layout was
  45685. vertical, the value returned will be the y position of the top of the item,
  45686. relative to the top of the rectangle in which the items were placed (so for
  45687. example, item 0 will always have position of 0, even in the rectangle passed
  45688. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  45689. the position returned is the item's left-hand position, again relative to the
  45690. x position of the rectangle used.
  45691. @see getItemCurrentSize, setItemPosition
  45692. */
  45693. int getItemCurrentPosition (int itemIndex) const;
  45694. /** Returns the current size of one of the items.
  45695. This is only meaningful after layOutComponents() has been called, as it
  45696. returns the last size that this item was given. If the layout was done
  45697. vertically, it'll return the item's height in pixels; if it was horizontal,
  45698. it'll return its width.
  45699. @see getItemCurrentRelativeSize
  45700. */
  45701. int getItemCurrentAbsoluteSize (int itemIndex) const;
  45702. /** Returns the current size of one of the items.
  45703. This is only meaningful after layOutComponents() has been called, as it
  45704. returns the last size that this item was given. If the layout was done
  45705. vertically, it'll return a negative value representing the item's height relative
  45706. to the last size used for laying the components out; if the layout was done
  45707. horizontally it'll be the proportion of its width.
  45708. @see getItemCurrentAbsoluteSize
  45709. */
  45710. double getItemCurrentRelativeSize (int itemIndex) const;
  45711. /** Moves one of the items, shifting along any other items as necessary in
  45712. order to get it to the desired position.
  45713. Calling this method will also update the preferred sizes of the items it
  45714. shuffles along, so that they reflect their new positions.
  45715. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  45716. about when it's dragged).
  45717. @param itemIndex the item to move
  45718. @param newPosition the absolute position that you'd like this item to move
  45719. to. The item might not be able to always reach exactly this position,
  45720. because other items may have minimum sizes that constrain how
  45721. far it can go
  45722. */
  45723. void setItemPosition (int itemIndex,
  45724. int newPosition);
  45725. private:
  45726. struct ItemLayoutProperties
  45727. {
  45728. int itemIndex;
  45729. int currentSize;
  45730. double minSize, maxSize, preferredSize;
  45731. };
  45732. OwnedArray <ItemLayoutProperties> items;
  45733. int totalSize;
  45734. static int sizeToRealSize (double size, int totalSpace);
  45735. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  45736. void setTotalSize (int newTotalSize);
  45737. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  45738. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  45739. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  45740. void updatePrefSizesToMatchCurrentPositions();
  45741. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutManager);
  45742. };
  45743. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  45744. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  45745. #endif
  45746. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45747. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  45748. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45749. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45750. /**
  45751. A component that acts as one of the vertical or horizontal bars you see being
  45752. used to resize panels in a window.
  45753. One of these acts with a StretchableLayoutManager to resize the other components.
  45754. @see StretchableLayoutManager
  45755. */
  45756. class JUCE_API StretchableLayoutResizerBar : public Component
  45757. {
  45758. public:
  45759. /** Creates a resizer bar for use on a specified layout.
  45760. @param layoutToUse the layout that will be affected when this bar
  45761. is dragged
  45762. @param itemIndexInLayout the item index in the layout that corresponds to
  45763. this bar component. You'll need to set up the item
  45764. properties in a suitable way for a divider bar, e.g.
  45765. for an 8-pixel wide bar which, you could call
  45766. myLayout->setItemLayout (barIndex, 8, 8, 8)
  45767. @param isBarVertical true if it's an upright bar that you drag left and
  45768. right; false for a horizontal one that you drag up and
  45769. down
  45770. */
  45771. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  45772. int itemIndexInLayout,
  45773. bool isBarVertical);
  45774. /** Destructor. */
  45775. ~StretchableLayoutResizerBar();
  45776. /** This is called when the bar is dragged.
  45777. This method must update the positions of any components whose position is
  45778. determined by the StretchableLayoutManager, because they might have just
  45779. moved.
  45780. The default implementation calls the resized() method of this component's
  45781. parent component, because that's often where you're likely to apply the
  45782. layout, but it can be overridden for more specific needs.
  45783. */
  45784. virtual void hasBeenMoved();
  45785. /** @internal */
  45786. void paint (Graphics& g);
  45787. /** @internal */
  45788. void mouseDown (const MouseEvent& e);
  45789. /** @internal */
  45790. void mouseDrag (const MouseEvent& e);
  45791. private:
  45792. StretchableLayoutManager* layout;
  45793. int itemIndex, mouseDownPos;
  45794. bool isVertical;
  45795. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutResizerBar);
  45796. };
  45797. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45798. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  45799. #endif
  45800. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45801. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  45802. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45803. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45804. /**
  45805. A utility class for fitting a set of objects whose sizes can vary between
  45806. a minimum and maximum size, into a space.
  45807. This is a trickier algorithm than it would first seem, so I've put it in this
  45808. class to allow it to be shared by various bits of code.
  45809. To use it, create one of these objects, call addItem() to add the list of items
  45810. you need, then call resizeToFit(), which will change all their sizes. You can
  45811. then retrieve the new sizes with getItemSize() and getNumItems().
  45812. It's currently used by the TableHeaderComponent for stretching out the table
  45813. headings to fill the table's width.
  45814. */
  45815. class StretchableObjectResizer
  45816. {
  45817. public:
  45818. /** Creates an empty object resizer. */
  45819. StretchableObjectResizer();
  45820. /** Destructor. */
  45821. ~StretchableObjectResizer();
  45822. /** Adds an item to the list.
  45823. The order parameter lets you specify groups of items that are resized first when some
  45824. space needs to be found. Those items with an order of 0 will be the first ones to be
  45825. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  45826. will then try resizing the items with an order of 1, then 2, and so on.
  45827. */
  45828. void addItem (double currentSize,
  45829. double minSize,
  45830. double maxSize,
  45831. int order = 0);
  45832. /** Resizes all the items to fit this amount of space.
  45833. This will attempt to fit them in without exceeding each item's miniumum and
  45834. maximum sizes. In cases where none of the items can be expanded or enlarged any
  45835. further, the final size may be greater or less than the size passed in.
  45836. After calling this method, you can retrieve the new sizes with the getItemSize()
  45837. method.
  45838. */
  45839. void resizeToFit (double targetSize);
  45840. /** Returns the number of items that have been added. */
  45841. int getNumItems() const noexcept { return items.size(); }
  45842. /** Returns the size of one of the items. */
  45843. double getItemSize (int index) const noexcept;
  45844. private:
  45845. struct Item
  45846. {
  45847. double size;
  45848. double minSize;
  45849. double maxSize;
  45850. int order;
  45851. };
  45852. OwnedArray <Item> items;
  45853. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableObjectResizer);
  45854. };
  45855. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45856. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  45857. #endif
  45858. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  45859. #endif
  45860. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  45861. #endif
  45862. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  45863. #endif
  45864. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  45865. /*** Start of inlined file: juce_LookAndFeel.h ***/
  45866. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  45867. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  45868. class ToggleButton;
  45869. class TextButton;
  45870. class AlertWindow;
  45871. class TextLayout;
  45872. class ScrollBar;
  45873. class BubbleComponent;
  45874. class ComboBox;
  45875. class Button;
  45876. class FilenameComponent;
  45877. class DocumentWindow;
  45878. class ResizableWindow;
  45879. class GroupComponent;
  45880. class MenuBarComponent;
  45881. class DropShadower;
  45882. class GlyphArrangement;
  45883. class PropertyComponent;
  45884. class TableHeaderComponent;
  45885. class Toolbar;
  45886. class ToolbarItemComponent;
  45887. class PopupMenu;
  45888. class ProgressBar;
  45889. class FileBrowserComponent;
  45890. class DirectoryContentsDisplayComponent;
  45891. class FilePreviewComponent;
  45892. class ImageButton;
  45893. class CallOutBox;
  45894. class Drawable;
  45895. class CaretComponent;
  45896. /**
  45897. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  45898. can be used to apply different 'skins' to the application.
  45899. */
  45900. class JUCE_API LookAndFeel
  45901. {
  45902. public:
  45903. /** Creates the default JUCE look and feel. */
  45904. LookAndFeel();
  45905. /** Destructor. */
  45906. virtual ~LookAndFeel();
  45907. /** Returns the current default look-and-feel for a component to use when it
  45908. hasn't got one explicitly set.
  45909. @see setDefaultLookAndFeel
  45910. */
  45911. static LookAndFeel& getDefaultLookAndFeel() noexcept;
  45912. /** Changes the default look-and-feel.
  45913. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  45914. set to null, it will revert to using the default one. The
  45915. object passed-in must be deleted by the caller when
  45916. it's no longer needed.
  45917. @see getDefaultLookAndFeel
  45918. */
  45919. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) noexcept;
  45920. /** Looks for a colour that has been registered with the given colour ID number.
  45921. If a colour has been set for this ID number using setColour(), then it is
  45922. returned. If none has been set, it will just return Colours::black.
  45923. The colour IDs for various purposes are stored as enums in the components that
  45924. they are relevent to - for an example, see Slider::ColourIds,
  45925. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  45926. If you're looking up a colour for use in drawing a component, it's usually
  45927. best not to call this directly, but to use the Component::findColour() method
  45928. instead. That will first check whether a suitable colour has been registered
  45929. directly with the component, and will fall-back on calling the component's
  45930. LookAndFeel's findColour() method if none is found.
  45931. @see setColour, Component::findColour, Component::setColour
  45932. */
  45933. const Colour findColour (int colourId) const noexcept;
  45934. /** Registers a colour to be used for a particular purpose.
  45935. For more details, see the comments for findColour().
  45936. @see findColour, Component::findColour, Component::setColour
  45937. */
  45938. void setColour (int colourId, const Colour& colour) noexcept;
  45939. /** Returns true if the specified colour ID has been explicitly set using the
  45940. setColour() method.
  45941. */
  45942. bool isColourSpecified (int colourId) const noexcept;
  45943. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  45944. /** Allows you to change the default sans-serif font.
  45945. If you need to supply your own Typeface object for any of the default fonts, rather
  45946. than just supplying the name (e.g. if you want to use an embedded font), then
  45947. you should instead override getTypefaceForFont() to create and return the typeface.
  45948. */
  45949. void setDefaultSansSerifTypefaceName (const String& newName);
  45950. /** Override this to get the chance to swap a component's mouse cursor for a
  45951. customised one.
  45952. */
  45953. virtual const MouseCursor getMouseCursorFor (Component& component);
  45954. /** Draws the lozenge-shaped background for a standard button. */
  45955. virtual void drawButtonBackground (Graphics& g,
  45956. Button& button,
  45957. const Colour& backgroundColour,
  45958. bool isMouseOverButton,
  45959. bool isButtonDown);
  45960. virtual const Font getFontForTextButton (TextButton& button);
  45961. /** Draws the text for a TextButton. */
  45962. virtual void drawButtonText (Graphics& g,
  45963. TextButton& button,
  45964. bool isMouseOverButton,
  45965. bool isButtonDown);
  45966. /** Draws the contents of a standard ToggleButton. */
  45967. virtual void drawToggleButton (Graphics& g,
  45968. ToggleButton& button,
  45969. bool isMouseOverButton,
  45970. bool isButtonDown);
  45971. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  45972. virtual void drawTickBox (Graphics& g,
  45973. Component& component,
  45974. float x, float y, float w, float h,
  45975. bool ticked,
  45976. bool isEnabled,
  45977. bool isMouseOverButton,
  45978. bool isButtonDown);
  45979. /* AlertWindow handling..
  45980. */
  45981. virtual AlertWindow* createAlertWindow (const String& title,
  45982. const String& message,
  45983. const String& button1,
  45984. const String& button2,
  45985. const String& button3,
  45986. AlertWindow::AlertIconType iconType,
  45987. int numButtons,
  45988. Component* associatedComponent);
  45989. virtual void drawAlertBox (Graphics& g,
  45990. AlertWindow& alert,
  45991. const Rectangle<int>& textArea,
  45992. TextLayout& textLayout);
  45993. virtual int getAlertBoxWindowFlags();
  45994. virtual int getAlertWindowButtonHeight();
  45995. virtual const Font getAlertWindowMessageFont();
  45996. virtual const Font getAlertWindowFont();
  45997. void setUsingNativeAlertWindows (bool shouldUseNativeAlerts);
  45998. bool isUsingNativeAlertWindows();
  45999. /** Draws a progress bar.
  46000. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  46001. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  46002. isn't known). It can use the current time as a basis for playing an animation.
  46003. (Used by progress bars in AlertWindow).
  46004. */
  46005. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  46006. int width, int height,
  46007. double progress, const String& textToShow);
  46008. // Draws a small image that spins to indicate that something's happening..
  46009. // This method should use the current time to animate itself, so just keep
  46010. // repainting it every so often.
  46011. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  46012. int x, int y, int w, int h);
  46013. /** Draws one of the buttons on a scrollbar.
  46014. @param g the context to draw into
  46015. @param scrollbar the bar itself
  46016. @param width the width of the button
  46017. @param height the height of the button
  46018. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  46019. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  46020. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  46021. @param isButtonDown whether the mouse button's held down
  46022. */
  46023. virtual void drawScrollbarButton (Graphics& g,
  46024. ScrollBar& scrollbar,
  46025. int width, int height,
  46026. int buttonDirection,
  46027. bool isScrollbarVertical,
  46028. bool isMouseOverButton,
  46029. bool isButtonDown);
  46030. /** Draws the thumb area of a scrollbar.
  46031. @param g the context to draw into
  46032. @param scrollbar the bar itself
  46033. @param x the x position of the left edge of the thumb area to draw in
  46034. @param y the y position of the top edge of the thumb area to draw in
  46035. @param width the width of the thumb area to draw in
  46036. @param height the height of the thumb area to draw in
  46037. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  46038. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  46039. thumb, or its x position for horizontal bars
  46040. @param thumbSize for vertical bars, the height of the thumb, or its width for
  46041. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  46042. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  46043. currently dragging the thumb
  46044. @param isMouseDown whether the mouse is currently dragging the scrollbar
  46045. */
  46046. virtual void drawScrollbar (Graphics& g,
  46047. ScrollBar& scrollbar,
  46048. int x, int y,
  46049. int width, int height,
  46050. bool isScrollbarVertical,
  46051. int thumbStartPosition,
  46052. int thumbSize,
  46053. bool isMouseOver,
  46054. bool isMouseDown);
  46055. /** Returns the component effect to use for a scrollbar */
  46056. virtual ImageEffectFilter* getScrollbarEffect();
  46057. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  46058. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  46059. /** Returns the default thickness to use for a scrollbar. */
  46060. virtual int getDefaultScrollbarWidth();
  46061. /** Returns the length in pixels to use for a scrollbar button. */
  46062. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  46063. /** Returns a tick shape for use in yes/no boxes, etc. */
  46064. virtual const Path getTickShape (float height);
  46065. /** Returns a cross shape for use in yes/no boxes, etc. */
  46066. virtual const Path getCrossShape (float height);
  46067. /** Draws the + or - box in a treeview. */
  46068. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  46069. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  46070. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  46071. virtual CaretComponent* createCaretComponent (Component* keyFocusOwner);
  46072. // These return a pointer to an internally cached drawable - make sure you don't keep
  46073. // a copy of this pointer anywhere, as it may become invalid in the future.
  46074. virtual const Drawable* getDefaultFolderImage();
  46075. virtual const Drawable* getDefaultDocumentFileImage();
  46076. virtual void createFileChooserHeaderText (const String& title,
  46077. const String& instructions,
  46078. GlyphArrangement& destArrangement,
  46079. int width);
  46080. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  46081. const String& filename, Image* icon,
  46082. const String& fileSizeDescription,
  46083. const String& fileTimeDescription,
  46084. bool isDirectory,
  46085. bool isItemSelected,
  46086. int itemIndex,
  46087. DirectoryContentsDisplayComponent& component);
  46088. virtual Button* createFileBrowserGoUpButton();
  46089. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  46090. DirectoryContentsDisplayComponent* fileListComponent,
  46091. FilePreviewComponent* previewComp,
  46092. ComboBox* currentPathBox,
  46093. TextEditor* filenameBox,
  46094. Button* goUpButton);
  46095. virtual void drawBubble (Graphics& g,
  46096. float tipX, float tipY,
  46097. float boxX, float boxY, float boxW, float boxH);
  46098. /** Fills the background of a popup menu component. */
  46099. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  46100. /** Draws one of the items in a popup menu. */
  46101. virtual void drawPopupMenuItem (Graphics& g,
  46102. int width, int height,
  46103. bool isSeparator,
  46104. bool isActive,
  46105. bool isHighlighted,
  46106. bool isTicked,
  46107. bool hasSubMenu,
  46108. const String& text,
  46109. const String& shortcutKeyText,
  46110. Image* image,
  46111. const Colour* const textColour);
  46112. /** Returns the size and style of font to use in popup menus. */
  46113. virtual const Font getPopupMenuFont();
  46114. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  46115. int width, int height,
  46116. bool isScrollUpArrow);
  46117. /** Finds the best size for an item in a popup menu. */
  46118. virtual void getIdealPopupMenuItemSize (const String& text,
  46119. bool isSeparator,
  46120. int standardMenuItemHeight,
  46121. int& idealWidth,
  46122. int& idealHeight);
  46123. virtual int getMenuWindowFlags();
  46124. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  46125. bool isMouseOverBar,
  46126. MenuBarComponent& menuBar);
  46127. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  46128. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  46129. virtual void drawMenuBarItem (Graphics& g,
  46130. int width, int height,
  46131. int itemIndex,
  46132. const String& itemText,
  46133. bool isMouseOverItem,
  46134. bool isMenuOpen,
  46135. bool isMouseOverBar,
  46136. MenuBarComponent& menuBar);
  46137. virtual void drawComboBox (Graphics& g, int width, int height,
  46138. bool isButtonDown,
  46139. int buttonX, int buttonY,
  46140. int buttonW, int buttonH,
  46141. ComboBox& box);
  46142. virtual const Font getComboBoxFont (ComboBox& box);
  46143. virtual Label* createComboBoxTextBox (ComboBox& box);
  46144. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  46145. virtual void drawLabel (Graphics& g, Label& label);
  46146. virtual void drawLinearSlider (Graphics& g,
  46147. int x, int y,
  46148. int width, int height,
  46149. float sliderPos,
  46150. float minSliderPos,
  46151. float maxSliderPos,
  46152. const Slider::SliderStyle style,
  46153. Slider& slider);
  46154. virtual void drawLinearSliderBackground (Graphics& g,
  46155. int x, int y,
  46156. int width, int height,
  46157. float sliderPos,
  46158. float minSliderPos,
  46159. float maxSliderPos,
  46160. const Slider::SliderStyle style,
  46161. Slider& slider);
  46162. virtual void drawLinearSliderThumb (Graphics& g,
  46163. int x, int y,
  46164. int width, int height,
  46165. float sliderPos,
  46166. float minSliderPos,
  46167. float maxSliderPos,
  46168. const Slider::SliderStyle style,
  46169. Slider& slider);
  46170. virtual int getSliderThumbRadius (Slider& slider);
  46171. virtual void drawRotarySlider (Graphics& g,
  46172. int x, int y,
  46173. int width, int height,
  46174. float sliderPosProportional,
  46175. float rotaryStartAngle,
  46176. float rotaryEndAngle,
  46177. Slider& slider);
  46178. virtual Button* createSliderButton (bool isIncrement);
  46179. virtual Label* createSliderTextBox (Slider& slider);
  46180. virtual ImageEffectFilter* getSliderEffect();
  46181. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  46182. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  46183. virtual Button* createFilenameComponentBrowseButton (const String& text);
  46184. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  46185. ComboBox* filenameBox, Button* browseButton);
  46186. virtual void drawCornerResizer (Graphics& g,
  46187. int w, int h,
  46188. bool isMouseOver,
  46189. bool isMouseDragging);
  46190. virtual void drawResizableFrame (Graphics& g,
  46191. int w, int h,
  46192. const BorderSize<int>& borders);
  46193. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  46194. const BorderSize<int>& border,
  46195. ResizableWindow& window);
  46196. virtual void drawResizableWindowBorder (Graphics& g,
  46197. int w, int h,
  46198. const BorderSize<int>& border,
  46199. ResizableWindow& window);
  46200. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  46201. Graphics& g, int w, int h,
  46202. int titleSpaceX, int titleSpaceW,
  46203. const Image* icon,
  46204. bool drawTitleTextOnLeft);
  46205. virtual Button* createDocumentWindowButton (int buttonType);
  46206. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  46207. int titleBarX, int titleBarY,
  46208. int titleBarW, int titleBarH,
  46209. Button* minimiseButton,
  46210. Button* maximiseButton,
  46211. Button* closeButton,
  46212. bool positionTitleBarButtonsOnLeft);
  46213. virtual int getDefaultMenuBarHeight();
  46214. virtual DropShadower* createDropShadowerForComponent (Component* component);
  46215. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  46216. int w, int h,
  46217. bool isVerticalBar,
  46218. bool isMouseOver,
  46219. bool isMouseDragging);
  46220. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  46221. const String& text,
  46222. const Justification& position,
  46223. GroupComponent& group);
  46224. virtual void createTabButtonShape (Path& p,
  46225. int width, int height,
  46226. int tabIndex,
  46227. const String& text,
  46228. Button& button,
  46229. TabbedButtonBar::Orientation orientation,
  46230. bool isMouseOver,
  46231. bool isMouseDown,
  46232. bool isFrontTab);
  46233. virtual void fillTabButtonShape (Graphics& g,
  46234. const Path& path,
  46235. const Colour& preferredBackgroundColour,
  46236. int tabIndex,
  46237. const String& text,
  46238. Button& button,
  46239. TabbedButtonBar::Orientation orientation,
  46240. bool isMouseOver,
  46241. bool isMouseDown,
  46242. bool isFrontTab);
  46243. virtual void drawTabButtonText (Graphics& g,
  46244. int x, int y, int w, int h,
  46245. const Colour& preferredBackgroundColour,
  46246. int tabIndex,
  46247. const String& text,
  46248. Button& button,
  46249. TabbedButtonBar::Orientation orientation,
  46250. bool isMouseOver,
  46251. bool isMouseDown,
  46252. bool isFrontTab);
  46253. virtual int getTabButtonOverlap (int tabDepth);
  46254. virtual int getTabButtonSpaceAroundImage();
  46255. virtual int getTabButtonBestWidth (int tabIndex,
  46256. const String& text,
  46257. int tabDepth,
  46258. Button& button);
  46259. virtual void drawTabButton (Graphics& g,
  46260. int w, int h,
  46261. const Colour& preferredColour,
  46262. int tabIndex,
  46263. const String& text,
  46264. Button& button,
  46265. TabbedButtonBar::Orientation orientation,
  46266. bool isMouseOver,
  46267. bool isMouseDown,
  46268. bool isFrontTab);
  46269. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  46270. int w, int h,
  46271. TabbedButtonBar& tabBar,
  46272. TabbedButtonBar::Orientation orientation);
  46273. virtual Button* createTabBarExtrasButton();
  46274. virtual void drawImageButton (Graphics& g, Image* image,
  46275. int imageX, int imageY, int imageW, int imageH,
  46276. const Colour& overlayColour,
  46277. float imageOpacity,
  46278. ImageButton& button);
  46279. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  46280. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  46281. int width, int height,
  46282. bool isMouseOver, bool isMouseDown,
  46283. int columnFlags);
  46284. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  46285. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  46286. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  46287. bool isMouseOver, bool isMouseDown,
  46288. ToolbarItemComponent& component);
  46289. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  46290. const String& text, ToolbarItemComponent& component);
  46291. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  46292. bool isOpen, int width, int height);
  46293. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  46294. PropertyComponent& component);
  46295. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  46296. PropertyComponent& component);
  46297. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  46298. virtual void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
  46299. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  46300. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  46301. /**
  46302. */
  46303. virtual void playAlertSound();
  46304. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  46305. static void drawGlassSphere (Graphics& g,
  46306. float x, float y,
  46307. float diameter,
  46308. const Colour& colour,
  46309. float outlineThickness) noexcept;
  46310. static void drawGlassPointer (Graphics& g,
  46311. float x, float y,
  46312. float diameter,
  46313. const Colour& colour, float outlineThickness,
  46314. int direction) noexcept;
  46315. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  46316. static void drawGlassLozenge (Graphics& g,
  46317. float x, float y,
  46318. float width, float height,
  46319. const Colour& colour,
  46320. float outlineThickness,
  46321. float cornerSize,
  46322. bool flatOnLeft, bool flatOnRight,
  46323. bool flatOnTop, bool flatOnBottom) noexcept;
  46324. static Drawable* loadDrawableFromData (const void* data, size_t numBytes);
  46325. private:
  46326. friend JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  46327. static void clearDefaultLookAndFeel() noexcept; // called at shutdown
  46328. Array <int> colourIds;
  46329. Array <Colour> colours;
  46330. // default typeface names
  46331. String defaultSans, defaultSerif, defaultFixed;
  46332. ScopedPointer<Drawable> folderImage, documentImage;
  46333. bool useNativeAlertWindows;
  46334. void drawShinyButtonShape (Graphics& g,
  46335. float x, float y, float w, float h, float maxCornerSize,
  46336. const Colour& baseColour,
  46337. float strokeWidth,
  46338. bool flatOnLeft,
  46339. bool flatOnRight,
  46340. bool flatOnTop,
  46341. bool flatOnBottom) noexcept;
  46342. // This has been deprecated - see the new parameter list..
  46343. virtual int drawFileBrowserRow (Graphics&, int, int, const String&, Image*, const String&, const String&, bool, bool, int) { return 0; }
  46344. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LookAndFeel);
  46345. };
  46346. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  46347. /*** End of inlined file: juce_LookAndFeel.h ***/
  46348. #endif
  46349. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46350. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  46351. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46352. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46353. /**
  46354. The original Juce look-and-feel.
  46355. */
  46356. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  46357. {
  46358. public:
  46359. /** Creates the default JUCE look and feel. */
  46360. OldSchoolLookAndFeel();
  46361. /** Destructor. */
  46362. virtual ~OldSchoolLookAndFeel();
  46363. /** Draws the lozenge-shaped background for a standard button. */
  46364. virtual void drawButtonBackground (Graphics& g,
  46365. Button& button,
  46366. const Colour& backgroundColour,
  46367. bool isMouseOverButton,
  46368. bool isButtonDown);
  46369. /** Draws the contents of a standard ToggleButton. */
  46370. virtual void drawToggleButton (Graphics& g,
  46371. ToggleButton& button,
  46372. bool isMouseOverButton,
  46373. bool isButtonDown);
  46374. virtual void drawTickBox (Graphics& g,
  46375. Component& component,
  46376. float x, float y, float w, float h,
  46377. bool ticked,
  46378. bool isEnabled,
  46379. bool isMouseOverButton,
  46380. bool isButtonDown);
  46381. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  46382. int width, int height,
  46383. double progress, const String& textToShow);
  46384. virtual void drawScrollbarButton (Graphics& g,
  46385. ScrollBar& scrollbar,
  46386. int width, int height,
  46387. int buttonDirection,
  46388. bool isScrollbarVertical,
  46389. bool isMouseOverButton,
  46390. bool isButtonDown);
  46391. virtual void drawScrollbar (Graphics& g,
  46392. ScrollBar& scrollbar,
  46393. int x, int y,
  46394. int width, int height,
  46395. bool isScrollbarVertical,
  46396. int thumbStartPosition,
  46397. int thumbSize,
  46398. bool isMouseOver,
  46399. bool isMouseDown);
  46400. virtual ImageEffectFilter* getScrollbarEffect();
  46401. virtual void drawTextEditorOutline (Graphics& g,
  46402. int width, int height,
  46403. TextEditor& textEditor);
  46404. /** Fills the background of a popup menu component. */
  46405. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  46406. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  46407. bool isMouseOverBar,
  46408. MenuBarComponent& menuBar);
  46409. virtual void drawComboBox (Graphics& g, int width, int height,
  46410. bool isButtonDown,
  46411. int buttonX, int buttonY,
  46412. int buttonW, int buttonH,
  46413. ComboBox& box);
  46414. virtual const Font getComboBoxFont (ComboBox& box);
  46415. virtual void drawLinearSlider (Graphics& g,
  46416. int x, int y,
  46417. int width, int height,
  46418. float sliderPos,
  46419. float minSliderPos,
  46420. float maxSliderPos,
  46421. const Slider::SliderStyle style,
  46422. Slider& slider);
  46423. virtual int getSliderThumbRadius (Slider& slider);
  46424. virtual Button* createSliderButton (bool isIncrement);
  46425. virtual ImageEffectFilter* getSliderEffect();
  46426. virtual void drawCornerResizer (Graphics& g,
  46427. int w, int h,
  46428. bool isMouseOver,
  46429. bool isMouseDragging);
  46430. virtual Button* createDocumentWindowButton (int buttonType);
  46431. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  46432. int titleBarX, int titleBarY,
  46433. int titleBarW, int titleBarH,
  46434. Button* minimiseButton,
  46435. Button* maximiseButton,
  46436. Button* closeButton,
  46437. bool positionTitleBarButtonsOnLeft);
  46438. private:
  46439. DropShadowEffect scrollbarShadow;
  46440. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OldSchoolLookAndFeel);
  46441. };
  46442. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46443. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  46444. #endif
  46445. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  46446. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  46447. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  46448. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  46449. /**
  46450. A menu bar component.
  46451. @see MenuBarModel
  46452. */
  46453. class JUCE_API MenuBarComponent : public Component,
  46454. private MenuBarModel::Listener,
  46455. private Timer
  46456. {
  46457. public:
  46458. /** Creates a menu bar.
  46459. @param model the model object to use to control this bar. You can
  46460. pass 0 into this if you like, and set the model later
  46461. using the setModel() method
  46462. */
  46463. MenuBarComponent (MenuBarModel* model);
  46464. /** Destructor. */
  46465. ~MenuBarComponent();
  46466. /** Changes the model object to use to control the bar.
  46467. This can be a null pointer, in which case the bar will be empty. Don't delete the object
  46468. that is passed-in while it's still being used by this MenuBar.
  46469. */
  46470. void setModel (MenuBarModel* newModel);
  46471. /** Returns the current menu bar model being used.
  46472. */
  46473. MenuBarModel* getModel() const noexcept;
  46474. /** Pops up one of the menu items.
  46475. This lets you manually open one of the menus - it could be triggered by a
  46476. key shortcut, for example.
  46477. */
  46478. void showMenu (int menuIndex);
  46479. /** @internal */
  46480. void paint (Graphics& g);
  46481. /** @internal */
  46482. void resized();
  46483. /** @internal */
  46484. void mouseEnter (const MouseEvent& e);
  46485. /** @internal */
  46486. void mouseExit (const MouseEvent& e);
  46487. /** @internal */
  46488. void mouseDown (const MouseEvent& e);
  46489. /** @internal */
  46490. void mouseDrag (const MouseEvent& e);
  46491. /** @internal */
  46492. void mouseUp (const MouseEvent& e);
  46493. /** @internal */
  46494. void mouseMove (const MouseEvent& e);
  46495. /** @internal */
  46496. void handleCommandMessage (int commandId);
  46497. /** @internal */
  46498. bool keyPressed (const KeyPress& key);
  46499. /** @internal */
  46500. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  46501. /** @internal */
  46502. void menuCommandInvoked (MenuBarModel* menuBarModel,
  46503. const ApplicationCommandTarget::InvocationInfo& info);
  46504. private:
  46505. MenuBarModel* model;
  46506. StringArray menuNames;
  46507. Array <int> xPositions;
  46508. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked;
  46509. int lastMouseX, lastMouseY;
  46510. int getItemAt (int x, int y);
  46511. void setItemUnderMouse (int index);
  46512. void setOpenItem (int index);
  46513. void updateItemUnderMouse (int x, int y);
  46514. void timerCallback();
  46515. void repaintMenuItem (int index);
  46516. void menuDismissed (int topLevelIndex, int itemId);
  46517. static void menuBarMenuDismissedCallback (int, MenuBarComponent*, int);
  46518. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarComponent);
  46519. };
  46520. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  46521. /*** End of inlined file: juce_MenuBarComponent.h ***/
  46522. #endif
  46523. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  46524. #endif
  46525. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  46526. #endif
  46527. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  46528. #endif
  46529. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  46530. #endif
  46531. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  46532. #endif
  46533. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  46534. #endif
  46535. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  46536. /*** Start of inlined file: juce_LassoComponent.h ***/
  46537. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  46538. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  46539. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  46540. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  46541. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  46542. /** Manages a list of selectable items.
  46543. Use one of these to keep a track of things that the user has highlighted, like
  46544. icons or things in a list.
  46545. The class is templated so that you can use it to hold either a set of pointers
  46546. to objects, or a set of ID numbers or handles, for cases where each item may
  46547. not always have a corresponding object.
  46548. To be informed when items are selected/deselected, register a ChangeListener with
  46549. this object.
  46550. @see SelectableObject
  46551. */
  46552. template <class SelectableItemType>
  46553. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  46554. {
  46555. public:
  46556. typedef SelectableItemType ItemType;
  46557. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  46558. /** Creates an empty set. */
  46559. SelectedItemSet()
  46560. {
  46561. }
  46562. /** Creates a set based on an array of items. */
  46563. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  46564. : selectedItems (items)
  46565. {
  46566. }
  46567. /** Creates a copy of another set. */
  46568. SelectedItemSet (const SelectedItemSet& other)
  46569. : selectedItems (other.selectedItems)
  46570. {
  46571. }
  46572. /** Creates a copy of another set. */
  46573. SelectedItemSet& operator= (const SelectedItemSet& other)
  46574. {
  46575. if (selectedItems != other.selectedItems)
  46576. {
  46577. selectedItems = other.selectedItems;
  46578. changed();
  46579. }
  46580. return *this;
  46581. }
  46582. /** Clears any other currently selected items, and selects this item.
  46583. If this item is already the only thing selected, no change notification
  46584. will be sent out.
  46585. @see addToSelection, addToSelectionBasedOnModifiers
  46586. */
  46587. void selectOnly (ParameterType item)
  46588. {
  46589. if (isSelected (item))
  46590. {
  46591. for (int i = selectedItems.size(); --i >= 0;)
  46592. {
  46593. if (selectedItems.getUnchecked(i) != item)
  46594. {
  46595. deselect (selectedItems.getUnchecked(i));
  46596. i = jmin (i, selectedItems.size());
  46597. }
  46598. }
  46599. }
  46600. else
  46601. {
  46602. deselectAll();
  46603. changed();
  46604. selectedItems.add (item);
  46605. itemSelected (item);
  46606. }
  46607. }
  46608. /** Selects an item.
  46609. If the item is already selected, no change notification will be sent out.
  46610. @see selectOnly, addToSelectionBasedOnModifiers
  46611. */
  46612. void addToSelection (ParameterType item)
  46613. {
  46614. if (! isSelected (item))
  46615. {
  46616. changed();
  46617. selectedItems.add (item);
  46618. itemSelected (item);
  46619. }
  46620. }
  46621. /** Selects or deselects an item.
  46622. This will use the modifier keys to decide whether to deselect other items
  46623. first.
  46624. So if the shift key is held down, the item will be added without deselecting
  46625. anything (same as calling addToSelection() )
  46626. If no modifiers are down, the current selection will be cleared first (same
  46627. as calling selectOnly() )
  46628. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  46629. so it'll be added to the set unless it's already there, in which case it'll be
  46630. deselected.
  46631. If the items that you're selecting can also be dragged, you may need to use the
  46632. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  46633. subtleties of this kind of usage.
  46634. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  46635. */
  46636. void addToSelectionBasedOnModifiers (ParameterType item,
  46637. const ModifierKeys& modifiers)
  46638. {
  46639. if (modifiers.isShiftDown())
  46640. {
  46641. addToSelection (item);
  46642. }
  46643. else if (modifiers.isCommandDown())
  46644. {
  46645. if (isSelected (item))
  46646. deselect (item);
  46647. else
  46648. addToSelection (item);
  46649. }
  46650. else
  46651. {
  46652. selectOnly (item);
  46653. }
  46654. }
  46655. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  46656. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  46657. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  46658. makes it easy to handle multiple-selection of sets of objects that can also
  46659. be dragged.
  46660. For example, if you have several items already selected, and you click on
  46661. one of them (without dragging), then you'd expect this to deselect the other, and
  46662. just select the item you clicked on. But if you had clicked on this item and
  46663. dragged it, you'd have expected them all to stay selected.
  46664. When you call this method, you'll need to store the boolean result, because the
  46665. addToSelectionOnMouseUp() method will need to be know this value.
  46666. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  46667. */
  46668. bool addToSelectionOnMouseDown (ParameterType item,
  46669. const ModifierKeys& modifiers)
  46670. {
  46671. if (isSelected (item))
  46672. {
  46673. return ! modifiers.isPopupMenu();
  46674. }
  46675. else
  46676. {
  46677. addToSelectionBasedOnModifiers (item, modifiers);
  46678. return false;
  46679. }
  46680. }
  46681. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  46682. Call this during a mouseUp callback, when you have previously called the
  46683. addToSelectionOnMouseDown() method during your mouseDown event.
  46684. See addToSelectionOnMouseDown() for more info
  46685. @param item the item to select (or deselect)
  46686. @param modifiers the modifiers from the mouse-up event
  46687. @param wasItemDragged true if your item was dragged during the mouse click
  46688. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  46689. back from the addToSelectionOnMouseDown() call that you
  46690. should have made during the matching mouseDown event
  46691. */
  46692. void addToSelectionOnMouseUp (ParameterType item,
  46693. const ModifierKeys& modifiers,
  46694. const bool wasItemDragged,
  46695. const bool resultOfMouseDownSelectMethod)
  46696. {
  46697. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  46698. addToSelectionBasedOnModifiers (item, modifiers);
  46699. }
  46700. /** Deselects an item. */
  46701. void deselect (ParameterType item)
  46702. {
  46703. const int i = selectedItems.indexOf (item);
  46704. if (i >= 0)
  46705. {
  46706. changed();
  46707. itemDeselected (selectedItems.remove (i));
  46708. }
  46709. }
  46710. /** Deselects all items. */
  46711. void deselectAll()
  46712. {
  46713. if (selectedItems.size() > 0)
  46714. {
  46715. changed();
  46716. for (int i = selectedItems.size(); --i >= 0;)
  46717. {
  46718. itemDeselected (selectedItems.remove (i));
  46719. i = jmin (i, selectedItems.size());
  46720. }
  46721. }
  46722. }
  46723. /** Returns the number of currently selected items.
  46724. @see getSelectedItem
  46725. */
  46726. int getNumSelected() const noexcept
  46727. {
  46728. return selectedItems.size();
  46729. }
  46730. /** Returns one of the currently selected items.
  46731. Returns 0 if the index is out-of-range.
  46732. @see getNumSelected
  46733. */
  46734. SelectableItemType getSelectedItem (const int index) const noexcept
  46735. {
  46736. return selectedItems [index];
  46737. }
  46738. /** True if this item is currently selected. */
  46739. bool isSelected (ParameterType item) const noexcept
  46740. {
  46741. return selectedItems.contains (item);
  46742. }
  46743. const Array <SelectableItemType>& getItemArray() const noexcept { return selectedItems; }
  46744. /** Can be overridden to do special handling when an item is selected.
  46745. For example, if the item is an object, you might want to call it and tell
  46746. it that it's being selected.
  46747. */
  46748. virtual void itemSelected (SelectableItemType item) { (void) item; }
  46749. /** Can be overridden to do special handling when an item is deselected.
  46750. For example, if the item is an object, you might want to call it and tell
  46751. it that it's being deselected.
  46752. */
  46753. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  46754. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  46755. */
  46756. void changed (const bool synchronous = false)
  46757. {
  46758. if (synchronous)
  46759. sendSynchronousChangeMessage();
  46760. else
  46761. sendChangeMessage();
  46762. }
  46763. private:
  46764. Array <SelectableItemType> selectedItems;
  46765. JUCE_LEAK_DETECTOR (SelectedItemSet <SelectableItemType>);
  46766. };
  46767. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  46768. /*** End of inlined file: juce_SelectedItemSet.h ***/
  46769. /**
  46770. A class used by the LassoComponent to manage the things that it selects.
  46771. This allows the LassoComponent to find out which items are within the lasso,
  46772. and to change the list of selected items.
  46773. @see LassoComponent, SelectedItemSet
  46774. */
  46775. template <class SelectableItemType>
  46776. class LassoSource
  46777. {
  46778. public:
  46779. /** Destructor. */
  46780. virtual ~LassoSource() {}
  46781. /** Returns the set of items that lie within a given lassoable region.
  46782. Your implementation of this method must find all the relevent items that lie
  46783. within the given rectangle. and add them to the itemsFound array.
  46784. The co-ordinates are relative to the top-left of the lasso component's parent
  46785. component. (i.e. they are the same as the size and position of the lasso
  46786. component itself).
  46787. */
  46788. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  46789. const Rectangle<int>& area) = 0;
  46790. /** Returns the SelectedItemSet that the lasso should update.
  46791. This set will be continuously updated by the LassoComponent as it gets
  46792. dragged around, so make sure that you've got a ChangeListener attached to
  46793. the set so that your UI objects will know when the selection changes and
  46794. be able to update themselves appropriately.
  46795. */
  46796. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  46797. };
  46798. /**
  46799. A component that acts as a rectangular selection region, which you drag with
  46800. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  46801. To use one of these:
  46802. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  46803. component, and call its beginLasso() method, giving it a
  46804. suitable LassoSource object that it can use to find out which items are in
  46805. the active area.
  46806. - Each time your parent component gets a mouseDrag event, call dragLasso()
  46807. to update the lasso's position - it will use its LassoSource to calculate and
  46808. update the current selection.
  46809. - After the drag has finished and you get a mouseUp callback, you should call
  46810. endLasso() to clean up. This will make the lasso component invisible, and you
  46811. can remove it from the parent component, or delete it.
  46812. The class takes into account the modifier keys that are being held down while
  46813. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  46814. be added to the original selection; if ctrl or command is pressed, they will be
  46815. xor'ed with any previously selected items.
  46816. @see LassoSource, SelectedItemSet
  46817. */
  46818. template <class SelectableItemType>
  46819. class LassoComponent : public Component
  46820. {
  46821. public:
  46822. /** Creates a Lasso component.
  46823. The fill colour is used to fill the lasso'ed rectangle, and the outline
  46824. colour is used to draw a line around its edge.
  46825. */
  46826. explicit LassoComponent (const int outlineThickness_ = 1)
  46827. : source (nullptr),
  46828. outlineThickness (outlineThickness_)
  46829. {
  46830. }
  46831. /** Destructor. */
  46832. ~LassoComponent()
  46833. {
  46834. }
  46835. /** Call this in your mouseDown event, to initialise a drag.
  46836. Pass in a suitable LassoSource object which the lasso will use to find
  46837. the items and change the selection.
  46838. After using this method to initialise the lasso, repeatedly call dragLasso()
  46839. in your component's mouseDrag callback.
  46840. @see dragLasso, endLasso, LassoSource
  46841. */
  46842. void beginLasso (const MouseEvent& e,
  46843. LassoSource <SelectableItemType>* const lassoSource)
  46844. {
  46845. jassert (source == nullptr); // this suggests that you didn't call endLasso() after the last drag...
  46846. jassert (lassoSource != nullptr); // the source can't be null!
  46847. jassert (getParentComponent() != nullptr); // you need to add this to a parent component for it to work!
  46848. source = lassoSource;
  46849. if (lassoSource != nullptr)
  46850. originalSelection = lassoSource->getLassoSelection().getItemArray();
  46851. setSize (0, 0);
  46852. dragStartPos = e.getMouseDownPosition();
  46853. }
  46854. /** Call this in your mouseDrag event, to update the lasso's position.
  46855. This must be repeatedly calling when the mouse is dragged, after you've
  46856. first initialised the lasso with beginLasso().
  46857. This method takes into account the modifier keys that are being held down, so
  46858. if shift is pressed, then the lassoed items will be added to any that were
  46859. previously selected; if ctrl or command is pressed, then they will be xor'ed
  46860. with previously selected items.
  46861. @see beginLasso, endLasso
  46862. */
  46863. void dragLasso (const MouseEvent& e)
  46864. {
  46865. if (source != nullptr)
  46866. {
  46867. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  46868. setVisible (true);
  46869. Array <SelectableItemType> itemsInLasso;
  46870. source->findLassoItemsInArea (itemsInLasso, getBounds());
  46871. if (e.mods.isShiftDown())
  46872. {
  46873. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  46874. itemsInLasso.addArray (originalSelection);
  46875. }
  46876. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  46877. {
  46878. Array <SelectableItemType> originalMinusNew (originalSelection);
  46879. originalMinusNew.removeValuesIn (itemsInLasso);
  46880. itemsInLasso.removeValuesIn (originalSelection);
  46881. itemsInLasso.addArray (originalMinusNew);
  46882. }
  46883. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  46884. }
  46885. }
  46886. /** Call this in your mouseUp event, after the lasso has been dragged.
  46887. @see beginLasso, dragLasso
  46888. */
  46889. void endLasso()
  46890. {
  46891. source = nullptr;
  46892. originalSelection.clear();
  46893. setVisible (false);
  46894. }
  46895. /** A set of colour IDs to use to change the colour of various aspects of the label.
  46896. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  46897. methods.
  46898. Note that you can also use the constants from TextEditor::ColourIds to change the
  46899. colour of the text editor that is opened when a label is editable.
  46900. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  46901. */
  46902. enum ColourIds
  46903. {
  46904. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  46905. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  46906. };
  46907. /** @internal */
  46908. void paint (Graphics& g)
  46909. {
  46910. g.fillAll (findColour (lassoFillColourId));
  46911. g.setColour (findColour (lassoOutlineColourId));
  46912. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  46913. // this suggests that you've left a lasso comp lying around after the
  46914. // mouse drag has finished.. Be careful to call endLasso() when you get a
  46915. // mouse-up event.
  46916. jassert (isMouseButtonDownAnywhere());
  46917. }
  46918. /** @internal */
  46919. bool hitTest (int, int) { return false; }
  46920. private:
  46921. Array <SelectableItemType> originalSelection;
  46922. LassoSource <SelectableItemType>* source;
  46923. int outlineThickness;
  46924. Point<int> dragStartPos;
  46925. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LassoComponent);
  46926. };
  46927. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  46928. /*** End of inlined file: juce_LassoComponent.h ***/
  46929. #endif
  46930. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  46931. #endif
  46932. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  46933. #endif
  46934. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46935. /*** Start of inlined file: juce_MouseInputSource.h ***/
  46936. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46937. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46938. class MouseInputSourceInternal;
  46939. /**
  46940. Represents a linear source of mouse events from a mouse device or individual finger
  46941. in a multi-touch environment.
  46942. Each MouseEvent object contains a reference to the MouseInputSource that generated
  46943. it. In an environment with a single mouse for input, all events will come from the
  46944. same source, but in a multi-touch system, there may be multiple MouseInputSource
  46945. obects active, each representing a stream of events coming from a particular finger.
  46946. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  46947. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  46948. the only events that can happen between a mouseDown and its corresponding mouseUp are
  46949. mouseDrags, etc.
  46950. When there are multiple touches arriving from multiple MouseInputSources, their
  46951. event streams may arrive in an interleaved order, so you should use the getIndex()
  46952. method to find out which finger each event came from.
  46953. @see MouseEvent
  46954. */
  46955. class JUCE_API MouseInputSource
  46956. {
  46957. public:
  46958. /** Creates a MouseInputSource.
  46959. You should never actually create a MouseInputSource in your own code - the
  46960. library takes care of managing these objects.
  46961. */
  46962. MouseInputSource (int index, bool isMouseDevice);
  46963. /** Destructor. */
  46964. ~MouseInputSource();
  46965. /** Returns true if this object represents a normal desk-based mouse device. */
  46966. bool isMouse() const;
  46967. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  46968. bool isTouch() const;
  46969. /** Returns true if this source has an on-screen pointer that can hover over
  46970. items without clicking them.
  46971. */
  46972. bool canHover() const;
  46973. /** Returns true if this source may have a scroll wheel. */
  46974. bool hasMouseWheel() const;
  46975. /** Returns this source's index in the global list of possible sources.
  46976. If the system only has a single mouse, there will only be a single MouseInputSource
  46977. with an index of 0.
  46978. If the system supports multi-touch input, then the index will represent a finger
  46979. number, starting from 0. When the first touch event begins, it will have finger
  46980. number 0, and then if a second touch happens while the first is still down, it
  46981. will have index 1, etc.
  46982. */
  46983. int getIndex() const;
  46984. /** Returns true if this device is currently being pressed. */
  46985. bool isDragging() const;
  46986. /** Returns the last-known screen position of this source. */
  46987. const Point<int> getScreenPosition() const;
  46988. /** Returns a set of modifiers that indicate which buttons are currently
  46989. held down on this device.
  46990. */
  46991. const ModifierKeys getCurrentModifiers() const;
  46992. /** Returns the component that was last known to be under this pointer. */
  46993. Component* getComponentUnderMouse() const;
  46994. /** Tells the device to dispatch a mouse-move or mouse-drag event.
  46995. This is asynchronous - the event will occur on the message thread.
  46996. */
  46997. void triggerFakeMove() const;
  46998. /** Returns the number of clicks that should be counted as belonging to the
  46999. current mouse event.
  47000. So the mouse is currently down and it's the second click of a double-click, this
  47001. will return 2.
  47002. */
  47003. int getNumberOfMultipleClicks() const noexcept;
  47004. /** Returns the time at which the last mouse-down occurred. */
  47005. const Time getLastMouseDownTime() const noexcept;
  47006. /** Returns the screen position at which the last mouse-down occurred. */
  47007. const Point<int> getLastMouseDownPosition() const noexcept;
  47008. /** Returns true if this mouse is currently down, and if it has been dragged more
  47009. than a couple of pixels from the place it was pressed.
  47010. */
  47011. bool hasMouseMovedSignificantlySincePressed() const noexcept;
  47012. /** Returns true if this input source uses a visible mouse cursor. */
  47013. bool hasMouseCursor() const noexcept;
  47014. /** Changes the mouse cursor, (if there is one). */
  47015. void showMouseCursor (const MouseCursor& cursor);
  47016. /** Hides the mouse cursor (if there is one). */
  47017. void hideCursor();
  47018. /** Un-hides the mouse cursor if it was hidden by hideCursor(). */
  47019. void revealCursor();
  47020. /** Forces an update of the mouse cursor for whatever component it's currently over. */
  47021. void forceMouseCursorUpdate();
  47022. /** Returns true if this mouse can be moved indefinitely in any direction without running out of space. */
  47023. bool canDoUnboundedMovement() const noexcept;
  47024. /** Allows the mouse to move beyond the edges of the screen.
  47025. Calling this method when the mouse button is currently pressed will remove the cursor
  47026. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  47027. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  47028. can be used for things like custom slider controls or dragging objects around, where
  47029. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  47030. The unbounded mode is automatically turned off when the mouse button is released, or
  47031. it can be turned off explicitly by calling this method again.
  47032. @param isEnabled whether to turn this mode on or off
  47033. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  47034. hidden; if true, it will only be hidden when it
  47035. is moved beyond the edge of the screen
  47036. */
  47037. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  47038. /** @internal */
  47039. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  47040. /** @internal */
  47041. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  47042. private:
  47043. friend class Desktop;
  47044. friend class ComponentPeer;
  47045. friend class MouseInputSourceInternal;
  47046. ScopedPointer<MouseInputSourceInternal> pimpl;
  47047. static const Point<int> getCurrentMousePosition();
  47048. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseInputSource);
  47049. };
  47050. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  47051. /*** End of inlined file: juce_MouseInputSource.h ***/
  47052. #endif
  47053. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  47054. #endif
  47055. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  47056. #endif
  47057. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  47058. #endif
  47059. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  47060. #endif
  47061. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  47062. #endif
  47063. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47064. /*** Start of inlined file: juce_RelativeParallelogram.h ***/
  47065. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47066. #define __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47067. /**
  47068. A parallelogram defined by three RelativePoint positions.
  47069. @see RelativePoint, RelativeCoordinate
  47070. */
  47071. class JUCE_API RelativeParallelogram
  47072. {
  47073. public:
  47074. RelativeParallelogram();
  47075. RelativeParallelogram (const Rectangle<float>& simpleRectangle);
  47076. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  47077. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  47078. ~RelativeParallelogram();
  47079. void resolveThreePoints (Point<float>* points, Expression::Scope* scope) const;
  47080. void resolveFourCorners (Point<float>* points, Expression::Scope* scope) const;
  47081. const Rectangle<float> getBounds (Expression::Scope* scope) const;
  47082. void getPath (Path& path, Expression::Scope* scope) const;
  47083. const AffineTransform resetToPerpendicular (Expression::Scope* scope);
  47084. bool isDynamic() const;
  47085. bool operator== (const RelativeParallelogram& other) const noexcept;
  47086. bool operator!= (const RelativeParallelogram& other) const noexcept;
  47087. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) noexcept;
  47088. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) noexcept;
  47089. static const Rectangle<float> getBoundingBox (const Point<float>* parallelogramCorners) noexcept;
  47090. RelativePoint topLeft, topRight, bottomLeft;
  47091. };
  47092. #endif // __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47093. /*** End of inlined file: juce_RelativeParallelogram.h ***/
  47094. #endif
  47095. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  47096. #endif
  47097. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47098. /*** Start of inlined file: juce_RelativePointPath.h ***/
  47099. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47100. #define __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47101. class DrawablePath;
  47102. /**
  47103. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  47104. One of these paths can be converted into a Path object for drawing and manipulation, but
  47105. unlike a Path, its points can be dynamic instead of just fixed.
  47106. @see RelativePoint, RelativeCoordinate
  47107. */
  47108. class JUCE_API RelativePointPath
  47109. {
  47110. public:
  47111. RelativePointPath();
  47112. RelativePointPath (const RelativePointPath& other);
  47113. explicit RelativePointPath (const Path& path);
  47114. ~RelativePointPath();
  47115. bool operator== (const RelativePointPath& other) const noexcept;
  47116. bool operator!= (const RelativePointPath& other) const noexcept;
  47117. /** Resolves this points in this path and adds them to a normal Path object. */
  47118. void createPath (Path& path, Expression::Scope* scope) const;
  47119. /** Returns true if the path contains any non-fixed points. */
  47120. bool containsAnyDynamicPoints() const;
  47121. /** Quickly swaps the contents of this path with another. */
  47122. void swapWith (RelativePointPath& other) noexcept;
  47123. /** The types of element that may be contained in this path.
  47124. @see RelativePointPath::ElementBase
  47125. */
  47126. enum ElementType
  47127. {
  47128. nullElement,
  47129. startSubPathElement,
  47130. closeSubPathElement,
  47131. lineToElement,
  47132. quadraticToElement,
  47133. cubicToElement
  47134. };
  47135. /** Base class for the elements that make up a RelativePointPath.
  47136. */
  47137. class JUCE_API ElementBase
  47138. {
  47139. public:
  47140. ElementBase (ElementType type);
  47141. virtual ~ElementBase() {}
  47142. virtual const ValueTree createTree() const = 0;
  47143. virtual void addToPath (Path& path, Expression::Scope*) const = 0;
  47144. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  47145. virtual ElementBase* clone() const = 0;
  47146. bool isDynamic();
  47147. const ElementType type;
  47148. private:
  47149. JUCE_DECLARE_NON_COPYABLE (ElementBase);
  47150. };
  47151. class JUCE_API StartSubPath : public ElementBase
  47152. {
  47153. public:
  47154. StartSubPath (const RelativePoint& pos);
  47155. const ValueTree createTree() const;
  47156. void addToPath (Path& path, Expression::Scope*) const;
  47157. RelativePoint* getControlPoints (int& numPoints);
  47158. ElementBase* clone() const;
  47159. RelativePoint startPos;
  47160. private:
  47161. JUCE_DECLARE_NON_COPYABLE (StartSubPath);
  47162. };
  47163. class JUCE_API CloseSubPath : public ElementBase
  47164. {
  47165. public:
  47166. CloseSubPath();
  47167. const ValueTree createTree() const;
  47168. void addToPath (Path& path, Expression::Scope*) const;
  47169. RelativePoint* getControlPoints (int& numPoints);
  47170. ElementBase* clone() const;
  47171. private:
  47172. JUCE_DECLARE_NON_COPYABLE (CloseSubPath);
  47173. };
  47174. class JUCE_API LineTo : public ElementBase
  47175. {
  47176. public:
  47177. LineTo (const RelativePoint& endPoint);
  47178. const ValueTree createTree() const;
  47179. void addToPath (Path& path, Expression::Scope*) const;
  47180. RelativePoint* getControlPoints (int& numPoints);
  47181. ElementBase* clone() const;
  47182. RelativePoint endPoint;
  47183. private:
  47184. JUCE_DECLARE_NON_COPYABLE (LineTo);
  47185. };
  47186. class JUCE_API QuadraticTo : public ElementBase
  47187. {
  47188. public:
  47189. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  47190. const ValueTree createTree() const;
  47191. void addToPath (Path& path, Expression::Scope*) const;
  47192. RelativePoint* getControlPoints (int& numPoints);
  47193. ElementBase* clone() const;
  47194. RelativePoint controlPoints[2];
  47195. private:
  47196. JUCE_DECLARE_NON_COPYABLE (QuadraticTo);
  47197. };
  47198. class JUCE_API CubicTo : public ElementBase
  47199. {
  47200. public:
  47201. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  47202. const ValueTree createTree() const;
  47203. void addToPath (Path& path, Expression::Scope*) const;
  47204. RelativePoint* getControlPoints (int& numPoints);
  47205. ElementBase* clone() const;
  47206. RelativePoint controlPoints[3];
  47207. private:
  47208. JUCE_DECLARE_NON_COPYABLE (CubicTo);
  47209. };
  47210. void addElement (ElementBase* newElement);
  47211. OwnedArray <ElementBase> elements;
  47212. bool usesNonZeroWinding;
  47213. private:
  47214. class Positioner;
  47215. friend class Positioner;
  47216. bool containsDynamicPoints;
  47217. void applyTo (DrawablePath& path) const;
  47218. RelativePointPath& operator= (const RelativePointPath&);
  47219. JUCE_LEAK_DETECTOR (RelativePointPath);
  47220. };
  47221. #endif // __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47222. /*** End of inlined file: juce_RelativePointPath.h ***/
  47223. #endif
  47224. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47225. /*** Start of inlined file: juce_RelativeRectangle.h ***/
  47226. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47227. #define __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47228. class Component;
  47229. /**
  47230. An rectangle stored as a set of RelativeCoordinate values.
  47231. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  47232. @see RelativeCoordinate, RelativePoint
  47233. */
  47234. class JUCE_API RelativeRectangle
  47235. {
  47236. public:
  47237. /** Creates a zero-size rectangle at the origin. */
  47238. RelativeRectangle();
  47239. /** Creates an absolute rectangle, relative to the origin. */
  47240. explicit RelativeRectangle (const Rectangle<float>& rect);
  47241. /** Creates a rectangle from four coordinates. */
  47242. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  47243. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  47244. /** Creates a rectangle from a stringified representation.
  47245. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  47246. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  47247. RelativeCoordinate class.
  47248. @see toString
  47249. */
  47250. explicit RelativeRectangle (const String& stringVersion);
  47251. bool operator== (const RelativeRectangle& other) const noexcept;
  47252. bool operator!= (const RelativeRectangle& other) const noexcept;
  47253. /** Calculates the absolute position of this rectangle.
  47254. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  47255. be needed to calculate the result.
  47256. */
  47257. const Rectangle<float> resolve (const Expression::Scope* scope) const;
  47258. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  47259. Calling this will leave any anchor points unchanged, but will set any absolute
  47260. or relative positions to whatever values are necessary to make the resultant position
  47261. match the position that is provided.
  47262. */
  47263. void moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope);
  47264. /** Returns true if this rectangle depends on any external symbols for its position.
  47265. Coordinates that refer to symbols based on "this" are assumed not to be dynamic.
  47266. */
  47267. bool isDynamic() const;
  47268. /** Returns a string which represents this point.
  47269. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  47270. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  47271. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  47272. */
  47273. const String toString() const;
  47274. /** Renames a symbol if it is used by any of the coordinates.
  47275. This calls Expression::withRenamedSymbol() on the rectangle's coordinates.
  47276. */
  47277. void renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope);
  47278. /** Creates and sets an appropriate Component::Positioner object for the given component, which will
  47279. keep it positioned with this rectangle.
  47280. */
  47281. void applyToComponent (Component& component) const;
  47282. // The actual rectangle coords...
  47283. RelativeCoordinate left, right, top, bottom;
  47284. };
  47285. #endif // __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47286. /*** End of inlined file: juce_RelativeRectangle.h ***/
  47287. #endif
  47288. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47289. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  47290. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47291. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47292. /**
  47293. A PropertyComponent that contains an on/off toggle button.
  47294. This type of property component can be used if you have a boolean value to
  47295. toggle on/off.
  47296. @see PropertyComponent
  47297. */
  47298. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  47299. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  47300. {
  47301. protected:
  47302. /** Creates a button component.
  47303. If you use this constructor, you must override the getState() and setState()
  47304. methods.
  47305. @param propertyName the property name to be passed to the PropertyComponent
  47306. @param buttonTextWhenTrue the text shown in the button when the value is true
  47307. @param buttonTextWhenFalse the text shown in the button when the value is false
  47308. */
  47309. BooleanPropertyComponent (const String& propertyName,
  47310. const String& buttonTextWhenTrue,
  47311. const String& buttonTextWhenFalse);
  47312. public:
  47313. /** Creates a button component.
  47314. @param valueToControl a Value object that this property should refer to.
  47315. @param propertyName the property name to be passed to the PropertyComponent
  47316. @param buttonText the text shown in the ToggleButton component
  47317. */
  47318. BooleanPropertyComponent (const Value& valueToControl,
  47319. const String& propertyName,
  47320. const String& buttonText);
  47321. /** Destructor. */
  47322. ~BooleanPropertyComponent();
  47323. /** Called to change the state of the boolean value. */
  47324. virtual void setState (bool newState);
  47325. /** Must return the current value of the property. */
  47326. virtual bool getState() const;
  47327. /** @internal */
  47328. void paint (Graphics& g);
  47329. /** @internal */
  47330. void refresh();
  47331. /** @internal */
  47332. void buttonClicked (Button*);
  47333. private:
  47334. ToggleButton button;
  47335. String onText, offText;
  47336. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BooleanPropertyComponent);
  47337. };
  47338. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47339. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  47340. #endif
  47341. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47342. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  47343. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47344. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47345. /**
  47346. A PropertyComponent that contains a button.
  47347. This type of property component can be used if you need a button to trigger some
  47348. kind of action.
  47349. @see PropertyComponent
  47350. */
  47351. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  47352. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  47353. {
  47354. public:
  47355. /** Creates a button component.
  47356. @param propertyName the property name to be passed to the PropertyComponent
  47357. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  47358. */
  47359. ButtonPropertyComponent (const String& propertyName,
  47360. bool triggerOnMouseDown);
  47361. /** Destructor. */
  47362. ~ButtonPropertyComponent();
  47363. /** Called when the user clicks the button.
  47364. */
  47365. virtual void buttonClicked() = 0;
  47366. /** Returns the string that should be displayed in the button.
  47367. If you need to change this string, call refresh() to update the component.
  47368. */
  47369. virtual const String getButtonText() const = 0;
  47370. /** @internal */
  47371. void refresh();
  47372. /** @internal */
  47373. void buttonClicked (Button*);
  47374. private:
  47375. TextButton button;
  47376. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonPropertyComponent);
  47377. };
  47378. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47379. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  47380. #endif
  47381. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47382. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  47383. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47384. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47385. /**
  47386. A PropertyComponent that shows its value as a combo box.
  47387. This type of property component contains a list of options and has a
  47388. combo box to choose one.
  47389. Your subclass's constructor must add some strings to the choices StringArray
  47390. and these are shown in the list.
  47391. The getIndex() method will be called to find out which option is the currently
  47392. selected one. If you call refresh() it will call getIndex() to check whether
  47393. the value has changed, and will update the combo box if needed.
  47394. If the user selects a different item from the list, setIndex() will be
  47395. called to let your class process this.
  47396. @see PropertyComponent, PropertyPanel
  47397. */
  47398. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  47399. private ComboBoxListener // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  47400. {
  47401. protected:
  47402. /** Creates the component.
  47403. Your subclass's constructor must add a list of options to the choices
  47404. member variable.
  47405. */
  47406. ChoicePropertyComponent (const String& propertyName);
  47407. public:
  47408. /** Creates the component.
  47409. @param valueToControl the value that the combo box will read and control
  47410. @param propertyName the name of the property
  47411. @param choices the list of possible values that the drop-down list will contain
  47412. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  47413. These are the values that will be read and written to the
  47414. valueToControl value. This array must contain the same number of items
  47415. as the choices array
  47416. */
  47417. ChoicePropertyComponent (const Value& valueToControl,
  47418. const String& propertyName,
  47419. const StringArray& choices,
  47420. const Array <var>& correspondingValues);
  47421. /** Destructor. */
  47422. ~ChoicePropertyComponent();
  47423. /** Called when the user selects an item from the combo box.
  47424. Your subclass must use this callback to update the value that this component
  47425. represents. The index is the index of the chosen item in the choices
  47426. StringArray.
  47427. */
  47428. virtual void setIndex (int newIndex);
  47429. /** Returns the index of the item that should currently be shown.
  47430. This is the index of the item in the choices StringArray that will be
  47431. shown.
  47432. */
  47433. virtual int getIndex() const;
  47434. /** Returns the list of options. */
  47435. const StringArray& getChoices() const;
  47436. /** @internal */
  47437. void refresh();
  47438. /** @internal */
  47439. void comboBoxChanged (ComboBox*);
  47440. protected:
  47441. /** The list of options that will be shown in the combo box.
  47442. Your subclass must populate this array in its constructor. If any empty
  47443. strings are added, these will be replaced with horizontal separators (see
  47444. ComboBox::addSeparator() for more info).
  47445. */
  47446. StringArray choices;
  47447. private:
  47448. ComboBox comboBox;
  47449. bool isCustomClass;
  47450. class RemapperValueSource;
  47451. void createComboBox();
  47452. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChoicePropertyComponent);
  47453. };
  47454. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47455. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  47456. #endif
  47457. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  47458. #endif
  47459. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  47460. #endif
  47461. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  47462. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  47463. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  47464. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  47465. /**
  47466. A PropertyComponent that shows its value as a slider.
  47467. @see PropertyComponent, Slider
  47468. */
  47469. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  47470. private SliderListener // (can't use Slider::Listener due to idiotic VC2005 bug)
  47471. {
  47472. protected:
  47473. /** Creates the property component.
  47474. The ranges, interval and skew factor are passed to the Slider component.
  47475. If you need to customise the slider in other ways, your constructor can
  47476. access the slider member variable and change it directly.
  47477. */
  47478. SliderPropertyComponent (const String& propertyName,
  47479. double rangeMin,
  47480. double rangeMax,
  47481. double interval,
  47482. double skewFactor = 1.0);
  47483. public:
  47484. /** Creates the property component.
  47485. The ranges, interval and skew factor are passed to the Slider component.
  47486. If you need to customise the slider in other ways, your constructor can
  47487. access the slider member variable and change it directly.
  47488. */
  47489. SliderPropertyComponent (const Value& valueToControl,
  47490. const String& propertyName,
  47491. double rangeMin,
  47492. double rangeMax,
  47493. double interval,
  47494. double skewFactor = 1.0);
  47495. /** Destructor. */
  47496. ~SliderPropertyComponent();
  47497. /** Called when the user moves the slider to change its value.
  47498. Your subclass must use this method to update whatever item this property
  47499. represents.
  47500. */
  47501. virtual void setValue (double newValue);
  47502. /** Returns the value that the slider should show. */
  47503. virtual double getValue() const;
  47504. /** @internal */
  47505. void refresh();
  47506. /** @internal */
  47507. void sliderValueChanged (Slider*);
  47508. protected:
  47509. /** The slider component being used in this component.
  47510. Your subclass has access to this in case it needs to customise it in some way.
  47511. */
  47512. Slider slider;
  47513. private:
  47514. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPropertyComponent);
  47515. };
  47516. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  47517. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  47518. #endif
  47519. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  47520. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  47521. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  47522. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  47523. /**
  47524. A PropertyComponent that shows its value as editable text.
  47525. @see PropertyComponent
  47526. */
  47527. class JUCE_API TextPropertyComponent : public PropertyComponent
  47528. {
  47529. protected:
  47530. /** Creates a text property component.
  47531. The maxNumChars is used to set the length of string allowable, and isMultiLine
  47532. sets whether the text editor allows carriage returns.
  47533. @see TextEditor
  47534. */
  47535. TextPropertyComponent (const String& propertyName,
  47536. int maxNumChars,
  47537. bool isMultiLine);
  47538. public:
  47539. /** Creates a text property component.
  47540. The maxNumChars is used to set the length of string allowable, and isMultiLine
  47541. sets whether the text editor allows carriage returns.
  47542. @see TextEditor
  47543. */
  47544. TextPropertyComponent (const Value& valueToControl,
  47545. const String& propertyName,
  47546. int maxNumChars,
  47547. bool isMultiLine);
  47548. /** Destructor. */
  47549. ~TextPropertyComponent();
  47550. /** Called when the user edits the text.
  47551. Your subclass must use this callback to change the value of whatever item
  47552. this property component represents.
  47553. */
  47554. virtual void setText (const String& newText);
  47555. /** Returns the text that should be shown in the text editor.
  47556. */
  47557. virtual const String getText() const;
  47558. /** @internal */
  47559. void refresh();
  47560. /** @internal */
  47561. void textWasEdited();
  47562. private:
  47563. ScopedPointer<Label> textEditor;
  47564. void createEditor (int maxNumChars, bool isMultiLine);
  47565. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextPropertyComponent);
  47566. };
  47567. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  47568. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  47569. #endif
  47570. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  47571. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  47572. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  47573. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  47574. #if JUCE_WINDOWS || DOXYGEN
  47575. /**
  47576. A Windows-specific class that can create and embed an ActiveX control inside
  47577. itself.
  47578. To use it, create one of these, put it in place and make sure it's visible in a
  47579. window, then use createControl() to instantiate an ActiveX control. The control
  47580. will then be moved and resized to follow the movements of this component.
  47581. Of course, since the control is a heavyweight window, it'll obliterate any
  47582. juce components that may overlap this component, but that's life.
  47583. */
  47584. class JUCE_API ActiveXControlComponent : public Component
  47585. {
  47586. public:
  47587. /** Create an initially-empty container. */
  47588. ActiveXControlComponent();
  47589. /** Destructor. */
  47590. ~ActiveXControlComponent();
  47591. /** Tries to create an ActiveX control and embed it in this peer.
  47592. The peer controlIID is a pointer to an IID structure - it's treated
  47593. as a void* because when including the Juce headers, you might not always
  47594. have included windows.h first, in which case IID wouldn't be defined.
  47595. e.g. @code
  47596. const IID myIID = __uuidof (QTControl);
  47597. myControlComp->createControl (&myIID);
  47598. @endcode
  47599. */
  47600. bool createControl (const void* controlIID);
  47601. /** Deletes the ActiveX control, if one has been created.
  47602. */
  47603. void deleteControl();
  47604. /** Returns true if a control is currently in use. */
  47605. bool isControlOpen() const noexcept { return control != nullptr; }
  47606. /** Does a QueryInterface call on the embedded control object.
  47607. This allows you to cast the control to whatever type of COM object you need.
  47608. The iid parameter is a pointer to an IID structure - it's treated
  47609. as a void* because when including the Juce headers, you might not always
  47610. have included windows.h first, in which case IID wouldn't be defined, but
  47611. you should just pass a pointer to an IID.
  47612. e.g. @code
  47613. const IID iid = __uuidof (IOleWindow);
  47614. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  47615. if (oleWindow != nullptr)
  47616. {
  47617. HWND hwnd;
  47618. oleWindow->GetWindow (&hwnd);
  47619. ...
  47620. oleWindow->Release();
  47621. }
  47622. @endcode
  47623. */
  47624. void* queryInterface (const void* iid) const;
  47625. /** Set this to false to stop mouse events being allowed through to the control.
  47626. */
  47627. void setMouseEventsAllowed (bool eventsCanReachControl);
  47628. /** Returns true if mouse events are allowed to get through to the control.
  47629. */
  47630. bool areMouseEventsAllowed() const noexcept { return mouseEventsAllowed; }
  47631. /** @internal */
  47632. void paint (Graphics& g);
  47633. /** @internal */
  47634. void* originalWndProc;
  47635. private:
  47636. class Pimpl;
  47637. friend class Pimpl;
  47638. friend class ScopedPointer <Pimpl>;
  47639. ScopedPointer <Pimpl> control;
  47640. bool mouseEventsAllowed;
  47641. void setControlBounds (const Rectangle<int>& bounds) const;
  47642. void setControlVisible (bool b) const;
  47643. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ActiveXControlComponent);
  47644. };
  47645. #endif
  47646. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  47647. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  47648. #endif
  47649. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  47650. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  47651. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  47652. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  47653. /**
  47654. A component containing controls to let the user change the audio settings of
  47655. an AudioDeviceManager object.
  47656. Very easy to use - just create one of these and show it to the user.
  47657. @see AudioDeviceManager
  47658. */
  47659. class JUCE_API AudioDeviceSelectorComponent : public Component,
  47660. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  47661. public ButtonListener,
  47662. public ChangeListener
  47663. {
  47664. public:
  47665. /** Creates the component.
  47666. If your app needs only output channels, you might ask for a maximum of 0 input
  47667. channels, and the component won't display any options for choosing the input
  47668. channels. And likewise if you're doing an input-only app.
  47669. @param deviceManager the device manager that this component should control
  47670. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  47671. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  47672. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  47673. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  47674. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  47675. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  47676. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  47677. treated as a set of separate mono channels.
  47678. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  47679. are shown, with an "advanced" button that shows the rest of them
  47680. */
  47681. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  47682. const int minAudioInputChannels,
  47683. const int maxAudioInputChannels,
  47684. const int minAudioOutputChannels,
  47685. const int maxAudioOutputChannels,
  47686. const bool showMidiInputOptions,
  47687. const bool showMidiOutputSelector,
  47688. const bool showChannelsAsStereoPairs,
  47689. const bool hideAdvancedOptionsWithButton);
  47690. /** Destructor */
  47691. ~AudioDeviceSelectorComponent();
  47692. /** @internal */
  47693. void resized();
  47694. /** @internal */
  47695. void comboBoxChanged (ComboBox*);
  47696. /** @internal */
  47697. void buttonClicked (Button*);
  47698. /** @internal */
  47699. void changeListenerCallback (ChangeBroadcaster*);
  47700. /** @internal */
  47701. void childBoundsChanged (Component*);
  47702. private:
  47703. AudioDeviceManager& deviceManager;
  47704. ScopedPointer<ComboBox> deviceTypeDropDown;
  47705. ScopedPointer<Label> deviceTypeDropDownLabel;
  47706. ScopedPointer<Component> audioDeviceSettingsComp;
  47707. String audioDeviceSettingsCompType;
  47708. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  47709. const bool showChannelsAsStereoPairs;
  47710. const bool hideAdvancedOptionsWithButton;
  47711. class MidiInputSelectorComponentListBox;
  47712. friend class ScopedPointer<MidiInputSelectorComponentListBox>;
  47713. ScopedPointer<MidiInputSelectorComponentListBox> midiInputsList;
  47714. ScopedPointer<ComboBox> midiOutputSelector;
  47715. ScopedPointer<Label> midiInputsLabel, midiOutputLabel;
  47716. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceSelectorComponent);
  47717. };
  47718. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  47719. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  47720. #endif
  47721. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  47722. /*** Start of inlined file: juce_BubbleComponent.h ***/
  47723. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  47724. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  47725. /**
  47726. A component for showing a message or other graphics inside a speech-bubble-shaped
  47727. outline, pointing at a location on the screen.
  47728. This is a base class that just draws and positions the bubble shape, but leaves
  47729. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  47730. that draws a text message.
  47731. To use it, create your subclass, then either add it to a parent component or
  47732. put it on the desktop with addToDesktop (0), use setPosition() to
  47733. resize and position it, then make it visible.
  47734. @see BubbleMessageComponent
  47735. */
  47736. class JUCE_API BubbleComponent : public Component
  47737. {
  47738. protected:
  47739. /** Creates a BubbleComponent.
  47740. Your subclass will need to implement the getContentSize() and paintContent()
  47741. methods to draw the bubble's contents.
  47742. */
  47743. BubbleComponent();
  47744. public:
  47745. /** Destructor. */
  47746. ~BubbleComponent();
  47747. /** A list of permitted placements for the bubble, relative to the co-ordinates
  47748. at which it should be pointing.
  47749. @see setAllowedPlacement
  47750. */
  47751. enum BubblePlacement
  47752. {
  47753. above = 1,
  47754. below = 2,
  47755. left = 4,
  47756. right = 8
  47757. };
  47758. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  47759. point at which it's pointing.
  47760. By default when setPosition() is called, the bubble will place itself either
  47761. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  47762. the values in BubblePlacement to restrict this choice.
  47763. E.g. if you only want your bubble to appear above or below the target area,
  47764. use setAllowedPlacement (above | below);
  47765. @see BubblePlacement
  47766. */
  47767. void setAllowedPlacement (int newPlacement);
  47768. /** Moves and resizes the bubble to point at a given component.
  47769. This will resize the bubble to fit its content, then find a position for it
  47770. so that it's next to, but doesn't overlap the given component.
  47771. It'll put itself either above, below, or to the side of the component depending
  47772. on where there's the most space, honouring any restrictions that were set
  47773. with setAllowedPlacement().
  47774. */
  47775. void setPosition (Component* componentToPointTo);
  47776. /** Moves and resizes the bubble to point at a given point.
  47777. This will resize the bubble to fit its content, then position it
  47778. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  47779. are relative to either the bubble component's parent component if it has one, or
  47780. they are screen co-ordinates if not.
  47781. It'll put itself either above, below, or to the side of this point, depending
  47782. on where there's the most space, honouring any restrictions that were set
  47783. with setAllowedPlacement().
  47784. */
  47785. void setPosition (int arrowTipX,
  47786. int arrowTipY);
  47787. /** Moves and resizes the bubble to point at a given rectangle.
  47788. This will resize the bubble to fit its content, then find a position for it
  47789. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  47790. co-ordinates are relative to either the bubble component's parent component
  47791. if it has one, or they are screen co-ordinates if not.
  47792. It'll put itself either above, below, or to the side of the component depending
  47793. on where there's the most space, honouring any restrictions that were set
  47794. with setAllowedPlacement().
  47795. */
  47796. void setPosition (const Rectangle<int>& rectangleToPointTo);
  47797. protected:
  47798. /** Subclasses should override this to return the size of the content they
  47799. want to draw inside the bubble.
  47800. */
  47801. virtual void getContentSize (int& width, int& height) = 0;
  47802. /** Subclasses should override this to draw their bubble's contents.
  47803. The graphics object's clip region and the dimensions passed in here are
  47804. set up to paint just the rectangle inside the bubble.
  47805. */
  47806. virtual void paintContent (Graphics& g, int width, int height) = 0;
  47807. public:
  47808. /** @internal */
  47809. void paint (Graphics& g);
  47810. private:
  47811. Rectangle<int> content;
  47812. int side, allowablePlacements;
  47813. float arrowTipX, arrowTipY;
  47814. DropShadowEffect shadow;
  47815. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleComponent);
  47816. };
  47817. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  47818. /*** End of inlined file: juce_BubbleComponent.h ***/
  47819. #endif
  47820. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47821. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  47822. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47823. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47824. /**
  47825. A speech-bubble component that displays a short message.
  47826. This can be used to show a message with the tail of the speech bubble
  47827. pointing to a particular component or location on the screen.
  47828. @see BubbleComponent
  47829. */
  47830. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  47831. private Timer
  47832. {
  47833. public:
  47834. /** Creates a bubble component.
  47835. After creating one a BubbleComponent, do the following:
  47836. - add it to an appropriate parent component, or put it on the
  47837. desktop with Component::addToDesktop (0).
  47838. - use the showAt() method to show a message.
  47839. - it will make itself invisible after it times-out (and can optionally
  47840. also delete itself), or you can reuse it somewhere else by calling
  47841. showAt() again.
  47842. */
  47843. BubbleMessageComponent (int fadeOutLengthMs = 150);
  47844. /** Destructor. */
  47845. ~BubbleMessageComponent();
  47846. /** Shows a message bubble at a particular position.
  47847. This shows the bubble with its stem pointing to the given location
  47848. (co-ordinates being relative to its parent component).
  47849. For details about exactly how it decides where to position itself, see
  47850. BubbleComponent::updatePosition().
  47851. @param x the x co-ordinate of end of the bubble's tail
  47852. @param y the y co-ordinate of end of the bubble's tail
  47853. @param message the text to display
  47854. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  47855. from its parent compnent. If this is 0 or less, it
  47856. will stay there until manually removed.
  47857. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  47858. mouse button is pressed (anywhere on the screen)
  47859. @param deleteSelfAfterUse if true, then the component will delete itself after
  47860. it becomes invisible
  47861. */
  47862. void showAt (int x, int y,
  47863. const String& message,
  47864. int numMillisecondsBeforeRemoving,
  47865. bool removeWhenMouseClicked = true,
  47866. bool deleteSelfAfterUse = false);
  47867. /** Shows a message bubble next to a particular component.
  47868. This shows the bubble with its stem pointing at the given component.
  47869. For details about exactly how it decides where to position itself, see
  47870. BubbleComponent::updatePosition().
  47871. @param component the component that you want to point at
  47872. @param message the text to display
  47873. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  47874. from its parent compnent. If this is 0 or less, it
  47875. will stay there until manually removed.
  47876. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  47877. mouse button is pressed (anywhere on the screen)
  47878. @param deleteSelfAfterUse if true, then the component will delete itself after
  47879. it becomes invisible
  47880. */
  47881. void showAt (Component* component,
  47882. const String& message,
  47883. int numMillisecondsBeforeRemoving,
  47884. bool removeWhenMouseClicked = true,
  47885. bool deleteSelfAfterUse = false);
  47886. /** @internal */
  47887. void getContentSize (int& w, int& h);
  47888. /** @internal */
  47889. void paintContent (Graphics& g, int w, int h);
  47890. /** @internal */
  47891. void timerCallback();
  47892. private:
  47893. int fadeOutLength, mouseClickCounter;
  47894. TextLayout textLayout;
  47895. int64 expiryTime;
  47896. bool deleteAfterUse;
  47897. void init (int numMillisecondsBeforeRemoving,
  47898. bool removeWhenMouseClicked,
  47899. bool deleteSelfAfterUse);
  47900. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleMessageComponent);
  47901. };
  47902. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47903. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  47904. #endif
  47905. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  47906. /*** Start of inlined file: juce_ColourSelector.h ***/
  47907. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  47908. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  47909. /**
  47910. A component that lets the user choose a colour.
  47911. This shows RGB sliders and a colourspace that the user can pick colours from.
  47912. This class is also a ChangeBroadcaster, so listeners can register to be told
  47913. when the colour changes.
  47914. */
  47915. class JUCE_API ColourSelector : public Component,
  47916. public ChangeBroadcaster,
  47917. protected SliderListener
  47918. {
  47919. public:
  47920. /** Options for the type of selector to show. These are passed into the constructor. */
  47921. enum ColourSelectorOptions
  47922. {
  47923. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  47924. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  47925. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  47926. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  47927. };
  47928. /** Creates a ColourSelector object.
  47929. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  47930. which of the selector's features should be visible.
  47931. The edgeGap value specifies the amount of space to leave around the edge.
  47932. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  47933. colourspace and hue selector components.
  47934. */
  47935. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  47936. int edgeGap = 4,
  47937. int gapAroundColourSpaceComponent = 7);
  47938. /** Destructor. */
  47939. ~ColourSelector();
  47940. /** Returns the colour that the user has currently selected.
  47941. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  47942. register to be told when the colour changes.
  47943. @see setCurrentColour
  47944. */
  47945. const Colour getCurrentColour() const;
  47946. /** Changes the colour that is currently being shown.
  47947. */
  47948. void setCurrentColour (const Colour& newColour);
  47949. /** Tells the selector how many preset colour swatches you want to have on the component.
  47950. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47951. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47952. their values.
  47953. */
  47954. virtual int getNumSwatches() const;
  47955. /** Called by the selector to find out the colour of one of the swatches.
  47956. Your subclass should return the colour of the swatch with the given index.
  47957. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47958. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47959. their values.
  47960. */
  47961. virtual const Colour getSwatchColour (int index) const;
  47962. /** Called by the selector when the user puts a new colour into one of the swatches.
  47963. Your subclass should change the colour of the swatch with the given index.
  47964. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47965. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47966. their values.
  47967. */
  47968. virtual void setSwatchColour (int index, const Colour& newColour) const;
  47969. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  47970. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  47971. methods.
  47972. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  47973. */
  47974. enum ColourIds
  47975. {
  47976. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  47977. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  47978. };
  47979. private:
  47980. class ColourSpaceView;
  47981. class HueSelectorComp;
  47982. class SwatchComponent;
  47983. friend class ColourSpaceView;
  47984. friend class ScopedPointer<ColourSpaceView>;
  47985. friend class HueSelectorComp;
  47986. friend class ScopedPointer<HueSelectorComp>;
  47987. Colour colour;
  47988. float h, s, v;
  47989. ScopedPointer<Slider> sliders[4];
  47990. ScopedPointer<ColourSpaceView> colourSpace;
  47991. ScopedPointer<HueSelectorComp> hueSelector;
  47992. OwnedArray <SwatchComponent> swatchComponents;
  47993. const int flags;
  47994. int edgeGap;
  47995. Rectangle<int> previewArea;
  47996. void setHue (float newH);
  47997. void setSV (float newS, float newV);
  47998. void updateHSV();
  47999. void update();
  48000. void sliderValueChanged (Slider*);
  48001. void paint (Graphics& g);
  48002. void resized();
  48003. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ColourSelector);
  48004. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  48005. // This constructor is here temporarily to prevent old code compiling, because the parameters
  48006. // have changed - if you get an error here, update your code to use the new constructor instead..
  48007. ColourSelector (bool);
  48008. #endif
  48009. };
  48010. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  48011. /*** End of inlined file: juce_ColourSelector.h ***/
  48012. #endif
  48013. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  48014. #endif
  48015. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48016. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  48017. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48018. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48019. /**
  48020. A component that displays a piano keyboard, whose notes can be clicked on.
  48021. This component will mimic a physical midi keyboard, showing the current state of
  48022. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  48023. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  48024. Another feature is that the computer keyboard can also be used to play notes. By
  48025. default it maps the top two rows of a standard querty keyboard to the notes, but
  48026. these can be remapped if needed. It will only respond to keypresses when it has
  48027. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  48028. The component is also a ChangeBroadcaster, so if you want to be informed when the
  48029. keyboard is scrolled, you can register a ChangeListener for callbacks.
  48030. @see MidiKeyboardState
  48031. */
  48032. class JUCE_API MidiKeyboardComponent : public Component,
  48033. public MidiKeyboardStateListener,
  48034. public ChangeBroadcaster,
  48035. private Timer,
  48036. private AsyncUpdater
  48037. {
  48038. public:
  48039. /** The direction of the keyboard.
  48040. @see setOrientation
  48041. */
  48042. enum Orientation
  48043. {
  48044. horizontalKeyboard,
  48045. verticalKeyboardFacingLeft,
  48046. verticalKeyboardFacingRight,
  48047. };
  48048. /** Creates a MidiKeyboardComponent.
  48049. @param state the midi keyboard model that this component will represent
  48050. @param orientation whether the keyboard is horizonal or vertical
  48051. */
  48052. MidiKeyboardComponent (MidiKeyboardState& state,
  48053. Orientation orientation);
  48054. /** Destructor. */
  48055. ~MidiKeyboardComponent();
  48056. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  48057. on the component.
  48058. Values are 0 to 1.0, where 1.0 is the heaviest.
  48059. @see setMidiChannel
  48060. */
  48061. void setVelocity (float velocity, bool useMousePositionForVelocity);
  48062. /** Changes the midi channel number that will be used for events triggered by clicking
  48063. on the component.
  48064. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  48065. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  48066. Although this is the channel used for outgoing events, the component can display
  48067. incoming events from more than one channel - see setMidiChannelsToDisplay()
  48068. @see setVelocity
  48069. */
  48070. void setMidiChannel (int midiChannelNumber);
  48071. /** Returns the midi channel that the keyboard is using for midi messages.
  48072. @see setMidiChannel
  48073. */
  48074. int getMidiChannel() const noexcept { return midiChannel; }
  48075. /** Sets a mask to indicate which incoming midi channels should be represented by
  48076. key movements.
  48077. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  48078. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  48079. in this mask, the on-screen keys will also go down.
  48080. By default, this mask is set to 0xffff (all channels displayed).
  48081. @see setMidiChannel
  48082. */
  48083. void setMidiChannelsToDisplay (int midiChannelMask);
  48084. /** Returns the current set of midi channels represented by the component.
  48085. This is the value that was set with setMidiChannelsToDisplay().
  48086. */
  48087. int getMidiChannelsToDisplay() const noexcept { return midiInChannelMask; }
  48088. /** Changes the width used to draw the white keys. */
  48089. void setKeyWidth (float widthInPixels);
  48090. /** Returns the width that was set by setKeyWidth(). */
  48091. float getKeyWidth() const noexcept { return keyWidth; }
  48092. /** Changes the keyboard's current direction. */
  48093. void setOrientation (Orientation newOrientation);
  48094. /** Returns the keyboard's current direction. */
  48095. const Orientation getOrientation() const noexcept { return orientation; }
  48096. /** Sets the range of midi notes that the keyboard will be limited to.
  48097. By default the range is 0 to 127 (inclusive), but you can limit this if you
  48098. only want a restricted set of the keys to be shown.
  48099. Note that the values here are inclusive and must be between 0 and 127.
  48100. */
  48101. void setAvailableRange (int lowestNote,
  48102. int highestNote);
  48103. /** Returns the first note in the available range.
  48104. @see setAvailableRange
  48105. */
  48106. int getRangeStart() const noexcept { return rangeStart; }
  48107. /** Returns the last note in the available range.
  48108. @see setAvailableRange
  48109. */
  48110. int getRangeEnd() const noexcept { return rangeEnd; }
  48111. /** If the keyboard extends beyond the size of the component, this will scroll
  48112. it to show the given key at the start.
  48113. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  48114. base class to send a callback to any ChangeListeners that have been registered.
  48115. */
  48116. void setLowestVisibleKey (int noteNumber);
  48117. /** Returns the number of the first key shown in the component.
  48118. @see setLowestVisibleKey
  48119. */
  48120. int getLowestVisibleKey() const noexcept { return firstKey; }
  48121. /** Returns the length of the black notes.
  48122. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  48123. */
  48124. int getBlackNoteLength() const noexcept { return blackNoteLength; }
  48125. /** If set to true, then scroll buttons will appear at either end of the keyboard
  48126. if there are too many notes to fit them all in the component at once.
  48127. */
  48128. void setScrollButtonsVisible (bool canScroll);
  48129. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  48130. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  48131. methods.
  48132. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  48133. */
  48134. enum ColourIds
  48135. {
  48136. whiteNoteColourId = 0x1005000,
  48137. blackNoteColourId = 0x1005001,
  48138. keySeparatorLineColourId = 0x1005002,
  48139. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  48140. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  48141. textLabelColourId = 0x1005005,
  48142. upDownButtonBackgroundColourId = 0x1005006,
  48143. upDownButtonArrowColourId = 0x1005007
  48144. };
  48145. /** Returns the position within the component of the left-hand edge of a key.
  48146. Depending on the keyboard's orientation, this may be a horizontal or vertical
  48147. distance, in either direction.
  48148. */
  48149. int getKeyStartPosition (const int midiNoteNumber) const;
  48150. /** Deletes all key-mappings.
  48151. @see setKeyPressForNote
  48152. */
  48153. void clearKeyMappings();
  48154. /** Maps a key-press to a given note.
  48155. @param key the key that should trigger the note
  48156. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  48157. be. The actual midi note that gets played will be
  48158. this value + (12 * the current base octave). To change
  48159. the base octave, see setKeyPressBaseOctave()
  48160. */
  48161. void setKeyPressForNote (const KeyPress& key,
  48162. int midiNoteOffsetFromC);
  48163. /** Removes any key-mappings for a given note.
  48164. For a description of what the note number means, see setKeyPressForNote().
  48165. */
  48166. void removeKeyPressForNote (int midiNoteOffsetFromC);
  48167. /** Changes the base note above which key-press-triggered notes are played.
  48168. The set of key-mappings that trigger notes can be moved up and down to cover
  48169. the entire scale using this method.
  48170. The value passed in is an octave number between 0 and 10 (inclusive), and
  48171. indicates which C is the base note to which the key-mapped notes are
  48172. relative.
  48173. */
  48174. void setKeyPressBaseOctave (int newOctaveNumber);
  48175. /** This sets the octave number which is shown as the octave number for middle C.
  48176. This affects only the default implementation of getWhiteNoteText(), which
  48177. passes this octave number to MidiMessage::getMidiNoteName() in order to
  48178. get the note text. See MidiMessage::getMidiNoteName() for more info about
  48179. the parameter.
  48180. By default this value is set to 3.
  48181. @see getOctaveForMiddleC
  48182. */
  48183. void setOctaveForMiddleC (int octaveNumForMiddleC);
  48184. /** This returns the value set by setOctaveForMiddleC().
  48185. @see setOctaveForMiddleC
  48186. */
  48187. int getOctaveForMiddleC() const noexcept { return octaveNumForMiddleC; }
  48188. /** @internal */
  48189. void paint (Graphics& g);
  48190. /** @internal */
  48191. void resized();
  48192. /** @internal */
  48193. void mouseMove (const MouseEvent& e);
  48194. /** @internal */
  48195. void mouseDrag (const MouseEvent& e);
  48196. /** @internal */
  48197. void mouseDown (const MouseEvent& e);
  48198. /** @internal */
  48199. void mouseUp (const MouseEvent& e);
  48200. /** @internal */
  48201. void mouseEnter (const MouseEvent& e);
  48202. /** @internal */
  48203. void mouseExit (const MouseEvent& e);
  48204. /** @internal */
  48205. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  48206. /** @internal */
  48207. void timerCallback();
  48208. /** @internal */
  48209. bool keyStateChanged (bool isKeyDown);
  48210. /** @internal */
  48211. void focusLost (FocusChangeType cause);
  48212. /** @internal */
  48213. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  48214. /** @internal */
  48215. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  48216. /** @internal */
  48217. void handleAsyncUpdate();
  48218. /** @internal */
  48219. void colourChanged();
  48220. protected:
  48221. /** Draws a white note in the given rectangle.
  48222. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  48223. currently pressed down.
  48224. When doing this, be sure to note the keyboard's orientation.
  48225. */
  48226. virtual void drawWhiteNote (int midiNoteNumber,
  48227. Graphics& g,
  48228. int x, int y, int w, int h,
  48229. bool isDown, bool isOver,
  48230. const Colour& lineColour,
  48231. const Colour& textColour);
  48232. /** Draws a black note in the given rectangle.
  48233. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  48234. currently pressed down.
  48235. When doing this, be sure to note the keyboard's orientation.
  48236. */
  48237. virtual void drawBlackNote (int midiNoteNumber,
  48238. Graphics& g,
  48239. int x, int y, int w, int h,
  48240. bool isDown, bool isOver,
  48241. const Colour& noteFillColour);
  48242. /** Allows text to be drawn on the white notes.
  48243. By default this is used to label the C in each octave, but could be used for other things.
  48244. @see setOctaveForMiddleC
  48245. */
  48246. virtual const String getWhiteNoteText (const int midiNoteNumber);
  48247. /** Draws the up and down buttons that change the base note. */
  48248. virtual void drawUpDownButton (Graphics& g, int w, int h,
  48249. const bool isMouseOver,
  48250. const bool isButtonPressed,
  48251. const bool movesOctavesUp);
  48252. /** Callback when the mouse is clicked on a key.
  48253. You could use this to do things like handle right-clicks on keys, etc.
  48254. Return true if you want the click to trigger the note, or false if you
  48255. want to handle it yourself and not have the note played.
  48256. @see mouseDraggedToKey
  48257. */
  48258. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  48259. /** Callback when the mouse is dragged from one key onto another.
  48260. @see mouseDownOnKey
  48261. */
  48262. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  48263. /** Calculates the positon of a given midi-note.
  48264. This can be overridden to create layouts with custom key-widths.
  48265. @param midiNoteNumber the note to find
  48266. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  48267. @param x the x position of the left-hand edge of the key (this method
  48268. always works in terms of a horizontal keyboard)
  48269. @param w the width of the key
  48270. */
  48271. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  48272. int& x, int& w) const;
  48273. private:
  48274. friend class MidiKeyboardUpDownButton;
  48275. MidiKeyboardState& state;
  48276. int xOffset, blackNoteLength;
  48277. float keyWidth;
  48278. Orientation orientation;
  48279. int midiChannel, midiInChannelMask;
  48280. float velocity;
  48281. int noteUnderMouse, mouseDownNote;
  48282. BigInteger keysPressed, keysCurrentlyDrawnDown;
  48283. int rangeStart, rangeEnd, firstKey;
  48284. bool canScroll, mouseDragging, useMousePositionForVelocity;
  48285. ScopedPointer<Button> scrollDown, scrollUp;
  48286. Array <KeyPress> keyPresses;
  48287. Array <int> keyPressNotes;
  48288. int keyMappingOctave;
  48289. int octaveNumForMiddleC;
  48290. static const uint8 whiteNotes[];
  48291. static const uint8 blackNotes[];
  48292. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  48293. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  48294. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  48295. void resetAnyKeysInUse();
  48296. void updateNoteUnderMouse (const Point<int>& pos);
  48297. void repaintNote (const int midiNoteNumber);
  48298. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardComponent);
  48299. };
  48300. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48301. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  48302. #endif
  48303. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48304. /*** Start of inlined file: juce_NSViewComponent.h ***/
  48305. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48306. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48307. #if ! DOXYGEN
  48308. class NSViewComponentInternal;
  48309. #endif
  48310. #if JUCE_MAC || DOXYGEN
  48311. /**
  48312. A Mac-specific class that can create and embed an NSView inside itself.
  48313. To use it, create one of these, put it in place and make sure it's visible in a
  48314. window, then use setView() to assign an NSView to it. The view will then be
  48315. moved and resized to follow the movements of this component.
  48316. Of course, since the view is a native object, it'll obliterate any
  48317. juce components that may overlap this component, but that's life.
  48318. */
  48319. class JUCE_API NSViewComponent : public Component
  48320. {
  48321. public:
  48322. /** Create an initially-empty container. */
  48323. NSViewComponent();
  48324. /** Destructor. */
  48325. ~NSViewComponent();
  48326. /** Assigns an NSView to this peer.
  48327. The view will be retained and released by this component for as long as
  48328. it is needed. To remove the current view, just call setView (nullptr).
  48329. Note: a void* is used here to avoid including the cocoa headers as
  48330. part of the juce.h, but the method expects an NSView*.
  48331. */
  48332. void setView (void* nsView);
  48333. /** Returns the current NSView.
  48334. Note: a void* is returned here to avoid including the cocoa headers as
  48335. a requirement of juce.h, so you should just cast the object to an NSView*.
  48336. */
  48337. void* getView() const;
  48338. /** Resizes this component to fit the view that it contains. */
  48339. void resizeToFitView();
  48340. /** @internal */
  48341. void paint (Graphics& g);
  48342. private:
  48343. friend class NSViewComponentInternal;
  48344. ScopedPointer <NSViewComponentInternal> info;
  48345. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponent);
  48346. };
  48347. #endif
  48348. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48349. /*** End of inlined file: juce_NSViewComponent.h ***/
  48350. #endif
  48351. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48352. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  48353. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48354. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48355. // this is used to disable OpenGL, and is defined in juce_Config.h
  48356. #if JUCE_OPENGL || DOXYGEN
  48357. /**
  48358. Represents the various properties of an OpenGL bitmap format.
  48359. @see OpenGLComponent::setPixelFormat
  48360. */
  48361. class JUCE_API OpenGLPixelFormat
  48362. {
  48363. public:
  48364. /** Creates an OpenGLPixelFormat.
  48365. The default constructor just initialises the object as a simple 8-bit
  48366. RGBA format.
  48367. */
  48368. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  48369. int alphaBits = 8,
  48370. int depthBufferBits = 16,
  48371. int stencilBufferBits = 0);
  48372. OpenGLPixelFormat (const OpenGLPixelFormat&);
  48373. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  48374. bool operator== (const OpenGLPixelFormat&) const;
  48375. int redBits; /**< The number of bits per pixel to use for the red channel. */
  48376. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  48377. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  48378. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  48379. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  48380. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  48381. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  48382. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  48383. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  48384. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  48385. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  48386. /** Returns a list of all the pixel formats that can be used in this system.
  48387. A reference component is needed in case there are multiple screens with different
  48388. capabilities - in which case, the one that the component is on will be used.
  48389. */
  48390. static void getAvailablePixelFormats (Component* component,
  48391. OwnedArray <OpenGLPixelFormat>& results);
  48392. private:
  48393. JUCE_LEAK_DETECTOR (OpenGLPixelFormat);
  48394. };
  48395. /**
  48396. A base class for types of OpenGL context.
  48397. An OpenGLComponent will supply its own context for drawing in its window.
  48398. */
  48399. class JUCE_API OpenGLContext
  48400. {
  48401. public:
  48402. /** Destructor. */
  48403. virtual ~OpenGLContext();
  48404. /** Makes this context the currently active one. */
  48405. virtual bool makeActive() const noexcept = 0;
  48406. /** If this context is currently active, it is disactivated. */
  48407. virtual bool makeInactive() const noexcept = 0;
  48408. /** Returns true if this context is currently active. */
  48409. virtual bool isActive() const noexcept = 0;
  48410. /** Swaps the buffers (if the context can do this). */
  48411. virtual void swapBuffers() = 0;
  48412. /** Sets whether the context checks the vertical sync before swapping.
  48413. The value is the number of frames to allow between buffer-swapping. This is
  48414. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  48415. and greater numbers indicate that it should swap less often.
  48416. Returns true if it sets the value successfully.
  48417. */
  48418. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  48419. /** Returns the current swap-sync interval.
  48420. See setSwapInterval() for info about the value returned.
  48421. */
  48422. virtual int getSwapInterval() const = 0;
  48423. /** Returns the pixel format being used by this context. */
  48424. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  48425. /** For windowed contexts, this moves the context within the bounds of
  48426. its parent window.
  48427. */
  48428. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  48429. /** For windowed contexts, this triggers a repaint of the window.
  48430. (Not relevent on all platforms).
  48431. */
  48432. virtual void repaint() = 0;
  48433. /** Returns an OS-dependent handle to the raw GL context.
  48434. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  48435. a GLXContext.
  48436. */
  48437. virtual void* getRawContext() const noexcept = 0;
  48438. /** Deletes the context.
  48439. This must only be called on the message thread, or will deadlock.
  48440. On background threads, call getCurrentContext()->deleteContext(), but be careful not
  48441. to call any other OpenGL function afterwards.
  48442. This doesn't touch other resources, such as window handles, etc.
  48443. You'll probably never have to call this method directly.
  48444. */
  48445. virtual void deleteContext() = 0;
  48446. /** Returns the context that's currently in active use by the calling thread.
  48447. Returns 0 if there isn't an active context.
  48448. */
  48449. static OpenGLContext* getCurrentContext();
  48450. protected:
  48451. OpenGLContext() noexcept;
  48452. private:
  48453. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLContext);
  48454. };
  48455. /**
  48456. A component that contains an OpenGL canvas.
  48457. Override this, add it to whatever component you want to, and use the renderOpenGL()
  48458. method to draw its contents.
  48459. */
  48460. class JUCE_API OpenGLComponent : public Component
  48461. {
  48462. public:
  48463. /** Used to select the type of openGL API to use, if more than one choice is available
  48464. on a particular platform.
  48465. */
  48466. enum OpenGLType
  48467. {
  48468. openGLDefault = 0,
  48469. #if JUCE_IOS
  48470. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  48471. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  48472. #endif
  48473. };
  48474. /** Creates an OpenGLComponent. */
  48475. OpenGLComponent (OpenGLType type = openGLDefault);
  48476. /** Destructor. */
  48477. ~OpenGLComponent();
  48478. /** Changes the pixel format used by this component.
  48479. @see OpenGLPixelFormat::getAvailablePixelFormats()
  48480. */
  48481. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  48482. /** Returns the pixel format that this component is currently using. */
  48483. const OpenGLPixelFormat getPixelFormat() const;
  48484. /** Specifies an OpenGL context which should be shared with the one that this
  48485. component is using.
  48486. This is an OpenGL feature that lets two contexts share their texture data.
  48487. Note that this pointer is stored by the component, and when the component
  48488. needs to recreate its internal context for some reason, the same context
  48489. will be used again to share lists. So if you pass a context in here,
  48490. don't delete the context while this component is still using it! You can
  48491. call shareWith (nullptr) to stop this component from sharing with it.
  48492. */
  48493. void shareWith (OpenGLContext* contextToShareListsWith);
  48494. /** Returns the context that this component is sharing with.
  48495. @see shareWith
  48496. */
  48497. OpenGLContext* getShareContext() const noexcept { return contextToShareListsWith; }
  48498. /** Flips the openGL buffers over. */
  48499. void swapBuffers();
  48500. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  48501. When this is called, makeCurrentContextActive() will already have been called
  48502. for you, so you just need to draw.
  48503. */
  48504. virtual void renderOpenGL() = 0;
  48505. /** This method is called when the component creates a new OpenGL context.
  48506. A new context may be created when the component is first used, or when it
  48507. is moved to a different window, or when the window is hidden and re-shown,
  48508. etc.
  48509. You can use this callback as an opportunity to set up things like textures
  48510. that your context needs.
  48511. New contexts are created on-demand by the makeCurrentContextActive() method - so
  48512. if the context is deleted, e.g. by changing the pixel format or window, no context
  48513. will be created until the next call to makeCurrentContextActive(), which will
  48514. synchronously create one and call this method. This means that if you're using
  48515. a non-GUI thread for rendering, you can make sure this method is be called by
  48516. your renderer thread.
  48517. When this callback happens, the context will already have been made current
  48518. using the makeCurrentContextActive() method, so there's no need to call it
  48519. again in your code.
  48520. */
  48521. virtual void newOpenGLContextCreated() = 0;
  48522. /** Returns the context that will draw into this component.
  48523. This may return 0 if the component is currently invisible or hasn't currently
  48524. got a context. The context object can be deleted and a new one created during
  48525. the lifetime of this component, and there may be times when it doesn't have one.
  48526. @see newOpenGLContextCreated()
  48527. */
  48528. OpenGLContext* getCurrentContext() const noexcept { return context; }
  48529. /** Makes this component the current openGL context.
  48530. You might want to use this in things like your resize() method, before calling
  48531. GL commands.
  48532. If this returns false, then the context isn't active, so you should avoid
  48533. making any calls.
  48534. This call may actually create a context if one isn't currently initialised. If
  48535. it does this, it will also synchronously call the newOpenGLContextCreated()
  48536. method to let you initialise it as necessary.
  48537. @see OpenGLContext::makeActive
  48538. */
  48539. bool makeCurrentContextActive();
  48540. /** Stops the current component being the active OpenGL context.
  48541. This is the opposite of makeCurrentContextActive()
  48542. @see OpenGLContext::makeInactive
  48543. */
  48544. void makeCurrentContextInactive();
  48545. /** Returns true if this component is the active openGL context for the
  48546. current thread.
  48547. @see OpenGLContext::isActive
  48548. */
  48549. bool isActiveContext() const noexcept;
  48550. /** Calls the rendering callback, and swaps the buffers afterwards.
  48551. This is called automatically by paint() when the component needs to be rendered.
  48552. It can be overridden if you need to decouple the rendering from the paint callback
  48553. and render with a custom thread.
  48554. Returns true if the operation succeeded.
  48555. */
  48556. virtual bool renderAndSwapBuffers();
  48557. /** This returns a critical section that can be used to lock the current context.
  48558. Because the context that is used by this component can change, e.g. when the
  48559. component is shown or hidden, then if you're rendering to it on a background
  48560. thread, this allows you to lock the context for the duration of your rendering
  48561. routine.
  48562. */
  48563. CriticalSection& getContextLock() noexcept { return contextLock; }
  48564. /** Returns the native handle of an embedded heavyweight window, if there is one.
  48565. E.g. On windows, this will return the HWND of the sub-window containing
  48566. the opengl context, on the mac it'll be the NSOpenGLView.
  48567. */
  48568. void* getNativeWindowHandle() const;
  48569. /** Delete the context.
  48570. This can be called back on the same thread that created the context. */
  48571. void deleteContext();
  48572. /** @internal */
  48573. void paint (Graphics& g);
  48574. private:
  48575. const OpenGLType type;
  48576. class OpenGLComponentWatcher;
  48577. friend class OpenGLComponentWatcher;
  48578. friend class ScopedPointer <OpenGLComponentWatcher>;
  48579. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  48580. ScopedPointer <OpenGLContext> context;
  48581. OpenGLContext* contextToShareListsWith;
  48582. CriticalSection contextLock;
  48583. OpenGLPixelFormat preferredPixelFormat;
  48584. bool needToUpdateViewport;
  48585. OpenGLContext* createContext();
  48586. void updateContextPosition();
  48587. void internalRepaint (int x, int y, int w, int h);
  48588. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponent);
  48589. };
  48590. #endif
  48591. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48592. /*** End of inlined file: juce_OpenGLComponent.h ***/
  48593. #endif
  48594. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  48595. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  48596. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  48597. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  48598. /**
  48599. A component with a set of buttons at the top for changing between pages of
  48600. preferences.
  48601. This is just a handy way of writing a Mac-style preferences panel where you
  48602. have a row of buttons along the top for the different preference categories,
  48603. each button having an icon above its name. Clicking these will show an
  48604. appropriate prefs page below it.
  48605. You can either put one of these inside your own component, or just use the
  48606. showInDialogBox() method to show it in a window and run it modally.
  48607. To use it, just add a set of named pages with the addSettingsPage() method,
  48608. and implement the createComponentForPage() method to create suitable components
  48609. for each of these pages.
  48610. */
  48611. class JUCE_API PreferencesPanel : public Component,
  48612. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  48613. {
  48614. public:
  48615. /** Creates an empty panel.
  48616. Use addSettingsPage() to add some pages to it in your constructor.
  48617. */
  48618. PreferencesPanel();
  48619. /** Destructor. */
  48620. ~PreferencesPanel();
  48621. /** Creates a page using a set of drawables to define the page's icon.
  48622. Note that the other version of this method is much easier if you're using
  48623. an image instead of a custom drawable.
  48624. @param pageTitle the name of this preferences page - you'll need to
  48625. make sure your createComponentForPage() method creates
  48626. a suitable component when it is passed this name
  48627. @param normalIcon the drawable to display in the page's button normally
  48628. @param overIcon the drawable to display in the page's button when the mouse is over
  48629. @param downIcon the drawable to display in the page's button when the button is down
  48630. @see DrawableButton
  48631. */
  48632. void addSettingsPage (const String& pageTitle,
  48633. const Drawable* normalIcon,
  48634. const Drawable* overIcon,
  48635. const Drawable* downIcon);
  48636. /** Creates a page using a set of drawables to define the page's icon.
  48637. The other version of this method gives you more control over the icon, but this
  48638. one is much easier if you're just loading it from a file.
  48639. @param pageTitle the name of this preferences page - you'll need to
  48640. make sure your createComponentForPage() method creates
  48641. a suitable component when it is passed this name
  48642. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  48643. For this to look good, you'll probably want to use a nice
  48644. transparent png file.
  48645. @param imageDataSize the size of the image data, in bytes
  48646. */
  48647. void addSettingsPage (const String& pageTitle,
  48648. const void* imageData,
  48649. int imageDataSize);
  48650. /** Utility method to display this panel in a DialogWindow.
  48651. Calling this will create a DialogWindow containing this panel with the
  48652. given size and title, and will run it modally, returning when the user
  48653. closes the dialog box.
  48654. */
  48655. void showInDialogBox (const String& dialogTitle,
  48656. int dialogWidth,
  48657. int dialogHeight,
  48658. const Colour& backgroundColour = Colours::white);
  48659. /** Subclasses must override this to return a component for each preferences page.
  48660. The subclass should return a pointer to a new component representing the named
  48661. page, which the panel will then display.
  48662. The panel will delete the component later when the user goes to another page
  48663. or deletes the panel.
  48664. */
  48665. virtual Component* createComponentForPage (const String& pageName) = 0;
  48666. /** Changes the current page being displayed. */
  48667. void setCurrentPage (const String& pageName);
  48668. /** Returns the size of the buttons shown along the top. */
  48669. int getButtonSize() const noexcept;
  48670. /** Changes the size of the buttons shown along the top. */
  48671. void setButtonSize (int newSize);
  48672. /** @internal */
  48673. void resized();
  48674. /** @internal */
  48675. void paint (Graphics& g);
  48676. /** @internal */
  48677. void buttonClicked (Button* button);
  48678. private:
  48679. String currentPageName;
  48680. ScopedPointer <Component> currentPage;
  48681. OwnedArray<DrawableButton> buttons;
  48682. int buttonSize;
  48683. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreferencesPanel);
  48684. };
  48685. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  48686. /*** End of inlined file: juce_PreferencesPanel.h ***/
  48687. #endif
  48688. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  48689. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  48690. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  48691. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  48692. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  48693. // amalgamated build)
  48694. #ifndef DOXYGEN
  48695. #if JUCE_WINDOWS
  48696. typedef ActiveXControlComponent QTCompBaseClass;
  48697. #elif JUCE_MAC
  48698. typedef NSViewComponent QTCompBaseClass;
  48699. #endif
  48700. #endif
  48701. // this is used to disable QuickTime, and is defined in juce_Config.h
  48702. #if JUCE_QUICKTIME || DOXYGEN
  48703. /**
  48704. A window that can play back a QuickTime movie.
  48705. */
  48706. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  48707. {
  48708. public:
  48709. /** Creates a QuickTimeMovieComponent, initially blank.
  48710. Use the loadMovie() method to load a movie once you've added the
  48711. component to a window, (or put it on the desktop as a heavyweight window).
  48712. Loading a movie when the component isn't visible can cause problems, as
  48713. QuickTime needs a window handle to initialise properly.
  48714. */
  48715. QuickTimeMovieComponent();
  48716. /** Destructor. */
  48717. ~QuickTimeMovieComponent();
  48718. /** Returns true if QT is installed and working on this machine.
  48719. */
  48720. static bool isQuickTimeAvailable() noexcept;
  48721. /** Tries to load a QuickTime movie from a file into the player.
  48722. It's best to call this function once you've added the component to a window,
  48723. (or put it on the desktop as a heavyweight window). Loading a movie when the
  48724. component isn't visible can cause problems, because QuickTime needs a window
  48725. handle to do its stuff.
  48726. @param movieFile the .mov file to open
  48727. @param isControllerVisible whether to show a controller bar at the bottom
  48728. @returns true if the movie opens successfully
  48729. */
  48730. bool loadMovie (const File& movieFile,
  48731. bool isControllerVisible);
  48732. /** Tries to load a QuickTime movie from a URL into the player.
  48733. It's best to call this function once you've added the component to a window,
  48734. (or put it on the desktop as a heavyweight window). Loading a movie when the
  48735. component isn't visible can cause problems, because QuickTime needs a window
  48736. handle to do its stuff.
  48737. @param movieURL the .mov file to open
  48738. @param isControllerVisible whether to show a controller bar at the bottom
  48739. @returns true if the movie opens successfully
  48740. */
  48741. bool loadMovie (const URL& movieURL,
  48742. bool isControllerVisible);
  48743. /** Tries to load a QuickTime movie from a stream into the player.
  48744. It's best to call this function once you've added the component to a window,
  48745. (or put it on the desktop as a heavyweight window). Loading a movie when the
  48746. component isn't visible can cause problems, because QuickTime needs a window
  48747. handle to do its stuff.
  48748. @param movieStream a stream containing a .mov file. The component may try
  48749. to read the whole stream before playing, rather than
  48750. streaming from it.
  48751. @param isControllerVisible whether to show a controller bar at the bottom
  48752. @returns true if the movie opens successfully
  48753. */
  48754. bool loadMovie (InputStream* movieStream,
  48755. bool isControllerVisible);
  48756. /** Closes the movie, if one is open. */
  48757. void closeMovie();
  48758. /** Returns the movie file that is currently open.
  48759. If there isn't one, this returns File::nonexistent
  48760. */
  48761. const File getCurrentMovieFile() const;
  48762. /** Returns true if there's currently a movie open. */
  48763. bool isMovieOpen() const;
  48764. /** Returns the length of the movie, in seconds. */
  48765. double getMovieDuration() const;
  48766. /** Returns the movie's natural size, in pixels.
  48767. You can use this to resize the component to show the movie at its preferred
  48768. scale.
  48769. If no movie is loaded, the size returned will be 0 x 0.
  48770. */
  48771. void getMovieNormalSize (int& width, int& height) const;
  48772. /** This will position the component within a given area, keeping its aspect
  48773. ratio correct according to the movie's normal size.
  48774. The component will be made as large as it can go within the space, and will
  48775. be aligned according to the justification value if this means there are gaps at
  48776. the top or sides.
  48777. */
  48778. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  48779. const RectanglePlacement& placement);
  48780. /** Starts the movie playing. */
  48781. void play();
  48782. /** Stops the movie playing. */
  48783. void stop();
  48784. /** Returns true if the movie is currently playing. */
  48785. bool isPlaying() const;
  48786. /** Moves the movie's position back to the start. */
  48787. void goToStart();
  48788. /** Sets the movie's position to a given time. */
  48789. void setPosition (double seconds);
  48790. /** Returns the current play position of the movie. */
  48791. double getPosition() const;
  48792. /** Changes the movie playback rate.
  48793. A value of 1 is normal speed, greater values play it proportionately faster,
  48794. smaller values play it slower.
  48795. */
  48796. void setSpeed (float newSpeed);
  48797. /** Changes the movie's playback volume.
  48798. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  48799. */
  48800. void setMovieVolume (float newVolume);
  48801. /** Returns the movie's playback volume.
  48802. @returns the volume in the range 0 (silent) to 1.0 (full)
  48803. */
  48804. float getMovieVolume() const;
  48805. /** Tells the movie whether it should loop. */
  48806. void setLooping (bool shouldLoop);
  48807. /** Returns true if the movie is currently looping.
  48808. @see setLooping
  48809. */
  48810. bool isLooping() const;
  48811. /** True if the native QuickTime controller bar is shown in the window.
  48812. @see loadMovie
  48813. */
  48814. bool isControllerVisible() const;
  48815. /** @internal */
  48816. void paint (Graphics& g);
  48817. private:
  48818. File movieFile;
  48819. bool movieLoaded, controllerVisible, looping;
  48820. #if JUCE_WINDOWS
  48821. void parentHierarchyChanged();
  48822. void visibilityChanged();
  48823. void createControlIfNeeded();
  48824. bool isControlCreated() const;
  48825. class Pimpl;
  48826. friend class ScopedPointer <Pimpl>;
  48827. ScopedPointer <Pimpl> pimpl;
  48828. #else
  48829. void* movie;
  48830. #endif
  48831. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QuickTimeMovieComponent);
  48832. };
  48833. #endif
  48834. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  48835. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  48836. #endif
  48837. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48838. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  48839. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48840. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48841. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  48842. /**
  48843. On Windows only, this component sits in the taskbar tray as a small icon.
  48844. To use it, just create one of these components, but don't attempt to make it
  48845. visible, add it to a parent, or put it on the desktop.
  48846. You can then call setIconImage() to create an icon for it in the taskbar.
  48847. To change the icon's tooltip, you can use setIconTooltip().
  48848. To respond to mouse-events, you can override the normal mouseDown(),
  48849. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  48850. position will not be valid, you can use this to respond to clicks. Traditionally
  48851. you'd use a left-click to show your application's window, and a right-click
  48852. to show a pop-up menu.
  48853. */
  48854. class JUCE_API SystemTrayIconComponent : public Component
  48855. {
  48856. public:
  48857. SystemTrayIconComponent();
  48858. /** Destructor. */
  48859. ~SystemTrayIconComponent();
  48860. /** Changes the image shown in the taskbar.
  48861. */
  48862. void setIconImage (const Image& newImage);
  48863. /** Changes the tooltip that Windows shows above the icon. */
  48864. void setIconTooltip (const String& tooltip);
  48865. #if JUCE_LINUX
  48866. /** @internal */
  48867. void paint (Graphics& g);
  48868. #endif
  48869. private:
  48870. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SystemTrayIconComponent);
  48871. };
  48872. #endif
  48873. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48874. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  48875. #endif
  48876. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48877. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  48878. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48879. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48880. #if JUCE_WEB_BROWSER || DOXYGEN
  48881. #if ! DOXYGEN
  48882. class WebBrowserComponentInternal;
  48883. #endif
  48884. /**
  48885. A component that displays an embedded web browser.
  48886. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  48887. Windows, probably IE.
  48888. */
  48889. class JUCE_API WebBrowserComponent : public Component
  48890. {
  48891. public:
  48892. /** Creates a WebBrowserComponent.
  48893. Once it's created and visible, send the browser to a URL using goToURL().
  48894. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  48895. component is taken offscreen, it'll clear the current page
  48896. and replace it with a blank page - this can be handy to stop
  48897. the browser using resources in the background when it's not
  48898. actually being used.
  48899. */
  48900. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  48901. /** Destructor. */
  48902. ~WebBrowserComponent();
  48903. /** Sends the browser to a particular URL.
  48904. @param url the URL to go to.
  48905. @param headers an optional set of parameters to put in the HTTP header. If
  48906. you supply this, it should be a set of string in the form
  48907. "HeaderKey: HeaderValue"
  48908. @param postData an optional block of data that will be attached to the HTTP
  48909. POST request
  48910. */
  48911. void goToURL (const String& url,
  48912. const StringArray* headers = nullptr,
  48913. const MemoryBlock* postData = nullptr);
  48914. /** Stops the current page loading.
  48915. */
  48916. void stop();
  48917. /** Sends the browser back one page.
  48918. */
  48919. void goBack();
  48920. /** Sends the browser forward one page.
  48921. */
  48922. void goForward();
  48923. /** Refreshes the browser.
  48924. */
  48925. void refresh();
  48926. /** This callback is called when the browser is about to navigate
  48927. to a new location.
  48928. You can override this method to perform some action when the user
  48929. tries to go to a particular URL. To allow the operation to carry on,
  48930. return true, or return false to stop the navigation happening.
  48931. */
  48932. virtual bool pageAboutToLoad (const String& newURL);
  48933. /** @internal */
  48934. void paint (Graphics& g);
  48935. /** @internal */
  48936. void resized();
  48937. /** @internal */
  48938. void parentHierarchyChanged();
  48939. /** @internal */
  48940. void visibilityChanged();
  48941. private:
  48942. WebBrowserComponentInternal* browser;
  48943. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  48944. String lastURL;
  48945. StringArray lastHeaders;
  48946. MemoryBlock lastPostData;
  48947. void reloadLastURL();
  48948. void checkWindowAssociation();
  48949. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponent);
  48950. };
  48951. #endif
  48952. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48953. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  48954. #endif
  48955. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  48956. #endif
  48957. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  48958. /*** Start of inlined file: juce_CallOutBox.h ***/
  48959. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  48960. #define __JUCE_CALLOUTBOX_JUCEHEADER__
  48961. /**
  48962. A box with a small arrow that can be used as a temporary pop-up window to show
  48963. extra controls when a button or other component is clicked.
  48964. Using one of these is similar to having a popup menu attached to a button or
  48965. other component - but it looks fancier, and has an arrow that can indicate the
  48966. object that it applies to.
  48967. Normally, you'd create one of these on the stack and run it modally, e.g.
  48968. @code
  48969. void mouseUp (const MouseEvent& e)
  48970. {
  48971. MyContentComponent content;
  48972. content.setSize (300, 300);
  48973. CallOutBox callOut (content, *this, nullptr);
  48974. callOut.runModalLoop();
  48975. }
  48976. @endcode
  48977. The call-out will resize and position itself when the content changes size.
  48978. */
  48979. class JUCE_API CallOutBox : public Component
  48980. {
  48981. public:
  48982. /** Creates a CallOutBox.
  48983. @param contentComponent the component to display inside the call-out. This should
  48984. already have a size set (although the call-out will also
  48985. update itself when the component's size is changed later).
  48986. Obviously this component must not be deleted until the
  48987. call-out box has been deleted.
  48988. @param componentToPointTo the component that the call-out's arrow should point towards
  48989. @param parentComponent if non-zero, this is the component to add the call-out to. If
  48990. this is zero, the call-out will be added to the desktop.
  48991. */
  48992. CallOutBox (Component& contentComponent,
  48993. Component& componentToPointTo,
  48994. Component* parentComponent);
  48995. /** Destructor. */
  48996. ~CallOutBox();
  48997. /** Changes the length of the arrow. */
  48998. void setArrowSize (float newSize);
  48999. /** Updates the position and size of the box.
  49000. You shouldn't normally need to call this, unless you need more precise control over the
  49001. layout.
  49002. @param newAreaToPointTo the rectangle to make the box's arrow point to
  49003. @param newAreaToFitIn the area within which the box's position should be constrained
  49004. */
  49005. void updatePosition (const Rectangle<int>& newAreaToPointTo,
  49006. const Rectangle<int>& newAreaToFitIn);
  49007. /** @internal */
  49008. void paint (Graphics& g);
  49009. /** @internal */
  49010. void resized();
  49011. /** @internal */
  49012. void moved();
  49013. /** @internal */
  49014. void childBoundsChanged (Component*);
  49015. /** @internal */
  49016. bool hitTest (int x, int y);
  49017. /** @internal */
  49018. void inputAttemptWhenModal();
  49019. /** @internal */
  49020. bool keyPressed (const KeyPress& key);
  49021. /** @internal */
  49022. void handleCommandMessage (int commandId);
  49023. private:
  49024. int borderSpace;
  49025. float arrowSize;
  49026. Component& content;
  49027. Path outline;
  49028. Point<float> targetPoint;
  49029. Rectangle<int> availableArea, targetArea;
  49030. Image background;
  49031. void refreshPath();
  49032. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallOutBox);
  49033. };
  49034. #endif // __JUCE_CALLOUTBOX_JUCEHEADER__
  49035. /*** End of inlined file: juce_CallOutBox.h ***/
  49036. #endif
  49037. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  49038. /*** Start of inlined file: juce_ComponentPeer.h ***/
  49039. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  49040. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  49041. class ComponentBoundsConstrainer;
  49042. /**
  49043. The Component class uses a ComponentPeer internally to create and manage a real
  49044. operating-system window.
  49045. This is an abstract base class - the platform specific code contains implementations of
  49046. it for the various platforms.
  49047. User-code should very rarely need to have any involvement with this class.
  49048. @see Component::createNewPeer
  49049. */
  49050. class JUCE_API ComponentPeer
  49051. {
  49052. public:
  49053. /** A combination of these flags is passed to the ComponentPeer constructor. */
  49054. enum StyleFlags
  49055. {
  49056. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  49057. entry on the taskbar (ignored on MacOSX) */
  49058. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  49059. tooltip, etc. */
  49060. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  49061. through it (may not be possible on some platforms). */
  49062. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  49063. title bar and frame\. if not specified, the window will be
  49064. borderless. */
  49065. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  49066. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  49067. minimise button on it. */
  49068. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  49069. maximise button on it. */
  49070. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  49071. close button on it. */
  49072. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  49073. not be possible on all platforms). */
  49074. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  49075. do its own repainting, but only to repaint when the
  49076. performAnyPendingRepaintsNow() method is called. */
  49077. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  49078. be used for things like plugin windows, to stop them interfering
  49079. with the host's shortcut keys */
  49080. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  49081. };
  49082. /** Creates a peer.
  49083. The component is the one that we intend to represent, and the style flags are
  49084. a combination of the values in the StyleFlags enum
  49085. */
  49086. ComponentPeer (Component* component, int styleFlags);
  49087. /** Destructor. */
  49088. virtual ~ComponentPeer();
  49089. /** Returns the component being represented by this peer. */
  49090. Component* getComponent() const noexcept { return component; }
  49091. /** Returns the set of style flags that were set when the window was created.
  49092. @see Component::addToDesktop
  49093. */
  49094. int getStyleFlags() const noexcept { return styleFlags; }
  49095. /** Returns the raw handle to whatever kind of window is being used.
  49096. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  49097. but rememeber there's no guarantees what you'll get back.
  49098. */
  49099. virtual void* getNativeHandle() const = 0;
  49100. /** Shows or hides the window. */
  49101. virtual void setVisible (bool shouldBeVisible) = 0;
  49102. /** Changes the title of the window. */
  49103. virtual void setTitle (const String& title) = 0;
  49104. /** Moves the window without changing its size.
  49105. If the native window is contained in another window, then the co-ordinates are
  49106. relative to the parent window's origin, not the screen origin.
  49107. This should result in a callback to handleMovedOrResized().
  49108. */
  49109. virtual void setPosition (int x, int y) = 0;
  49110. /** Resizes the window without changing its position.
  49111. This should result in a callback to handleMovedOrResized().
  49112. */
  49113. virtual void setSize (int w, int h) = 0;
  49114. /** Moves and resizes the window.
  49115. If the native window is contained in another window, then the co-ordinates are
  49116. relative to the parent window's origin, not the screen origin.
  49117. This should result in a callback to handleMovedOrResized().
  49118. */
  49119. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  49120. /** Returns the current position and size of the window.
  49121. If the native window is contained in another window, then the co-ordinates are
  49122. relative to the parent window's origin, not the screen origin.
  49123. */
  49124. virtual const Rectangle<int> getBounds() const = 0;
  49125. /** Returns the x-position of this window, relative to the screen's origin. */
  49126. virtual const Point<int> getScreenPosition() const = 0;
  49127. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  49128. virtual const Point<int> localToGlobal (const Point<int>& relativePosition) = 0;
  49129. /** Converts a rectangle relative to the top-left of this component to screen co-ordinates. */
  49130. virtual const Rectangle<int> localToGlobal (const Rectangle<int>& relativePosition);
  49131. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  49132. virtual const Point<int> globalToLocal (const Point<int>& screenPosition) = 0;
  49133. /** Converts a screen area to a position relative to the top-left of this component. */
  49134. virtual const Rectangle<int> globalToLocal (const Rectangle<int>& screenPosition);
  49135. /** Minimises the window. */
  49136. virtual void setMinimised (bool shouldBeMinimised) = 0;
  49137. /** True if the window is currently minimised. */
  49138. virtual bool isMinimised() const = 0;
  49139. /** Enable/disable fullscreen mode for the window. */
  49140. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  49141. /** True if the window is currently full-screen. */
  49142. virtual bool isFullScreen() const = 0;
  49143. /** Sets the size to restore to if fullscreen mode is turned off. */
  49144. void setNonFullScreenBounds (const Rectangle<int>& newBounds) noexcept;
  49145. /** Returns the size to restore to if fullscreen mode is turned off. */
  49146. const Rectangle<int>& getNonFullScreenBounds() const noexcept;
  49147. /** Attempts to change the icon associated with this window.
  49148. */
  49149. virtual void setIcon (const Image& newIcon) = 0;
  49150. /** Sets a constrainer to use if the peer can resize itself.
  49151. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  49152. */
  49153. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) noexcept;
  49154. /** Returns the current constrainer, if one has been set. */
  49155. ComponentBoundsConstrainer* getConstrainer() const noexcept { return constrainer; }
  49156. /** Checks if a point is in the window.
  49157. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  49158. is false, then this returns false if the point is actually inside a child of this
  49159. window.
  49160. */
  49161. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  49162. /** Returns the size of the window frame that's around this window.
  49163. Whether or not the window has a normal window frame depends on the flags
  49164. that were set when the window was created by Component::addToDesktop()
  49165. */
  49166. virtual const BorderSize<int> getFrameSize() const = 0;
  49167. /** This is called when the window's bounds change.
  49168. A peer implementation must call this when the window is moved and resized, so that
  49169. this method can pass the message on to the component.
  49170. */
  49171. void handleMovedOrResized();
  49172. /** This is called if the screen resolution changes.
  49173. A peer implementation must call this if the monitor arrangement changes or the available
  49174. screen size changes.
  49175. */
  49176. void handleScreenSizeChange();
  49177. /** This is called to repaint the component into the given context. */
  49178. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  49179. /** Sets this window to either be always-on-top or normal.
  49180. Some kinds of window might not be able to do this, so should return false.
  49181. */
  49182. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  49183. /** Brings the window to the top, optionally also giving it focus. */
  49184. virtual void toFront (bool makeActive) = 0;
  49185. /** Moves the window to be just behind another one. */
  49186. virtual void toBehind (ComponentPeer* other) = 0;
  49187. /** Called when the window is brought to the front, either by the OS or by a call
  49188. to toFront().
  49189. */
  49190. void handleBroughtToFront();
  49191. /** True if the window has the keyboard focus. */
  49192. virtual bool isFocused() const = 0;
  49193. /** Tries to give the window keyboard focus. */
  49194. virtual void grabFocus() = 0;
  49195. /** Called when the window gains keyboard focus. */
  49196. void handleFocusGain();
  49197. /** Called when the window loses keyboard focus. */
  49198. void handleFocusLoss();
  49199. Component* getLastFocusedSubcomponent() const noexcept;
  49200. /** Called when a key is pressed.
  49201. For keycode info, see the KeyPress class.
  49202. Returns true if the keystroke was used.
  49203. */
  49204. bool handleKeyPress (int keyCode, juce_wchar textCharacter);
  49205. /** Called whenever a key is pressed or released.
  49206. Returns true if the keystroke was used.
  49207. */
  49208. bool handleKeyUpOrDown (bool isKeyDown);
  49209. /** Called whenever a modifier key is pressed or released. */
  49210. void handleModifierKeysChange();
  49211. /** Tells the window that text input may be required at the given position.
  49212. This may cause things like a virtual on-screen keyboard to appear, depending
  49213. on the OS.
  49214. */
  49215. virtual void textInputRequired (const Point<int>& position) = 0;
  49216. /** If there's some kind of OS input-method in progress, this should dismiss it. */
  49217. virtual void dismissPendingTextInput();
  49218. /** Returns the currently focused TextInputTarget, or null if none is found. */
  49219. TextInputTarget* findCurrentTextInputTarget();
  49220. /** Invalidates a region of the window to be repainted asynchronously. */
  49221. virtual void repaint (const Rectangle<int>& area) = 0;
  49222. /** This can be called (from the message thread) to cause the immediate redrawing
  49223. of any areas of this window that need repainting.
  49224. You shouldn't ever really need to use this, it's mainly for special purposes
  49225. like supporting audio plugins where the host's event loop is out of our control.
  49226. */
  49227. virtual void performAnyPendingRepaintsNow() = 0;
  49228. /** Changes the window's transparency. */
  49229. virtual void setAlpha (float newAlpha) = 0;
  49230. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  49231. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  49232. void handleUserClosingWindow();
  49233. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  49234. void handleFileDragExit (const StringArray& files);
  49235. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  49236. /** Resets the masking region.
  49237. The subclass should call this every time it's about to call the handlePaint
  49238. method.
  49239. @see addMaskedRegion
  49240. */
  49241. void clearMaskedRegion();
  49242. /** Adds a rectangle to the set of areas not to paint over.
  49243. A component can call this on its peer during its paint() method, to signal
  49244. that the painting code should ignore a given region. The reason
  49245. for this is to stop embedded windows (such as OpenGL) getting painted over.
  49246. The masked region is cleared each time before a paint happens, so a component
  49247. will have to make sure it calls this every time it's painted.
  49248. */
  49249. void addMaskedRegion (int x, int y, int w, int h);
  49250. /** Returns the number of currently-active peers.
  49251. @see getPeer
  49252. */
  49253. static int getNumPeers() noexcept;
  49254. /** Returns one of the currently-active peers.
  49255. @see getNumPeers
  49256. */
  49257. static ComponentPeer* getPeer (int index) noexcept;
  49258. /** Checks if this peer object is valid.
  49259. @see getNumPeers
  49260. */
  49261. static bool isValidPeer (const ComponentPeer* peer) noexcept;
  49262. virtual const StringArray getAvailableRenderingEngines();
  49263. virtual int getCurrentRenderingEngine() const;
  49264. virtual void setCurrentRenderingEngine (int index);
  49265. protected:
  49266. Component* const component;
  49267. const int styleFlags;
  49268. RectangleList maskedRegion;
  49269. Rectangle<int> lastNonFullscreenBounds;
  49270. uint32 lastPaintTime;
  49271. ComponentBoundsConstrainer* constrainer;
  49272. static void updateCurrentModifiers() noexcept;
  49273. private:
  49274. WeakReference<Component> lastFocusedComponent, dragAndDropTargetComponent;
  49275. Component* lastDragAndDropCompUnderMouse;
  49276. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  49277. friend class Component;
  49278. friend class Desktop;
  49279. static ComponentPeer* getPeerFor (const Component* component) noexcept;
  49280. void setLastDragDropTarget (Component* comp);
  49281. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentPeer);
  49282. };
  49283. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  49284. /*** End of inlined file: juce_ComponentPeer.h ***/
  49285. #endif
  49286. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  49287. /*** Start of inlined file: juce_DialogWindow.h ***/
  49288. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  49289. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  49290. /**
  49291. A dialog-box style window.
  49292. This class is a convenient way of creating a DocumentWindow with a close button
  49293. that can be triggered by pressing the escape key.
  49294. Any of the methods available to a DocumentWindow or ResizableWindow are also
  49295. available to this, so it can be made resizable, have a menu bar, etc.
  49296. To add items to the box, see the ResizableWindow::setContentOwned() or
  49297. ResizableWindow::setContentNonOwned() methods. Don't add components directly to this
  49298. class - always put them in a content component!
  49299. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  49300. the user clicking the close button - for more info, see the DocumentWindow
  49301. help.
  49302. @see DocumentWindow, ResizableWindow
  49303. */
  49304. class JUCE_API DialogWindow : public DocumentWindow
  49305. {
  49306. public:
  49307. /** Creates a DialogWindow.
  49308. @param name the name to give the component - this is also
  49309. the title shown at the top of the window. To change
  49310. this later, use setName()
  49311. @param backgroundColour the colour to use for filling the window's background.
  49312. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  49313. close button to be triggered
  49314. @param addToDesktop if true, the window will be automatically added to the
  49315. desktop; if false, you can use it as a child component
  49316. */
  49317. DialogWindow (const String& name,
  49318. const Colour& backgroundColour,
  49319. bool escapeKeyTriggersCloseButton,
  49320. bool addToDesktop = true);
  49321. /** Destructor.
  49322. If a content component has been set with setContentOwned(), it will be deleted.
  49323. */
  49324. ~DialogWindow();
  49325. /** Easy way of quickly showing a dialog box containing a given component.
  49326. This will open and display a DialogWindow containing a given component, making it
  49327. modal, but returning immediately to allow the dialog to finish in its own time. If
  49328. you want to block and run a modal loop until the dialog is dismissed, use showModalDialog()
  49329. instead.
  49330. To close the dialog programatically, you should call exitModalState (returnValue) on
  49331. the DialogWindow that is created. To find a pointer to this window from your
  49332. contentComponent, you can do something like this:
  49333. @code
  49334. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) nullptr);
  49335. if (dw != nullptr)
  49336. dw->exitModalState (1234);
  49337. @endcode
  49338. @param dialogTitle the dialog box's title
  49339. @param contentComponent the content component for the dialog box. Make sure
  49340. that this has been set to the size you want it to
  49341. be before calling this method. The component won't
  49342. be deleted by this call, so you can re-use it or delete
  49343. it afterwards
  49344. @param componentToCentreAround if this is non-zero, it indicates a component that
  49345. you'd like to show this dialog box in front of. See the
  49346. DocumentWindow::centreAroundComponent() method for more
  49347. info on this parameter
  49348. @param backgroundColour a colour to use for the dialog box's background colour
  49349. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  49350. close button to be triggered
  49351. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  49352. a corner resizer
  49353. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  49354. to use a border or corner resizer component. See ResizableWindow::setResizable()
  49355. */
  49356. static void showDialog (const String& dialogTitle,
  49357. Component* contentComponent,
  49358. Component* componentToCentreAround,
  49359. const Colour& backgroundColour,
  49360. bool escapeKeyTriggersCloseButton,
  49361. bool shouldBeResizable = false,
  49362. bool useBottomRightCornerResizer = false);
  49363. /** Easy way of quickly showing a dialog box containing a given component.
  49364. This will open and display a DialogWindow containing a given component, returning
  49365. when the user clicks its close button.
  49366. It returns the value that was returned by the dialog box's runModalLoop() call.
  49367. To close the dialog programatically, you should call exitModalState (returnValue) on
  49368. the DialogWindow that is created. To find a pointer to this window from your
  49369. contentComponent, you can do something like this:
  49370. @code
  49371. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) nullptr);
  49372. if (dw != nullptr)
  49373. dw->exitModalState (1234);
  49374. @endcode
  49375. @param dialogTitle the dialog box's title
  49376. @param contentComponent the content component for the dialog box. Make sure
  49377. that this has been set to the size you want it to
  49378. be before calling this method. The component won't
  49379. be deleted by this call, so you can re-use it or delete
  49380. it afterwards
  49381. @param componentToCentreAround if this is non-zero, it indicates a component that
  49382. you'd like to show this dialog box in front of. See the
  49383. DocumentWindow::centreAroundComponent() method for more
  49384. info on this parameter
  49385. @param backgroundColour a colour to use for the dialog box's background colour
  49386. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  49387. close button to be triggered
  49388. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  49389. a corner resizer
  49390. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  49391. to use a border or corner resizer component. See ResizableWindow::setResizable()
  49392. */
  49393. #if JUCE_MODAL_LOOPS_PERMITTED || DOXYGEN
  49394. static int showModalDialog (const String& dialogTitle,
  49395. Component* contentComponent,
  49396. Component* componentToCentreAround,
  49397. const Colour& backgroundColour,
  49398. bool escapeKeyTriggersCloseButton,
  49399. bool shouldBeResizable = false,
  49400. bool useBottomRightCornerResizer = false);
  49401. #endif
  49402. protected:
  49403. /** @internal */
  49404. void resized();
  49405. private:
  49406. bool escapeKeyTriggersCloseButton;
  49407. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DialogWindow);
  49408. };
  49409. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  49410. /*** End of inlined file: juce_DialogWindow.h ***/
  49411. #endif
  49412. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  49413. #endif
  49414. #ifndef __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  49415. /*** Start of inlined file: juce_NativeMessageBox.h ***/
  49416. #ifndef __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  49417. #define __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  49418. class NativeMessageBox
  49419. {
  49420. public:
  49421. /** Shows a dialog box that just has a message and a single 'ok' button to close it.
  49422. If the callback parameter is null, the box is shown modally, and the method will
  49423. block until the user has clicked the button (or pressed the escape or return keys).
  49424. If the callback parameter is non-null, the box will be displayed and placed into a
  49425. modal state, but this method will return immediately, and the callback will be invoked
  49426. later when the user dismisses the box.
  49427. @param iconType the type of icon to show
  49428. @param title the headline to show at the top of the box
  49429. @param message a longer, more descriptive message to show underneath the title
  49430. @param associatedComponent if this is non-null, it specifies the component that the
  49431. alert window should be associated with. Depending on the look
  49432. and feel, this might be used for positioning of the alert window.
  49433. */
  49434. #if JUCE_MODAL_LOOPS_PERMITTED
  49435. static void JUCE_CALLTYPE showMessageBox (AlertWindow::AlertIconType iconType,
  49436. const String& title,
  49437. const String& message,
  49438. Component* associatedComponent = nullptr);
  49439. #endif
  49440. /** Shows a dialog box that just has a message and a single 'ok' button to close it.
  49441. If the callback parameter is null, the box is shown modally, and the method will
  49442. block until the user has clicked the button (or pressed the escape or return keys).
  49443. If the callback parameter is non-null, the box will be displayed and placed into a
  49444. modal state, but this method will return immediately, and the callback will be invoked
  49445. later when the user dismisses the box.
  49446. @param iconType the type of icon to show
  49447. @param title the headline to show at the top of the box
  49448. @param message a longer, more descriptive message to show underneath the title
  49449. @param associatedComponent if this is non-null, it specifies the component that the
  49450. alert window should be associated with. Depending on the look
  49451. and feel, this might be used for positioning of the alert window.
  49452. */
  49453. static void JUCE_CALLTYPE showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  49454. const String& title,
  49455. const String& message,
  49456. Component* associatedComponent = nullptr);
  49457. /** Shows a dialog box with two buttons.
  49458. Ideal for ok/cancel or yes/no choices. The return key can also be used
  49459. to trigger the first button, and the escape key for the second button.
  49460. If the callback parameter is null, the box is shown modally, and the method will
  49461. block until the user has clicked the button (or pressed the escape or return keys).
  49462. If the callback parameter is non-null, the box will be displayed and placed into a
  49463. modal state, but this method will return immediately, and the callback will be invoked
  49464. later when the user dismisses the box.
  49465. @param iconType the type of icon to show
  49466. @param title the headline to show at the top of the box
  49467. @param message a longer, more descriptive message to show underneath the title
  49468. @param associatedComponent if this is non-null, it specifies the component that the
  49469. alert window should be associated with. Depending on the look
  49470. and feel, this might be used for positioning of the alert window.
  49471. @param callback if this is non-null, the menu will be launched asynchronously,
  49472. returning immediately, and the callback will receive a call to its
  49473. modalStateFinished() when the box is dismissed, with its parameter
  49474. being 1 if the ok button was pressed, or 0 for cancel, The callback object
  49475. will be owned and deleted by the system, so make sure that it works
  49476. safely and doesn't keep any references to objects that might be deleted
  49477. before it gets called.
  49478. @returns true if button 1 was clicked, false if it was button 2. If the callback parameter
  49479. is not null, the method always returns false, and the user's choice is delivered
  49480. later by the callback.
  49481. */
  49482. static bool JUCE_CALLTYPE showOkCancelBox (AlertWindow::AlertIconType iconType,
  49483. const String& title,
  49484. const String& message,
  49485. #if JUCE_MODAL_LOOPS_PERMITTED
  49486. Component* associatedComponent = nullptr,
  49487. ModalComponentManager::Callback* callback = nullptr);
  49488. #else
  49489. Component* associatedComponent,
  49490. ModalComponentManager::Callback* callback);
  49491. #endif
  49492. /** Shows a dialog box with three buttons.
  49493. Ideal for yes/no/cancel boxes.
  49494. The escape key can be used to trigger the third button.
  49495. If the callback parameter is null, the box is shown modally, and the method will
  49496. block until the user has clicked the button (or pressed the escape or return keys).
  49497. If the callback parameter is non-null, the box will be displayed and placed into a
  49498. modal state, but this method will return immediately, and the callback will be invoked
  49499. later when the user dismisses the box.
  49500. @param iconType the type of icon to show
  49501. @param title the headline to show at the top of the box
  49502. @param message a longer, more descriptive message to show underneath the title
  49503. @param associatedComponent if this is non-null, it specifies the component that the
  49504. alert window should be associated with. Depending on the look
  49505. and feel, this might be used for positioning of the alert window.
  49506. @param callback if this is non-null, the menu will be launched asynchronously,
  49507. returning immediately, and the callback will receive a call to its
  49508. modalStateFinished() when the box is dismissed, with its parameter
  49509. being 1 if the "yes" button was pressed, 2 for the "no" button, or 0
  49510. if it was cancelled, The callback object will be owned and deleted by the
  49511. system, so make sure that it works safely and doesn't keep any references
  49512. to objects that might be deleted before it gets called.
  49513. @returns If the callback parameter has been set, this returns 0. Otherwise, it returns one
  49514. of the following values:
  49515. - 0 if 'cancel' was pressed
  49516. - 1 if 'yes' was pressed
  49517. - 2 if 'no' was pressed
  49518. */
  49519. static int JUCE_CALLTYPE showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  49520. const String& title,
  49521. const String& message,
  49522. #if JUCE_MODAL_LOOPS_PERMITTED
  49523. Component* associatedComponent = nullptr,
  49524. ModalComponentManager::Callback* callback = nullptr);
  49525. #else
  49526. Component* associatedComponent,
  49527. ModalComponentManager::Callback* callback);
  49528. #endif
  49529. };
  49530. #endif // __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  49531. /*** End of inlined file: juce_NativeMessageBox.h ***/
  49532. #endif
  49533. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  49534. #endif
  49535. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  49536. /*** Start of inlined file: juce_SplashScreen.h ***/
  49537. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  49538. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  49539. /** A component for showing a splash screen while your app starts up.
  49540. This will automatically position itself, and delete itself when the app has
  49541. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  49542. this).
  49543. To use it, just create one of these in your JUCEApplication::initialise() method,
  49544. call its show() method and let the object delete itself later.
  49545. E.g. @code
  49546. void MyApp::initialise (const String& commandLine)
  49547. {
  49548. SplashScreen* splash = new SplashScreen();
  49549. splash->show ("welcome to my app",
  49550. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  49551. 4000, false);
  49552. .. no need to delete the splash screen - it'll do that itself.
  49553. }
  49554. @endcode
  49555. */
  49556. class JUCE_API SplashScreen : public Component,
  49557. public Timer,
  49558. private DeletedAtShutdown
  49559. {
  49560. public:
  49561. /** Creates a SplashScreen object.
  49562. After creating one of these (or your subclass of it), call one of the show()
  49563. methods to display it.
  49564. */
  49565. SplashScreen();
  49566. /** Destructor. */
  49567. ~SplashScreen();
  49568. /** Creates a SplashScreen object that will display an image.
  49569. As soon as this is called, the SplashScreen will be displayed in the centre of the
  49570. screen. This method will also dispatch any pending messages to make sure that when
  49571. it returns, the splash screen has been completely drawn, and your initialisation
  49572. code can carry on.
  49573. @param title the name to give the component
  49574. @param backgroundImage an image to draw on the component. The component's size
  49575. will be set to the size of this image, and if the image is
  49576. semi-transparent, the component will be made semi-transparent
  49577. too. This image will be deleted (or released from the ImageCache
  49578. if that's how it was created) by the splash screen object when
  49579. it is itself deleted.
  49580. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  49581. should stay visible for. If the initialisation takes longer than
  49582. this time, the splash screen will wait for it to finish before
  49583. disappearing, but if initialisation is very quick, this lets
  49584. you make sure that people get a good look at your splash.
  49585. @param useDropShadow if true, the window will have a drop shadow
  49586. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  49587. the mouse (anywhere)
  49588. */
  49589. void show (const String& title,
  49590. const Image& backgroundImage,
  49591. int minimumTimeToDisplayFor,
  49592. bool useDropShadow,
  49593. bool removeOnMouseClick = true);
  49594. /** Creates a SplashScreen object with a specified size.
  49595. For a custom splash screen, you can use this method to display it at a certain size
  49596. and then override the paint() method yourself to do whatever's necessary.
  49597. As soon as this is called, the SplashScreen will be displayed in the centre of the
  49598. screen. This method will also dispatch any pending messages to make sure that when
  49599. it returns, the splash screen has been completely drawn, and your initialisation
  49600. code can carry on.
  49601. @param title the name to give the component
  49602. @param width the width to use
  49603. @param height the height to use
  49604. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  49605. should stay visible for. If the initialisation takes longer than
  49606. this time, the splash screen will wait for it to finish before
  49607. disappearing, but if initialisation is very quick, this lets
  49608. you make sure that people get a good look at your splash.
  49609. @param useDropShadow if true, the window will have a drop shadow
  49610. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  49611. the mouse (anywhere)
  49612. */
  49613. void show (const String& title,
  49614. int width,
  49615. int height,
  49616. int minimumTimeToDisplayFor,
  49617. bool useDropShadow,
  49618. bool removeOnMouseClick = true);
  49619. /** @internal */
  49620. void paint (Graphics& g);
  49621. /** @internal */
  49622. void timerCallback();
  49623. private:
  49624. Image backgroundImage;
  49625. Time earliestTimeToDelete;
  49626. int originalClickCounter;
  49627. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SplashScreen);
  49628. };
  49629. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  49630. /*** End of inlined file: juce_SplashScreen.h ***/
  49631. #endif
  49632. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  49633. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  49634. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  49635. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  49636. /**
  49637. A thread that automatically pops up a modal dialog box with a progress bar
  49638. and cancel button while it's busy running.
  49639. These are handy for performing some sort of task while giving the user feedback
  49640. about how long there is to go, etc.
  49641. E.g. @code
  49642. class MyTask : public ThreadWithProgressWindow
  49643. {
  49644. public:
  49645. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  49646. {
  49647. }
  49648. ~MyTask()
  49649. {
  49650. }
  49651. void run()
  49652. {
  49653. for (int i = 0; i < thingsToDo; ++i)
  49654. {
  49655. // must check this as often as possible, because this is
  49656. // how we know if the user's pressed 'cancel'
  49657. if (threadShouldExit())
  49658. break;
  49659. // this will update the progress bar on the dialog box
  49660. setProgress (i / (double) thingsToDo);
  49661. // ... do the business here...
  49662. }
  49663. }
  49664. };
  49665. void doTheTask()
  49666. {
  49667. MyTask m;
  49668. if (m.runThread())
  49669. {
  49670. // thread finished normally..
  49671. }
  49672. else
  49673. {
  49674. // user pressed the cancel button..
  49675. }
  49676. }
  49677. @endcode
  49678. @see Thread, AlertWindow
  49679. */
  49680. class JUCE_API ThreadWithProgressWindow : public Thread,
  49681. private Timer
  49682. {
  49683. public:
  49684. /** Creates the thread.
  49685. Initially, the dialog box won't be visible, it'll only appear when the
  49686. runThread() method is called.
  49687. @param windowTitle the title to go at the top of the dialog box
  49688. @param hasProgressBar whether the dialog box should have a progress bar (see
  49689. setProgress() )
  49690. @param hasCancelButton whether the dialog box should have a cancel button
  49691. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  49692. the thread to stop before killing it forcibly (see
  49693. Thread::stopThread() )
  49694. @param cancelButtonText the text that should be shown in the cancel button
  49695. (if it has one)
  49696. */
  49697. ThreadWithProgressWindow (const String& windowTitle,
  49698. bool hasProgressBar,
  49699. bool hasCancelButton,
  49700. int timeOutMsWhenCancelling = 10000,
  49701. const String& cancelButtonText = "Cancel");
  49702. /** Destructor. */
  49703. ~ThreadWithProgressWindow();
  49704. /** Starts the thread and waits for it to finish.
  49705. This will start the thread, make the dialog box appear, and wait until either
  49706. the thread finishes normally, or until the cancel button is pressed.
  49707. Before returning, the dialog box will be hidden.
  49708. @param threadPriority the priority to use when starting the thread - see
  49709. Thread::startThread() for values
  49710. @returns true if the thread finished normally; false if the user pressed cancel
  49711. */
  49712. bool runThread (int threadPriority = 5);
  49713. /** The thread should call this periodically to update the position of the progress bar.
  49714. @param newProgress the progress, from 0.0 to 1.0
  49715. @see setStatusMessage
  49716. */
  49717. void setProgress (double newProgress);
  49718. /** The thread can call this to change the message that's displayed in the dialog box.
  49719. */
  49720. void setStatusMessage (const String& newStatusMessage);
  49721. /** Returns the AlertWindow that is being used.
  49722. */
  49723. AlertWindow* getAlertWindow() const noexcept { return alertWindow; }
  49724. private:
  49725. void timerCallback();
  49726. double progress;
  49727. ScopedPointer <AlertWindow> alertWindow;
  49728. String message;
  49729. CriticalSection messageLock;
  49730. const int timeOutMsWhenCancelling;
  49731. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadWithProgressWindow);
  49732. };
  49733. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  49734. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  49735. #endif
  49736. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  49737. #endif
  49738. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  49739. #endif
  49740. #ifndef __JUCE_COLOUR_JUCEHEADER__
  49741. #endif
  49742. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  49743. #endif
  49744. #ifndef __JUCE_COLOURS_JUCEHEADER__
  49745. #endif
  49746. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  49747. #endif
  49748. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  49749. /*** Start of inlined file: juce_EdgeTable.h ***/
  49750. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  49751. #define __JUCE_EDGETABLE_JUCEHEADER__
  49752. class Path;
  49753. class Image;
  49754. /**
  49755. A table of horizontal scan-line segments - used for rasterising Paths.
  49756. @see Path, Graphics
  49757. */
  49758. class JUCE_API EdgeTable
  49759. {
  49760. public:
  49761. /** Creates an edge table containing a path.
  49762. A table is created with a fixed vertical range, and only sections of the path
  49763. which lie within this range will be added to the table.
  49764. @param clipLimits only the region of the path that lies within this area will be added
  49765. @param pathToAdd the path to add to the table
  49766. @param transform a transform to apply to the path being added
  49767. */
  49768. EdgeTable (const Rectangle<int>& clipLimits,
  49769. const Path& pathToAdd,
  49770. const AffineTransform& transform);
  49771. /** Creates an edge table containing a rectangle. */
  49772. EdgeTable (const Rectangle<int>& rectangleToAdd);
  49773. /** Creates an edge table containing a rectangle list. */
  49774. EdgeTable (const RectangleList& rectanglesToAdd);
  49775. /** Creates an edge table containing a rectangle. */
  49776. EdgeTable (const Rectangle<float>& rectangleToAdd);
  49777. /** Creates a copy of another edge table. */
  49778. EdgeTable (const EdgeTable& other);
  49779. /** Copies from another edge table. */
  49780. EdgeTable& operator= (const EdgeTable& other);
  49781. /** Destructor. */
  49782. ~EdgeTable();
  49783. void clipToRectangle (const Rectangle<int>& r);
  49784. void excludeRectangle (const Rectangle<int>& r);
  49785. void clipToEdgeTable (const EdgeTable& other);
  49786. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels);
  49787. bool isEmpty() noexcept;
  49788. const Rectangle<int>& getMaximumBounds() const noexcept { return bounds; }
  49789. void translate (float dx, int dy) noexcept;
  49790. /** Reduces the amount of space the table has allocated.
  49791. This will shrink the table down to use as little memory as possible - useful for
  49792. read-only tables that get stored and re-used for rendering.
  49793. */
  49794. void optimiseTable();
  49795. /** Iterates the lines in the table, for rendering.
  49796. This function will iterate each line in the table, and call a user-defined class
  49797. to render each pixel or continuous line of pixels that the table contains.
  49798. @param iterationCallback this templated class must contain the following methods:
  49799. @code
  49800. inline void setEdgeTableYPos (int y);
  49801. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  49802. inline void handleEdgeTablePixelFull (int x) const;
  49803. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  49804. inline void handleEdgeTableLineFull (int x, int width) const;
  49805. @endcode
  49806. (these don't necessarily have to be 'const', but it might help it go faster)
  49807. */
  49808. template <class EdgeTableIterationCallback>
  49809. void iterate (EdgeTableIterationCallback& iterationCallback) const noexcept
  49810. {
  49811. const int* lineStart = table;
  49812. for (int y = 0; y < bounds.getHeight(); ++y)
  49813. {
  49814. const int* line = lineStart;
  49815. lineStart += lineStrideElements;
  49816. int numPoints = line[0];
  49817. if (--numPoints > 0)
  49818. {
  49819. int x = *++line;
  49820. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  49821. int levelAccumulator = 0;
  49822. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  49823. while (--numPoints >= 0)
  49824. {
  49825. const int level = *++line;
  49826. jassert (isPositiveAndBelow (level, (int) 256));
  49827. const int endX = *++line;
  49828. jassert (endX >= x);
  49829. const int endOfRun = (endX >> 8);
  49830. if (endOfRun == (x >> 8))
  49831. {
  49832. // small segment within the same pixel, so just save it for the next
  49833. // time round..
  49834. levelAccumulator += (endX - x) * level;
  49835. }
  49836. else
  49837. {
  49838. // plot the fist pixel of this segment, including any accumulated
  49839. // levels from smaller segments that haven't been drawn yet
  49840. levelAccumulator += (0x100 - (x & 0xff)) * level;
  49841. levelAccumulator >>= 8;
  49842. x >>= 8;
  49843. if (levelAccumulator > 0)
  49844. {
  49845. if (levelAccumulator >= 255)
  49846. iterationCallback.handleEdgeTablePixelFull (x);
  49847. else
  49848. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  49849. }
  49850. // if there's a run of similar pixels, do it all in one go..
  49851. if (level > 0)
  49852. {
  49853. jassert (endOfRun <= bounds.getRight());
  49854. const int numPix = endOfRun - ++x;
  49855. if (numPix > 0)
  49856. iterationCallback.handleEdgeTableLine (x, numPix, level);
  49857. }
  49858. // save the bit at the end to be drawn next time round the loop.
  49859. levelAccumulator = (endX & 0xff) * level;
  49860. }
  49861. x = endX;
  49862. }
  49863. levelAccumulator >>= 8;
  49864. if (levelAccumulator > 0)
  49865. {
  49866. x >>= 8;
  49867. jassert (x >= bounds.getX() && x < bounds.getRight());
  49868. if (levelAccumulator >= 255)
  49869. iterationCallback.handleEdgeTablePixelFull (x);
  49870. else
  49871. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  49872. }
  49873. }
  49874. }
  49875. }
  49876. private:
  49877. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  49878. HeapBlock<int> table;
  49879. Rectangle<int> bounds;
  49880. int maxEdgesPerLine, lineStrideElements;
  49881. bool needToCheckEmptinesss;
  49882. void addEdgePoint (int x, int y, int winding);
  49883. void remapTableForNumEdges (int newNumEdgesPerLine);
  49884. void intersectWithEdgeTableLine (int y, const int* otherLine);
  49885. void clipEdgeTableLineToRange (int* line, int x1, int x2) noexcept;
  49886. void sanitiseLevels (bool useNonZeroWinding) noexcept;
  49887. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) noexcept;
  49888. JUCE_LEAK_DETECTOR (EdgeTable);
  49889. };
  49890. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  49891. /*** End of inlined file: juce_EdgeTable.h ***/
  49892. #endif
  49893. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  49894. /*** Start of inlined file: juce_FillType.h ***/
  49895. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  49896. #define __JUCE_FILLTYPE_JUCEHEADER__
  49897. /**
  49898. Represents a colour or fill pattern to use for rendering paths.
  49899. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  49900. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  49901. @see Graphics::setFillType, DrawablePath::setFill
  49902. */
  49903. class JUCE_API FillType
  49904. {
  49905. public:
  49906. /** Creates a default fill type, of solid black. */
  49907. FillType() noexcept;
  49908. /** Creates a fill type of a solid colour.
  49909. @see setColour
  49910. */
  49911. FillType (const Colour& colour) noexcept;
  49912. /** Creates a gradient fill type.
  49913. @see setGradient
  49914. */
  49915. FillType (const ColourGradient& gradient);
  49916. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  49917. and rotation of the pattern.
  49918. @see setTiledImage
  49919. */
  49920. FillType (const Image& image, const AffineTransform& transform) noexcept;
  49921. /** Creates a copy of another FillType. */
  49922. FillType (const FillType& other);
  49923. /** Makes a copy of another FillType. */
  49924. FillType& operator= (const FillType& other);
  49925. /** Destructor. */
  49926. ~FillType() noexcept;
  49927. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  49928. bool isColour() const noexcept { return gradient == nullptr && image.isNull(); }
  49929. /** Returns true if this is a gradient fill. */
  49930. bool isGradient() const noexcept { return gradient != nullptr; }
  49931. /** Returns true if this is a tiled image pattern fill. */
  49932. bool isTiledImage() const noexcept { return image.isValid(); }
  49933. /** Turns this object into a solid colour fill.
  49934. If the object was an image or gradient, those fields will no longer be valid. */
  49935. void setColour (const Colour& newColour) noexcept;
  49936. /** Turns this object into a gradient fill. */
  49937. void setGradient (const ColourGradient& newGradient);
  49938. /** Turns this object into a tiled image fill type. The transform allows you to set
  49939. the scaling, offset and rotation of the pattern.
  49940. */
  49941. void setTiledImage (const Image& image, const AffineTransform& transform) noexcept;
  49942. /** Changes the opacity that should be used.
  49943. If the fill is a solid colour, this just changes the opacity of that colour. For
  49944. gradients and image tiles, it changes the opacity that will be used for them.
  49945. */
  49946. void setOpacity (float newOpacity) noexcept;
  49947. /** Returns the current opacity to be applied to the colour, gradient, or image.
  49948. @see setOpacity
  49949. */
  49950. float getOpacity() const noexcept { return colour.getFloatAlpha(); }
  49951. /** Returns true if this fill type is completely transparent. */
  49952. bool isInvisible() const noexcept;
  49953. /** The solid colour being used.
  49954. If the fill type is not a solid colour, the alpha channel of this colour indicates
  49955. the opacity that should be used for the fill, and the RGB channels are ignored.
  49956. */
  49957. Colour colour;
  49958. /** Returns the gradient that should be used for filling.
  49959. This will be zero if the object is some other type of fill.
  49960. If a gradient is active, the overall opacity with which it should be applied
  49961. is indicated by the alpha channel of the colour variable.
  49962. */
  49963. ScopedPointer <ColourGradient> gradient;
  49964. /** The image that should be used for tiling.
  49965. If an image fill is active, the overall opacity with which it should be applied
  49966. is indicated by the alpha channel of the colour variable.
  49967. */
  49968. Image image;
  49969. /** The transform that should be applied to the image or gradient that's being drawn. */
  49970. AffineTransform transform;
  49971. bool operator== (const FillType& other) const;
  49972. bool operator!= (const FillType& other) const;
  49973. private:
  49974. JUCE_LEAK_DETECTOR (FillType);
  49975. };
  49976. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  49977. /*** End of inlined file: juce_FillType.h ***/
  49978. #endif
  49979. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  49980. #endif
  49981. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  49982. #endif
  49983. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49984. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  49985. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49986. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49987. /**
  49988. Interface class for graphics context objects, used internally by the Graphics class.
  49989. Users are not supposed to create instances of this class directly - do your drawing
  49990. via the Graphics object instead.
  49991. It's a base class for different types of graphics context, that may perform software-based
  49992. or OS-accelerated rendering.
  49993. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  49994. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  49995. context.
  49996. */
  49997. class JUCE_API LowLevelGraphicsContext
  49998. {
  49999. protected:
  50000. LowLevelGraphicsContext();
  50001. public:
  50002. virtual ~LowLevelGraphicsContext();
  50003. /** Returns true if this device is vector-based, e.g. a printer. */
  50004. virtual bool isVectorDevice() const = 0;
  50005. /** Moves the origin to a new position.
  50006. The co-ords are relative to the current origin, and indicate the new position
  50007. of (0, 0).
  50008. */
  50009. virtual void setOrigin (int x, int y) = 0;
  50010. virtual void addTransform (const AffineTransform& transform) = 0;
  50011. virtual float getScaleFactor() = 0;
  50012. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  50013. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  50014. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  50015. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  50016. virtual void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform) = 0;
  50017. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  50018. virtual const Rectangle<int> getClipBounds() const = 0;
  50019. virtual bool isClipEmpty() const = 0;
  50020. virtual void saveState() = 0;
  50021. virtual void restoreState() = 0;
  50022. virtual void beginTransparencyLayer (float opacity) = 0;
  50023. virtual void endTransparencyLayer() = 0;
  50024. virtual void setFill (const FillType& fillType) = 0;
  50025. virtual void setOpacity (float newOpacity) = 0;
  50026. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  50027. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  50028. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  50029. virtual void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  50030. virtual void drawLine (const Line <float>& line) = 0;
  50031. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  50032. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  50033. virtual void setFont (const Font& newFont) = 0;
  50034. virtual const Font getFont() = 0;
  50035. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  50036. };
  50037. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  50038. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  50039. #endif
  50040. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50041. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  50042. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50043. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50044. /**
  50045. An implementation of LowLevelGraphicsContext that turns the drawing operations
  50046. into a PostScript document.
  50047. */
  50048. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  50049. {
  50050. public:
  50051. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  50052. const String& documentTitle,
  50053. int totalWidth,
  50054. int totalHeight);
  50055. ~LowLevelGraphicsPostScriptRenderer();
  50056. bool isVectorDevice() const;
  50057. void setOrigin (int x, int y);
  50058. void addTransform (const AffineTransform& transform);
  50059. float getScaleFactor();
  50060. bool clipToRectangle (const Rectangle<int>& r);
  50061. bool clipToRectangleList (const RectangleList& clipRegion);
  50062. void excludeClipRectangle (const Rectangle<int>& r);
  50063. void clipToPath (const Path& path, const AffineTransform& transform);
  50064. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  50065. void saveState();
  50066. void restoreState();
  50067. void beginTransparencyLayer (float opacity);
  50068. void endTransparencyLayer();
  50069. bool clipRegionIntersects (const Rectangle<int>& r);
  50070. const Rectangle<int> getClipBounds() const;
  50071. bool isClipEmpty() const;
  50072. void setFill (const FillType& fillType);
  50073. void setOpacity (float opacity);
  50074. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  50075. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  50076. void fillPath (const Path& path, const AffineTransform& transform);
  50077. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  50078. void drawLine (const Line <float>& line);
  50079. void drawVerticalLine (int x, float top, float bottom);
  50080. void drawHorizontalLine (int x, float top, float bottom);
  50081. const Font getFont();
  50082. void setFont (const Font& newFont);
  50083. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  50084. protected:
  50085. OutputStream& out;
  50086. int totalWidth, totalHeight;
  50087. bool needToClip;
  50088. Colour lastColour;
  50089. struct SavedState
  50090. {
  50091. SavedState();
  50092. ~SavedState();
  50093. RectangleList clip;
  50094. int xOffset, yOffset;
  50095. FillType fillType;
  50096. Font font;
  50097. private:
  50098. SavedState& operator= (const SavedState&);
  50099. };
  50100. OwnedArray <SavedState> stateStack;
  50101. void writeClip();
  50102. void writeColour (const Colour& colour);
  50103. void writePath (const Path& path) const;
  50104. void writeXY (float x, float y) const;
  50105. void writeTransform (const AffineTransform& trans) const;
  50106. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  50107. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsPostScriptRenderer);
  50108. };
  50109. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50110. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  50111. #endif
  50112. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50113. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  50114. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50115. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50116. /**
  50117. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  50118. its rendering in memory.
  50119. User code is not supposed to create instances of this class directly - do all your
  50120. rendering via the Graphics class instead.
  50121. */
  50122. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  50123. {
  50124. public:
  50125. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  50126. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  50127. ~LowLevelGraphicsSoftwareRenderer();
  50128. bool isVectorDevice() const;
  50129. void setOrigin (int x, int y);
  50130. void addTransform (const AffineTransform& transform);
  50131. float getScaleFactor();
  50132. bool clipToRectangle (const Rectangle<int>& r);
  50133. bool clipToRectangleList (const RectangleList& clipRegion);
  50134. void excludeClipRectangle (const Rectangle<int>& r);
  50135. void clipToPath (const Path& path, const AffineTransform& transform);
  50136. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  50137. bool clipRegionIntersects (const Rectangle<int>& r);
  50138. const Rectangle<int> getClipBounds() const;
  50139. bool isClipEmpty() const;
  50140. void saveState();
  50141. void restoreState();
  50142. void beginTransparencyLayer (float opacity);
  50143. void endTransparencyLayer();
  50144. void setFill (const FillType& fillType);
  50145. void setOpacity (float opacity);
  50146. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  50147. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  50148. void fillPath (const Path& path, const AffineTransform& transform);
  50149. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  50150. void drawLine (const Line <float>& line);
  50151. void drawVerticalLine (int x, float top, float bottom);
  50152. void drawHorizontalLine (int x, float top, float bottom);
  50153. void setFont (const Font& newFont);
  50154. const Font getFont();
  50155. void drawGlyph (int glyphNumber, float x, float y);
  50156. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  50157. protected:
  50158. Image image;
  50159. class GlyphCache;
  50160. class CachedGlyph;
  50161. class SavedState;
  50162. friend class ScopedPointer <SavedState>;
  50163. friend class OwnedArray <SavedState>;
  50164. friend class OwnedArray <CachedGlyph>;
  50165. ScopedPointer <SavedState> currentState;
  50166. OwnedArray <SavedState> stateStack;
  50167. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsSoftwareRenderer);
  50168. };
  50169. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50170. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  50171. #endif
  50172. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  50173. #endif
  50174. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  50175. #endif
  50176. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  50177. /*** Start of inlined file: juce_DrawableComposite.h ***/
  50178. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  50179. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  50180. /**
  50181. A drawable object which acts as a container for a set of other Drawables.
  50182. @see Drawable
  50183. */
  50184. class JUCE_API DrawableComposite : public Drawable
  50185. {
  50186. public:
  50187. /** Creates a composite Drawable. */
  50188. DrawableComposite();
  50189. /** Creates a copy of a DrawableComposite. */
  50190. DrawableComposite (const DrawableComposite& other);
  50191. /** Destructor. */
  50192. ~DrawableComposite();
  50193. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  50194. @see setContentArea
  50195. */
  50196. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  50197. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  50198. @see setBoundingBox
  50199. */
  50200. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  50201. /** Changes the bounding box transform to match the content area, so that any sub-items will
  50202. be drawn at their untransformed positions.
  50203. */
  50204. void resetBoundingBoxToContentArea();
  50205. /** Returns the main content rectangle.
  50206. The content area is actually defined by the markers named "left", "right", "top" and
  50207. "bottom", but this method is a shortcut that returns them all at once.
  50208. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  50209. */
  50210. const RelativeRectangle getContentArea() const;
  50211. /** Changes the main content area.
  50212. The content area is actually defined by the markers named "left", "right", "top" and
  50213. "bottom", but this method is a shortcut that sets them all at once.
  50214. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  50215. */
  50216. void setContentArea (const RelativeRectangle& newArea);
  50217. /** Resets the content area and the bounding transform to fit around the area occupied
  50218. by the child components (ignoring any markers).
  50219. */
  50220. void resetContentAreaAndBoundingBoxToFitChildren();
  50221. /** The name of the marker that defines the left edge of the content area. */
  50222. static const char* const contentLeftMarkerName;
  50223. /** The name of the marker that defines the right edge of the content area. */
  50224. static const char* const contentRightMarkerName;
  50225. /** The name of the marker that defines the top edge of the content area. */
  50226. static const char* const contentTopMarkerName;
  50227. /** The name of the marker that defines the bottom edge of the content area. */
  50228. static const char* const contentBottomMarkerName;
  50229. /** @internal */
  50230. Drawable* createCopy() const;
  50231. /** @internal */
  50232. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50233. /** @internal */
  50234. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50235. /** @internal */
  50236. static const Identifier valueTreeType;
  50237. /** @internal */
  50238. const Rectangle<float> getDrawableBounds() const;
  50239. /** @internal */
  50240. void childBoundsChanged (Component*);
  50241. /** @internal */
  50242. void childrenChanged();
  50243. /** @internal */
  50244. void parentHierarchyChanged();
  50245. /** @internal */
  50246. MarkerList* getMarkers (bool xAxis);
  50247. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  50248. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  50249. {
  50250. public:
  50251. ValueTreeWrapper (const ValueTree& state);
  50252. ValueTree getChildList() const;
  50253. ValueTree getChildListCreating (UndoManager* undoManager);
  50254. const RelativeParallelogram getBoundingBox() const;
  50255. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  50256. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  50257. const RelativeRectangle getContentArea() const;
  50258. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  50259. MarkerList::ValueTreeWrapper getMarkerList (bool xAxis) const;
  50260. MarkerList::ValueTreeWrapper getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  50261. static const Identifier topLeft, topRight, bottomLeft;
  50262. private:
  50263. static const Identifier childGroupTag, markerGroupTagX, markerGroupTagY;
  50264. };
  50265. private:
  50266. RelativeParallelogram bounds;
  50267. MarkerList markersX, markersY;
  50268. bool updateBoundsReentrant;
  50269. friend class Drawable::Positioner<DrawableComposite>;
  50270. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  50271. void recalculateCoordinates (Expression::Scope*);
  50272. void updateBoundsToFitChildren();
  50273. DrawableComposite& operator= (const DrawableComposite&);
  50274. JUCE_LEAK_DETECTOR (DrawableComposite);
  50275. };
  50276. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  50277. /*** End of inlined file: juce_DrawableComposite.h ***/
  50278. #endif
  50279. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50280. /*** Start of inlined file: juce_DrawableImage.h ***/
  50281. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50282. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50283. /**
  50284. A drawable object which is a bitmap image.
  50285. @see Drawable
  50286. */
  50287. class JUCE_API DrawableImage : public Drawable
  50288. {
  50289. public:
  50290. DrawableImage();
  50291. DrawableImage (const DrawableImage& other);
  50292. /** Destructor. */
  50293. ~DrawableImage();
  50294. /** Sets the image that this drawable will render. */
  50295. void setImage (const Image& imageToUse);
  50296. /** Returns the current image. */
  50297. const Image getImage() const { return image; }
  50298. /** Sets the opacity to use when drawing the image. */
  50299. void setOpacity (float newOpacity);
  50300. /** Returns the image's opacity. */
  50301. float getOpacity() const noexcept { return opacity; }
  50302. /** Sets a colour to draw over the image's alpha channel.
  50303. By default this is transparent so isn't drawn, but if you set a non-transparent
  50304. colour here, then it will be overlaid on the image, using the image's alpha
  50305. channel as a mask.
  50306. This is handy for doing things like darkening or lightening an image by overlaying
  50307. it with semi-transparent black or white.
  50308. */
  50309. void setOverlayColour (const Colour& newOverlayColour);
  50310. /** Returns the overlay colour. */
  50311. const Colour& getOverlayColour() const noexcept { return overlayColour; }
  50312. /** Sets the bounding box within which the image should be displayed. */
  50313. void setBoundingBox (const RelativeParallelogram& newBounds);
  50314. /** Returns the position to which the image's top-left corner should be remapped in the target
  50315. coordinate space when rendering this object.
  50316. @see setTransform
  50317. */
  50318. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  50319. /** @internal */
  50320. void paint (Graphics& g);
  50321. /** @internal */
  50322. bool hitTest (int x, int y);
  50323. /** @internal */
  50324. Drawable* createCopy() const;
  50325. /** @internal */
  50326. const Rectangle<float> getDrawableBounds() const;
  50327. /** @internal */
  50328. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50329. /** @internal */
  50330. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50331. /** @internal */
  50332. static const Identifier valueTreeType;
  50333. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  50334. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  50335. {
  50336. public:
  50337. ValueTreeWrapper (const ValueTree& state);
  50338. const var getImageIdentifier() const;
  50339. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  50340. Value getImageIdentifierValue (UndoManager* undoManager);
  50341. float getOpacity() const;
  50342. void setOpacity (float newOpacity, UndoManager* undoManager);
  50343. Value getOpacityValue (UndoManager* undoManager);
  50344. const Colour getOverlayColour() const;
  50345. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  50346. Value getOverlayColourValue (UndoManager* undoManager);
  50347. const RelativeParallelogram getBoundingBox() const;
  50348. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  50349. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  50350. };
  50351. private:
  50352. Image image;
  50353. float opacity;
  50354. Colour overlayColour;
  50355. RelativeParallelogram bounds;
  50356. friend class Drawable::Positioner<DrawableImage>;
  50357. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  50358. void recalculateCoordinates (Expression::Scope*);
  50359. DrawableImage& operator= (const DrawableImage&);
  50360. JUCE_LEAK_DETECTOR (DrawableImage);
  50361. };
  50362. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50363. /*** End of inlined file: juce_DrawableImage.h ***/
  50364. #endif
  50365. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  50366. /*** Start of inlined file: juce_DrawablePath.h ***/
  50367. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  50368. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  50369. /*** Start of inlined file: juce_DrawableShape.h ***/
  50370. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  50371. #define __JUCE_DRAWABLESHAPE_JUCEHEADER__
  50372. /**
  50373. A base class implementing common functionality for Drawable classes which
  50374. consist of some kind of filled and stroked outline.
  50375. @see DrawablePath, DrawableRectangle
  50376. */
  50377. class JUCE_API DrawableShape : public Drawable
  50378. {
  50379. protected:
  50380. DrawableShape();
  50381. DrawableShape (const DrawableShape&);
  50382. public:
  50383. /** Destructor. */
  50384. ~DrawableShape();
  50385. /** A FillType wrapper that allows the gradient coordinates to be implemented using RelativePoint.
  50386. */
  50387. class RelativeFillType
  50388. {
  50389. public:
  50390. RelativeFillType();
  50391. RelativeFillType (const FillType& fill);
  50392. RelativeFillType (const RelativeFillType&);
  50393. RelativeFillType& operator= (const RelativeFillType&);
  50394. bool operator== (const RelativeFillType&) const;
  50395. bool operator!= (const RelativeFillType&) const;
  50396. bool isDynamic() const;
  50397. bool recalculateCoords (Expression::Scope* scope);
  50398. void writeTo (ValueTree& v, ComponentBuilder::ImageProvider*, UndoManager*) const;
  50399. bool readFrom (const ValueTree& v, ComponentBuilder::ImageProvider*);
  50400. FillType fill;
  50401. RelativePoint gradientPoint1, gradientPoint2, gradientPoint3;
  50402. };
  50403. /** Sets a fill type for the path.
  50404. This colour is used to fill the path - if you don't want the path to be
  50405. filled (e.g. if you're just drawing an outline), set this to a transparent
  50406. colour.
  50407. @see setPath, setStrokeFill
  50408. */
  50409. void setFill (const FillType& newFill);
  50410. /** Sets a fill type for the path.
  50411. This colour is used to fill the path - if you don't want the path to be
  50412. filled (e.g. if you're just drawing an outline), set this to a transparent
  50413. colour.
  50414. @see setPath, setStrokeFill
  50415. */
  50416. void setFill (const RelativeFillType& newFill);
  50417. /** Returns the current fill type.
  50418. @see setFill
  50419. */
  50420. const RelativeFillType& getFill() const noexcept { return mainFill; }
  50421. /** Sets the fill type with which the outline will be drawn.
  50422. @see setFill
  50423. */
  50424. void setStrokeFill (const FillType& newStrokeFill);
  50425. /** Sets the fill type with which the outline will be drawn.
  50426. @see setFill
  50427. */
  50428. void setStrokeFill (const RelativeFillType& newStrokeFill);
  50429. /** Returns the current stroke fill.
  50430. @see setStrokeFill
  50431. */
  50432. const RelativeFillType& getStrokeFill() const noexcept { return strokeFill; }
  50433. /** Changes the properties of the outline that will be drawn around the path.
  50434. If the stroke has 0 thickness, no stroke will be drawn.
  50435. @see setStrokeThickness, setStrokeColour
  50436. */
  50437. void setStrokeType (const PathStrokeType& newStrokeType);
  50438. /** Changes the stroke thickness.
  50439. This is a shortcut for calling setStrokeType.
  50440. */
  50441. void setStrokeThickness (float newThickness);
  50442. /** Returns the current outline style. */
  50443. const PathStrokeType& getStrokeType() const noexcept { return strokeType; }
  50444. /** @internal */
  50445. class FillAndStrokeState : public Drawable::ValueTreeWrapperBase
  50446. {
  50447. public:
  50448. FillAndStrokeState (const ValueTree& state);
  50449. ValueTree getFillState (const Identifier& fillOrStrokeType);
  50450. const RelativeFillType getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider*) const;
  50451. void setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  50452. ComponentBuilder::ImageProvider*, UndoManager*);
  50453. const PathStrokeType getStrokeType() const;
  50454. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager*);
  50455. static const Identifier type, colour, colours, fill, stroke, path, jointStyle, capStyle, strokeWidth,
  50456. gradientPoint1, gradientPoint2, gradientPoint3, radial, imageId, imageOpacity;
  50457. };
  50458. /** @internal */
  50459. const Rectangle<float> getDrawableBounds() const;
  50460. /** @internal */
  50461. void paint (Graphics& g);
  50462. /** @internal */
  50463. bool hitTest (int x, int y);
  50464. protected:
  50465. /** Called when the cached path should be updated. */
  50466. void pathChanged();
  50467. /** Called when the cached stroke should be updated. */
  50468. void strokeChanged();
  50469. /** True if there's a stroke with a non-zero thickness and non-transparent colour. */
  50470. bool isStrokeVisible() const noexcept;
  50471. /** Updates the details from a FillAndStrokeState object, returning true if something changed. */
  50472. void refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider*);
  50473. /** Writes the stroke and fill details to a FillAndStrokeState object. */
  50474. void writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider*, UndoManager*) const;
  50475. PathStrokeType strokeType;
  50476. Path path, strokePath;
  50477. private:
  50478. class RelativePositioner;
  50479. RelativeFillType mainFill, strokeFill;
  50480. ScopedPointer<RelativeCoordinatePositionerBase> mainFillPositioner, strokeFillPositioner;
  50481. void setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  50482. ScopedPointer<RelativeCoordinatePositionerBase>& positioner);
  50483. DrawableShape& operator= (const DrawableShape&);
  50484. };
  50485. #endif // __JUCE_DRAWABLESHAPE_JUCEHEADER__
  50486. /*** End of inlined file: juce_DrawableShape.h ***/
  50487. /**
  50488. A drawable object which renders a filled or outlined shape.
  50489. For details on how to change the fill and stroke, see the DrawableShape class.
  50490. @see Drawable, DrawableShape
  50491. */
  50492. class JUCE_API DrawablePath : public DrawableShape
  50493. {
  50494. public:
  50495. /** Creates a DrawablePath. */
  50496. DrawablePath();
  50497. DrawablePath (const DrawablePath& other);
  50498. /** Destructor. */
  50499. ~DrawablePath();
  50500. /** Changes the path that will be drawn.
  50501. @see setFillColour, setStrokeType
  50502. */
  50503. void setPath (const Path& newPath);
  50504. /** Sets the path using a RelativePointPath.
  50505. Calling this will set up a Component::Positioner to automatically update the path
  50506. if any of the points in the source path are dynamic.
  50507. */
  50508. void setPath (const RelativePointPath& newPath);
  50509. /** Returns the current path. */
  50510. const Path& getPath() const;
  50511. /** Returns the current path for the outline. */
  50512. const Path& getStrokePath() const;
  50513. /** @internal */
  50514. Drawable* createCopy() const;
  50515. /** @internal */
  50516. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50517. /** @internal */
  50518. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50519. /** @internal */
  50520. static const Identifier valueTreeType;
  50521. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  50522. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  50523. {
  50524. public:
  50525. ValueTreeWrapper (const ValueTree& state);
  50526. bool usesNonZeroWinding() const;
  50527. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  50528. class Element
  50529. {
  50530. public:
  50531. explicit Element (const ValueTree& state);
  50532. ~Element();
  50533. const Identifier getType() const noexcept { return state.getType(); }
  50534. int getNumControlPoints() const noexcept;
  50535. const RelativePoint getControlPoint (int index) const;
  50536. Value getControlPointValue (int index, UndoManager*) const;
  50537. const RelativePoint getStartPoint() const;
  50538. const RelativePoint getEndPoint() const;
  50539. void setControlPoint (int index, const RelativePoint& point, UndoManager*);
  50540. float getLength (Expression::Scope*) const;
  50541. ValueTreeWrapper getParent() const;
  50542. Element getPreviousElement() const;
  50543. const String getModeOfEndPoint() const;
  50544. void setModeOfEndPoint (const String& newMode, UndoManager*);
  50545. void convertToLine (UndoManager*);
  50546. void convertToCubic (Expression::Scope*, UndoManager*);
  50547. void convertToPathBreak (UndoManager* undoManager);
  50548. ValueTree insertPoint (const Point<float>& targetPoint, Expression::Scope*, UndoManager*);
  50549. void removePoint (UndoManager* undoManager);
  50550. float findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope*) const;
  50551. static const Identifier mode, startSubPathElement, closeSubPathElement,
  50552. lineToElement, quadraticToElement, cubicToElement;
  50553. static const char* cornerMode;
  50554. static const char* roundedMode;
  50555. static const char* symmetricMode;
  50556. ValueTree state;
  50557. };
  50558. ValueTree getPathState();
  50559. void readFrom (const RelativePointPath& path, UndoManager* undoManager);
  50560. void writeTo (RelativePointPath& path) const;
  50561. static const Identifier nonZeroWinding, point1, point2, point3;
  50562. };
  50563. private:
  50564. ScopedPointer<RelativePointPath> relativePath;
  50565. class RelativePositioner;
  50566. friend class RelativePositioner;
  50567. void applyRelativePath (const RelativePointPath&, Expression::Scope*);
  50568. DrawablePath& operator= (const DrawablePath&);
  50569. JUCE_LEAK_DETECTOR (DrawablePath);
  50570. };
  50571. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  50572. /*** End of inlined file: juce_DrawablePath.h ***/
  50573. #endif
  50574. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  50575. /*** Start of inlined file: juce_DrawableRectangle.h ***/
  50576. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  50577. #define __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  50578. /**
  50579. A Drawable object which draws a rectangle.
  50580. For details on how to change the fill and stroke, see the DrawableShape class.
  50581. @see Drawable, DrawableShape
  50582. */
  50583. class JUCE_API DrawableRectangle : public DrawableShape
  50584. {
  50585. public:
  50586. DrawableRectangle();
  50587. DrawableRectangle (const DrawableRectangle& other);
  50588. /** Destructor. */
  50589. ~DrawableRectangle();
  50590. /** Sets the rectangle's bounds. */
  50591. void setRectangle (const RelativeParallelogram& newBounds);
  50592. /** Returns the rectangle's bounds. */
  50593. const RelativeParallelogram& getRectangle() const noexcept { return bounds; }
  50594. /** Returns the corner size to be used. */
  50595. const RelativePoint getCornerSize() const { return cornerSize; }
  50596. /** Sets a new corner size for the rectangle */
  50597. void setCornerSize (const RelativePoint& newSize);
  50598. /** @internal */
  50599. Drawable* createCopy() const;
  50600. /** @internal */
  50601. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50602. /** @internal */
  50603. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50604. /** @internal */
  50605. static const Identifier valueTreeType;
  50606. /** Internally-used class for wrapping a DrawableRectangle's state into a ValueTree. */
  50607. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  50608. {
  50609. public:
  50610. ValueTreeWrapper (const ValueTree& state);
  50611. const RelativeParallelogram getRectangle() const;
  50612. void setRectangle (const RelativeParallelogram& newBounds, UndoManager*);
  50613. void setCornerSize (const RelativePoint& cornerSize, UndoManager*);
  50614. const RelativePoint getCornerSize() const;
  50615. Value getCornerSizeValue (UndoManager*) const;
  50616. static const Identifier topLeft, topRight, bottomLeft, cornerSize;
  50617. };
  50618. private:
  50619. friend class Drawable::Positioner<DrawableRectangle>;
  50620. RelativeParallelogram bounds;
  50621. RelativePoint cornerSize;
  50622. void rebuildPath();
  50623. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  50624. void recalculateCoordinates (Expression::Scope*);
  50625. DrawableRectangle& operator= (const DrawableRectangle&);
  50626. JUCE_LEAK_DETECTOR (DrawableRectangle);
  50627. };
  50628. #endif // __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  50629. /*** End of inlined file: juce_DrawableRectangle.h ***/
  50630. #endif
  50631. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  50632. #endif
  50633. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  50634. /*** Start of inlined file: juce_DrawableText.h ***/
  50635. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  50636. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  50637. /**
  50638. A drawable object which renders a line of text.
  50639. @see Drawable
  50640. */
  50641. class JUCE_API DrawableText : public Drawable
  50642. {
  50643. public:
  50644. /** Creates a DrawableText object. */
  50645. DrawableText();
  50646. DrawableText (const DrawableText& other);
  50647. /** Destructor. */
  50648. ~DrawableText();
  50649. /** Sets the text to display.*/
  50650. void setText (const String& newText);
  50651. /** Sets the colour of the text. */
  50652. void setColour (const Colour& newColour);
  50653. /** Returns the current text colour. */
  50654. const Colour& getColour() const noexcept { return colour; }
  50655. /** Sets the font to use.
  50656. Note that the font height and horizontal scale are actually based upon the position
  50657. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  50658. the height and scale control point will be moved to match the dimensions of the font supplied;
  50659. if it is false, then the new font's height and scale are ignored.
  50660. */
  50661. void setFont (const Font& newFont, bool applySizeAndScale);
  50662. /** Changes the justification of the text within the bounding box. */
  50663. void setJustification (const Justification& newJustification);
  50664. /** Returns the parallelogram that defines the text bounding box. */
  50665. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  50666. /** Sets the bounding box that contains the text. */
  50667. void setBoundingBox (const RelativeParallelogram& newBounds);
  50668. /** Returns the point within the bounds that defines the font's size and scale. */
  50669. const RelativePoint& getFontSizeControlPoint() const noexcept { return fontSizeControlPoint; }
  50670. /** Sets the control point that defines the font's height and horizontal scale.
  50671. This position is a point within the bounding box parallelogram, whose Y position (relative
  50672. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  50673. and its X defines the font's horizontal scale.
  50674. */
  50675. void setFontSizeControlPoint (const RelativePoint& newPoint);
  50676. /** @internal */
  50677. void paint (Graphics& g);
  50678. /** @internal */
  50679. Drawable* createCopy() const;
  50680. /** @internal */
  50681. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50682. /** @internal */
  50683. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50684. /** @internal */
  50685. static const Identifier valueTreeType;
  50686. /** @internal */
  50687. const Rectangle<float> getDrawableBounds() const;
  50688. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  50689. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  50690. {
  50691. public:
  50692. ValueTreeWrapper (const ValueTree& state);
  50693. const String getText() const;
  50694. void setText (const String& newText, UndoManager* undoManager);
  50695. Value getTextValue (UndoManager* undoManager);
  50696. const Colour getColour() const;
  50697. void setColour (const Colour& newColour, UndoManager* undoManager);
  50698. const Justification getJustification() const;
  50699. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  50700. const Font getFont() const;
  50701. void setFont (const Font& newFont, UndoManager* undoManager);
  50702. Value getFontValue (UndoManager* undoManager);
  50703. const RelativeParallelogram getBoundingBox() const;
  50704. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  50705. const RelativePoint getFontSizeControlPoint() const;
  50706. void setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager);
  50707. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  50708. };
  50709. private:
  50710. RelativeParallelogram bounds;
  50711. RelativePoint fontSizeControlPoint;
  50712. Point<float> resolvedPoints[3];
  50713. Font font, scaledFont;
  50714. String text;
  50715. Colour colour;
  50716. Justification justification;
  50717. friend class Drawable::Positioner<DrawableText>;
  50718. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  50719. void recalculateCoordinates (Expression::Scope*);
  50720. void refreshBounds();
  50721. const AffineTransform getArrangementAndTransform (GlyphArrangement& glyphs) const;
  50722. DrawableText& operator= (const DrawableText&);
  50723. JUCE_LEAK_DETECTOR (DrawableText);
  50724. };
  50725. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  50726. /*** End of inlined file: juce_DrawableText.h ***/
  50727. #endif
  50728. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  50729. #endif
  50730. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  50731. /*** Start of inlined file: juce_GlowEffect.h ***/
  50732. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  50733. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  50734. /**
  50735. A component effect that adds a coloured blur around the component's contents.
  50736. (This will only work on non-opaque components).
  50737. @see Component::setComponentEffect, DropShadowEffect
  50738. */
  50739. class JUCE_API GlowEffect : public ImageEffectFilter
  50740. {
  50741. public:
  50742. /** Creates a default 'glow' effect.
  50743. To customise its appearance, use the setGlowProperties() method.
  50744. */
  50745. GlowEffect();
  50746. /** Destructor. */
  50747. ~GlowEffect();
  50748. /** Sets the glow's radius and colour.
  50749. The radius is how large the blur should be, and the colour is
  50750. used to render it (for a less intense glow, lower the colour's
  50751. opacity).
  50752. */
  50753. void setGlowProperties (float newRadius,
  50754. const Colour& newColour);
  50755. /** @internal */
  50756. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  50757. private:
  50758. float radius;
  50759. Colour colour;
  50760. JUCE_LEAK_DETECTOR (GlowEffect);
  50761. };
  50762. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  50763. /*** End of inlined file: juce_GlowEffect.h ***/
  50764. #endif
  50765. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  50766. #endif
  50767. #ifndef __JUCE_FONT_JUCEHEADER__
  50768. #endif
  50769. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  50770. #endif
  50771. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  50772. #endif
  50773. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  50774. #endif
  50775. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  50776. #endif
  50777. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  50778. #endif
  50779. #ifndef __JUCE_LINE_JUCEHEADER__
  50780. #endif
  50781. #ifndef __JUCE_PATH_JUCEHEADER__
  50782. #endif
  50783. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  50784. /*** Start of inlined file: juce_PathIterator.h ***/
  50785. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  50786. #define __JUCE_PATHITERATOR_JUCEHEADER__
  50787. /**
  50788. Flattens a Path object into a series of straight-line sections.
  50789. Use one of these to iterate through a Path object, and it will convert
  50790. all the curves into line sections so it's easy to render or perform
  50791. geometric operations on.
  50792. @see Path
  50793. */
  50794. class JUCE_API PathFlatteningIterator
  50795. {
  50796. public:
  50797. /** Creates a PathFlatteningIterator.
  50798. After creation, use the next() method to initialise the fields in the
  50799. object with the first line's position.
  50800. @param path the path to iterate along
  50801. @param transform a transform to apply to each point in the path being iterated
  50802. @param tolerance the amount by which the curves are allowed to deviate from the lines
  50803. into which they are being broken down - a higher tolerance contains
  50804. less lines, so can be generated faster, but will be less smooth.
  50805. */
  50806. PathFlatteningIterator (const Path& path,
  50807. const AffineTransform& transform = AffineTransform::identity,
  50808. float tolerance = defaultTolerance);
  50809. /** Destructor. */
  50810. ~PathFlatteningIterator();
  50811. /** Fetches the next line segment from the path.
  50812. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  50813. so that they describe the new line segment.
  50814. @returns false when there are no more lines to fetch.
  50815. */
  50816. bool next();
  50817. float x1; /**< The x position of the start of the current line segment. */
  50818. float y1; /**< The y position of the start of the current line segment. */
  50819. float x2; /**< The x position of the end of the current line segment. */
  50820. float y2; /**< The y position of the end of the current line segment. */
  50821. /** Indicates whether the current line segment is closing a sub-path.
  50822. If the current line is the one that connects the end of a sub-path
  50823. back to the start again, this will be true.
  50824. */
  50825. bool closesSubPath;
  50826. /** The index of the current line within the current sub-path.
  50827. E.g. you can use this to see whether the line is the first one in the
  50828. subpath by seeing if it's 0.
  50829. */
  50830. int subPathIndex;
  50831. /** Returns true if the current segment is the last in the current sub-path. */
  50832. bool isLastInSubpath() const noexcept;
  50833. /** This is the default value that should be used for the tolerance value (see the constructor parameters). */
  50834. static const float defaultTolerance;
  50835. private:
  50836. const Path& path;
  50837. const AffineTransform transform;
  50838. float* points;
  50839. const float toleranceSquared;
  50840. float subPathCloseX, subPathCloseY;
  50841. const bool isIdentityTransform;
  50842. HeapBlock <float> stackBase;
  50843. float* stackPos;
  50844. size_t index, stackSize;
  50845. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PathFlatteningIterator);
  50846. };
  50847. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  50848. /*** End of inlined file: juce_PathIterator.h ***/
  50849. #endif
  50850. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  50851. #endif
  50852. #ifndef __JUCE_POINT_JUCEHEADER__
  50853. #endif
  50854. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  50855. #endif
  50856. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  50857. #endif
  50858. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  50859. /*** Start of inlined file: juce_CameraDevice.h ***/
  50860. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  50861. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  50862. #if JUCE_USE_CAMERA || DOXYGEN
  50863. /**
  50864. Controls any video capture devices that might be available.
  50865. Use getAvailableDevices() to list the devices that are attached to the
  50866. system, then call openDevice to open one for use. Once you have a CameraDevice
  50867. object, you can get a viewer component from it, and use its methods to
  50868. stream to a file or capture still-frames.
  50869. */
  50870. class JUCE_API CameraDevice
  50871. {
  50872. public:
  50873. /** Destructor. */
  50874. virtual ~CameraDevice();
  50875. /** Returns a list of the available cameras on this machine.
  50876. You can open one of these devices by calling openDevice().
  50877. */
  50878. static const StringArray getAvailableDevices();
  50879. /** Opens a camera device.
  50880. The index parameter indicates which of the items returned by getAvailableDevices()
  50881. to open.
  50882. The size constraints allow the method to choose between different resolutions if
  50883. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  50884. then these will be ignored.
  50885. */
  50886. static CameraDevice* openDevice (int deviceIndex,
  50887. int minWidth = 128, int minHeight = 64,
  50888. int maxWidth = 1024, int maxHeight = 768);
  50889. /** Returns the name of this device */
  50890. const String getName() const { return name; }
  50891. /** Creates a component that can be used to display a preview of the
  50892. video from this camera.
  50893. */
  50894. Component* createViewerComponent();
  50895. /** Starts recording video to the specified file.
  50896. You should use getFileExtension() to find out the correct extension to
  50897. use for your filename.
  50898. If the file exists, it will be deleted before the recording starts.
  50899. This method may not start recording instantly, so if you need to know the
  50900. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  50901. after the recording has finished.
  50902. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  50903. or may not be used, depending on the driver.
  50904. */
  50905. void startRecordingToFile (const File& file, int quality = 2);
  50906. /** Stops recording, after a call to startRecordingToFile().
  50907. */
  50908. void stopRecording();
  50909. /** Returns the file extension that should be used for the files
  50910. that you pass to startRecordingToFile().
  50911. This may be platform-specific, e.g. ".mov" or ".avi".
  50912. */
  50913. static const String getFileExtension();
  50914. /** After calling stopRecording(), this method can be called to return the timestamp
  50915. of the first frame that was written to the file.
  50916. */
  50917. const Time getTimeOfFirstRecordedFrame() const;
  50918. /**
  50919. Receives callbacks with images from a CameraDevice.
  50920. @see CameraDevice::addListener
  50921. */
  50922. class JUCE_API Listener
  50923. {
  50924. public:
  50925. Listener() {}
  50926. virtual ~Listener() {}
  50927. /** This method is called when a new image arrives.
  50928. This may be called by any thread, so be careful about thread-safety,
  50929. and make sure that you process the data as quickly as possible to
  50930. avoid glitching!
  50931. */
  50932. virtual void imageReceived (const Image& image) = 0;
  50933. };
  50934. /** Adds a listener to receive images from the camera.
  50935. Be very careful not to delete the listener without first removing it by calling
  50936. removeListener().
  50937. */
  50938. void addListener (Listener* listenerToAdd);
  50939. /** Removes a listener that was previously added with addListener().
  50940. */
  50941. void removeListener (Listener* listenerToRemove);
  50942. protected:
  50943. #ifndef DOXYGEN
  50944. CameraDevice (const String& name, int index);
  50945. #endif
  50946. private:
  50947. void* internal;
  50948. bool isRecording;
  50949. String name;
  50950. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CameraDevice);
  50951. };
  50952. /** This typedef is just for compatibility with old code - newer code should use the CameraDevice::Listener class directly. */
  50953. typedef CameraDevice::Listener CameraImageListener;
  50954. #endif
  50955. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  50956. /*** End of inlined file: juce_CameraDevice.h ***/
  50957. #endif
  50958. #ifndef __JUCE_IMAGE_JUCEHEADER__
  50959. #endif
  50960. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  50961. /*** Start of inlined file: juce_ImageCache.h ***/
  50962. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  50963. #define __JUCE_IMAGECACHE_JUCEHEADER__
  50964. /**
  50965. A global cache of images that have been loaded from files or memory.
  50966. If you're loading an image and may need to use the image in more than one
  50967. place, this is used to allow the same image to be shared rather than loading
  50968. multiple copies into memory.
  50969. Another advantage is that after images are released, they will be kept in
  50970. memory for a few seconds before it is actually deleted, so if you're repeatedly
  50971. loading/deleting the same image, it'll reduce the chances of having to reload it
  50972. each time.
  50973. @see Image, ImageFileFormat
  50974. */
  50975. class JUCE_API ImageCache
  50976. {
  50977. public:
  50978. /** Loads an image from a file, (or just returns the image if it's already cached).
  50979. If the cache already contains an image that was loaded from this file,
  50980. that image will be returned. Otherwise, this method will try to load the
  50981. file, add it to the cache, and return it.
  50982. Remember that the image returned is shared, so drawing into it might
  50983. affect other things that are using it! If you want to draw on it, first
  50984. call Image::duplicateIfShared()
  50985. @param file the file to try to load
  50986. @returns the image, or null if it there was an error loading it
  50987. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  50988. */
  50989. static const Image getFromFile (const File& file);
  50990. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  50991. If the cache already contains an image that was loaded from this block of memory,
  50992. that image will be returned. Otherwise, this method will try to load the
  50993. file, add it to the cache, and return it.
  50994. Remember that the image returned is shared, so drawing into it might
  50995. affect other things that are using it! If you want to draw on it, first
  50996. call Image::duplicateIfShared()
  50997. @param imageData the block of memory containing the image data
  50998. @param dataSize the data size in bytes
  50999. @returns the image, or an invalid image if it there was an error loading it
  51000. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  51001. */
  51002. static const Image getFromMemory (const void* imageData, int dataSize);
  51003. /** Checks the cache for an image with a particular hashcode.
  51004. If there's an image in the cache with this hashcode, it will be returned,
  51005. otherwise it will return an invalid image.
  51006. @param hashCode the hash code that was associated with the image by addImageToCache()
  51007. @see addImageToCache
  51008. */
  51009. static const Image getFromHashCode (int64 hashCode);
  51010. /** Adds an image to the cache with a user-defined hash-code.
  51011. The image passed-in will be referenced (not copied) by the cache, so it's probably
  51012. a good idea not to draw into it after adding it, otherwise this will affect all
  51013. instances of it that may be in use.
  51014. @param image the image to add
  51015. @param hashCode the hash-code to associate with it
  51016. @see getFromHashCode
  51017. */
  51018. static void addImageToCache (const Image& image, int64 hashCode);
  51019. /** Changes the amount of time before an unused image will be removed from the cache.
  51020. By default this is about 5 seconds.
  51021. */
  51022. static void setCacheTimeout (int millisecs);
  51023. private:
  51024. class Pimpl;
  51025. friend class Pimpl;
  51026. ImageCache();
  51027. ~ImageCache();
  51028. JUCE_DECLARE_NON_COPYABLE (ImageCache);
  51029. };
  51030. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  51031. /*** End of inlined file: juce_ImageCache.h ***/
  51032. #endif
  51033. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  51034. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  51035. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  51036. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  51037. /**
  51038. Represents a filter kernel to use in convoluting an image.
  51039. @see Image::applyConvolution
  51040. */
  51041. class JUCE_API ImageConvolutionKernel
  51042. {
  51043. public:
  51044. /** Creates an empty convulution kernel.
  51045. @param size the length of each dimension of the kernel, so e.g. if the size
  51046. is 5, it will create a 5x5 kernel
  51047. */
  51048. ImageConvolutionKernel (int size);
  51049. /** Destructor. */
  51050. ~ImageConvolutionKernel();
  51051. /** Resets all values in the kernel to zero. */
  51052. void clear();
  51053. /** Returns one of the kernel values. */
  51054. float getKernelValue (int x, int y) const noexcept;
  51055. /** Sets the value of a specific cell in the kernel.
  51056. The x and y parameters must be in the range 0 < x < getKernelSize().
  51057. @see setOverallSum
  51058. */
  51059. void setKernelValue (int x, int y, float value) noexcept;
  51060. /** Rescales all values in the kernel to make the total add up to a fixed value.
  51061. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  51062. */
  51063. void setOverallSum (float desiredTotalSum);
  51064. /** Multiplies all values in the kernel by a value. */
  51065. void rescaleAllValues (float multiplier);
  51066. /** Intialises the kernel for a gaussian blur.
  51067. @param blurRadius this may be larger or smaller than the kernel's actual
  51068. size but this will obviously be wasteful or clip at the
  51069. edges. Ideally the kernel should be just larger than
  51070. (blurRadius * 2).
  51071. */
  51072. void createGaussianBlur (float blurRadius);
  51073. /** Returns the size of the kernel.
  51074. E.g. if it's a 3x3 kernel, this returns 3.
  51075. */
  51076. int getKernelSize() const { return size; }
  51077. /** Applies the kernel to an image.
  51078. @param destImage the image that will receive the resultant convoluted pixels.
  51079. @param sourceImage the source image to read from - this can be the same image as
  51080. the destination, but if different, it must be exactly the same
  51081. size and format.
  51082. @param destinationArea the region of the image to apply the filter to
  51083. */
  51084. void applyToImage (Image& destImage,
  51085. const Image& sourceImage,
  51086. const Rectangle<int>& destinationArea) const;
  51087. private:
  51088. HeapBlock <float> values;
  51089. const int size;
  51090. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageConvolutionKernel);
  51091. };
  51092. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  51093. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  51094. #endif
  51095. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  51096. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  51097. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  51098. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  51099. /**
  51100. Base-class for codecs that can read and write image file formats such
  51101. as PNG, JPEG, etc.
  51102. This class also contains static methods to make it easy to load images
  51103. from files, streams or from memory.
  51104. @see Image, ImageCache
  51105. */
  51106. class JUCE_API ImageFileFormat
  51107. {
  51108. protected:
  51109. /** Creates an ImageFormat. */
  51110. ImageFileFormat() {}
  51111. public:
  51112. /** Destructor. */
  51113. virtual ~ImageFileFormat() {}
  51114. /** Returns a description of this file format.
  51115. E.g. "JPEG", "PNG"
  51116. */
  51117. virtual const String getFormatName() = 0;
  51118. /** Returns true if the given stream seems to contain data that this format
  51119. understands.
  51120. The format class should only read the first few bytes of the stream and sniff
  51121. for header bytes that it understands.
  51122. @see decodeImage
  51123. */
  51124. virtual bool canUnderstand (InputStream& input) = 0;
  51125. /** Tries to decode and return an image from the given stream.
  51126. This will be called for an image format after calling its canUnderStand() method
  51127. to see if it can handle the stream.
  51128. @param input the stream to read the data from. The stream will be positioned
  51129. at the start of the image data (but this may not necessarily
  51130. be position 0)
  51131. @returns the image that was decoded, or an invalid image if it fails.
  51132. @see loadFrom
  51133. */
  51134. virtual const Image decodeImage (InputStream& input) = 0;
  51135. /** Attempts to write an image to a stream.
  51136. To specify extra information like encoding quality, there will be appropriate parameters
  51137. in the subclasses of the specific file types.
  51138. @returns true if it nothing went wrong.
  51139. */
  51140. virtual bool writeImageToStream (const Image& sourceImage,
  51141. OutputStream& destStream) = 0;
  51142. /** Tries the built-in decoders to see if it can find one to read this stream.
  51143. There are currently built-in decoders for PNG, JPEG and GIF formats.
  51144. The object that is returned should not be deleted by the caller.
  51145. @see canUnderstand, decodeImage, loadFrom
  51146. */
  51147. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  51148. /** Tries to load an image from a stream.
  51149. This will use the findImageFormatForStream() method to locate a suitable
  51150. codec, and use that to load the image.
  51151. @returns the image that was decoded, or an invalid image if it fails.
  51152. */
  51153. static const Image loadFrom (InputStream& input);
  51154. /** Tries to load an image from a file.
  51155. This will use the findImageFormatForStream() method to locate a suitable
  51156. codec, and use that to load the image.
  51157. @returns the image that was decoded, or an invalid image if it fails.
  51158. */
  51159. static const Image loadFrom (const File& file);
  51160. /** Tries to load an image from a block of raw image data.
  51161. This will use the findImageFormatForStream() method to locate a suitable
  51162. codec, and use that to load the image.
  51163. @returns the image that was decoded, or an invalid image if it fails.
  51164. */
  51165. static const Image loadFrom (const void* rawData,
  51166. const int numBytesOfData);
  51167. };
  51168. /**
  51169. A subclass of ImageFileFormat for reading and writing PNG files.
  51170. @see ImageFileFormat, JPEGImageFormat
  51171. */
  51172. class JUCE_API PNGImageFormat : public ImageFileFormat
  51173. {
  51174. public:
  51175. PNGImageFormat();
  51176. ~PNGImageFormat();
  51177. const String getFormatName();
  51178. bool canUnderstand (InputStream& input);
  51179. const Image decodeImage (InputStream& input);
  51180. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  51181. };
  51182. /**
  51183. A subclass of ImageFileFormat for reading and writing JPEG files.
  51184. @see ImageFileFormat, PNGImageFormat
  51185. */
  51186. class JUCE_API JPEGImageFormat : public ImageFileFormat
  51187. {
  51188. public:
  51189. JPEGImageFormat();
  51190. ~JPEGImageFormat();
  51191. /** Specifies the quality to be used when writing a JPEG file.
  51192. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  51193. any negative value is "default" quality
  51194. */
  51195. void setQuality (float newQuality);
  51196. const String getFormatName();
  51197. bool canUnderstand (InputStream& input);
  51198. const Image decodeImage (InputStream& input);
  51199. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  51200. private:
  51201. float quality;
  51202. };
  51203. /**
  51204. A subclass of ImageFileFormat for reading GIF files.
  51205. @see ImageFileFormat, PNGImageFormat, JPEGImageFormat
  51206. */
  51207. class JUCE_API GIFImageFormat : public ImageFileFormat
  51208. {
  51209. public:
  51210. GIFImageFormat();
  51211. ~GIFImageFormat();
  51212. const String getFormatName();
  51213. bool canUnderstand (InputStream& input);
  51214. const Image decodeImage (InputStream& input);
  51215. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  51216. };
  51217. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  51218. /*** End of inlined file: juce_ImageFileFormat.h ***/
  51219. #endif
  51220. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  51221. #endif
  51222. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  51223. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  51224. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  51225. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  51226. /**
  51227. A class to take care of the logic involved with the loading/saving of some kind
  51228. of document.
  51229. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  51230. functions you need for documents that get saved to a file, so this class attempts
  51231. to abstract most of the boring stuff.
  51232. Your subclass should just implement all the pure virtual methods, and you can
  51233. then use the higher-level public methods to do the load/save dialogs, to warn the user
  51234. about overwriting files, etc.
  51235. The document object keeps track of whether it has changed since it was last saved or
  51236. loaded, so when you change something, call its changed() method. This will set a
  51237. flag so it knows it needs saving, and will also broadcast a change message using the
  51238. ChangeBroadcaster base class.
  51239. @see ChangeBroadcaster
  51240. */
  51241. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  51242. {
  51243. public:
  51244. /** Creates a FileBasedDocument.
  51245. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  51246. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  51247. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  51248. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  51249. */
  51250. FileBasedDocument (const String& fileExtension,
  51251. const String& fileWildCard,
  51252. const String& openFileDialogTitle,
  51253. const String& saveFileDialogTitle);
  51254. /** Destructor. */
  51255. virtual ~FileBasedDocument();
  51256. /** Returns true if the changed() method has been called since the file was
  51257. last saved or loaded.
  51258. @see resetChangedFlag, changed
  51259. */
  51260. bool hasChangedSinceSaved() const { return changedSinceSave; }
  51261. /** Called to indicate that the document has changed and needs saving.
  51262. This method will also trigger a change message to be sent out using the
  51263. ChangeBroadcaster base class.
  51264. After calling the method, the hasChangedSinceSaved() method will return true, until
  51265. it is reset either by saving to a file or using the resetChangedFlag() method.
  51266. @see hasChangedSinceSaved, resetChangedFlag
  51267. */
  51268. virtual void changed();
  51269. /** Sets the state of the 'changed' flag.
  51270. The 'changed' flag is set to true when the changed() method is called - use this method
  51271. to reset it or to set it without also broadcasting a change message.
  51272. @see changed, hasChangedSinceSaved
  51273. */
  51274. void setChangedFlag (bool hasChanged);
  51275. /** Tries to open a file.
  51276. If the file opens correctly, the document's file (see the getFile() method) is set
  51277. to this new one; if it fails, the document's file is left unchanged, and optionally
  51278. a message box is shown telling the user there was an error.
  51279. @returns true if the new file loaded successfully
  51280. @see loadDocument, loadFromUserSpecifiedFile
  51281. */
  51282. bool loadFrom (const File& fileToLoadFrom,
  51283. bool showMessageOnFailure);
  51284. /** Asks the user for a file and tries to load it.
  51285. This will pop up a dialog box using the title, file extension and
  51286. wildcard specified in the document's constructor, and asks the user
  51287. for a file. If they pick one, the loadFrom() method is used to
  51288. try to load it, optionally showing a message if it fails.
  51289. @returns true if a file was loaded; false if the user cancelled or if they
  51290. picked a file which failed to load correctly
  51291. @see loadFrom
  51292. */
  51293. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  51294. /** A set of possible outcomes of one of the save() methods
  51295. */
  51296. enum SaveResult
  51297. {
  51298. savedOk = 0, /**< indicates that a file was saved successfully. */
  51299. userCancelledSave, /**< indicates that the user aborted the save operation. */
  51300. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  51301. };
  51302. /** Tries to save the document to the last file it was saved or loaded from.
  51303. This will always try to write to the file, even if the document isn't flagged as
  51304. having changed.
  51305. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  51306. true, it will prompt the user to pick a file, as if
  51307. saveAsInteractive() was called.
  51308. @param showMessageOnFailure if true it will show a warning message when if the
  51309. save operation fails
  51310. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  51311. */
  51312. SaveResult save (bool askUserForFileIfNotSpecified,
  51313. bool showMessageOnFailure);
  51314. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  51315. it if they say yes.
  51316. If you've got a document open and want to close it (e.g. to quit the app), this is the
  51317. method to call.
  51318. If the document doesn't need saving it'll return the value savedOk so
  51319. you can go ahead and delete the document.
  51320. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  51321. return savedOk, so again, you can safely delete the document.
  51322. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  51323. close-document operation.
  51324. And if they click "save changes", it'll try to save and either return savedOk, or
  51325. failedToWriteToFile if there was a problem.
  51326. @see save, saveAs, saveAsInteractive
  51327. */
  51328. SaveResult saveIfNeededAndUserAgrees();
  51329. /** Tries to save the document to a specified file.
  51330. If this succeeds, it'll also change the document's internal file (as returned by
  51331. the getFile() method). If it fails, the file will be left unchanged.
  51332. @param newFile the file to try to write to
  51333. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  51334. the user first if they want to overwrite it
  51335. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  51336. use the saveAsInteractive() method to ask the user for a
  51337. filename
  51338. @param showMessageOnFailure if true and the write operation fails, it'll show
  51339. a message box to warn the user
  51340. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  51341. */
  51342. SaveResult saveAs (const File& newFile,
  51343. bool warnAboutOverwritingExistingFiles,
  51344. bool askUserForFileIfNotSpecified,
  51345. bool showMessageOnFailure);
  51346. /** Prompts the user for a filename and tries to save to it.
  51347. This will pop up a dialog box using the title, file extension and
  51348. wildcard specified in the document's constructor, and asks the user
  51349. for a file. If they pick one, the saveAs() method is used to try to save
  51350. to this file.
  51351. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  51352. the user first if they want to overwrite it
  51353. @see saveIfNeededAndUserAgrees, save, saveAs
  51354. */
  51355. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  51356. /** Returns the file that this document was last successfully saved or loaded from.
  51357. When the document object is created, this will be set to File::nonexistent.
  51358. It is changed when one of the load or save methods is used, or when setFile()
  51359. is used to explicitly set it.
  51360. */
  51361. const File getFile() const { return documentFile; }
  51362. /** Sets the file that this document thinks it was loaded from.
  51363. This won't actually load anything - it just changes the file stored internally.
  51364. @see getFile
  51365. */
  51366. void setFile (const File& newFile);
  51367. protected:
  51368. /** Overload this to return the title of the document.
  51369. This is used in message boxes, filenames and file choosers, so it should be
  51370. something sensible.
  51371. */
  51372. virtual const String getDocumentTitle() = 0;
  51373. /** This method should try to load your document from the given file.
  51374. If it fails, it should return an error message. If it succeeds, it should return
  51375. an empty string.
  51376. */
  51377. virtual const String loadDocument (const File& file) = 0;
  51378. /** This method should try to write your document to the given file.
  51379. If it fails, it should return an error message. If it succeeds, it should return
  51380. an empty string.
  51381. */
  51382. virtual const String saveDocument (const File& file) = 0;
  51383. /** This is used for dialog boxes to make them open at the last folder you
  51384. were using.
  51385. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  51386. the last document that was used - you might want to store this value
  51387. in a static variable, or even in your application's properties. It should
  51388. be a global setting rather than a property of this object.
  51389. This method works very well in conjunction with a RecentlyOpenedFilesList
  51390. object to manage your recent-files list.
  51391. As a default value, it's ok to return File::nonexistent, and the document
  51392. object will use a sensible one instead.
  51393. @see RecentlyOpenedFilesList
  51394. */
  51395. virtual const File getLastDocumentOpened() = 0;
  51396. /** This is used for dialog boxes to make them open at the last folder you
  51397. were using.
  51398. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  51399. the last document that was used - you might want to store this value
  51400. in a static variable, or even in your application's properties. It should
  51401. be a global setting rather than a property of this object.
  51402. This method works very well in conjunction with a RecentlyOpenedFilesList
  51403. object to manage your recent-files list.
  51404. @see RecentlyOpenedFilesList
  51405. */
  51406. virtual void setLastDocumentOpened (const File& file) = 0;
  51407. private:
  51408. File documentFile;
  51409. bool changedSinceSave;
  51410. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  51411. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBasedDocument);
  51412. };
  51413. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  51414. /*** End of inlined file: juce_FileBasedDocument.h ***/
  51415. #endif
  51416. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  51417. #endif
  51418. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  51419. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  51420. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  51421. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  51422. /**
  51423. Manages a set of files for use as a list of recently-opened documents.
  51424. This is a handy class for holding your list of recently-opened documents, with
  51425. helpful methods for things like purging any non-existent files, automatically
  51426. adding them to a menu, and making persistence easy.
  51427. @see File, FileBasedDocument
  51428. */
  51429. class JUCE_API RecentlyOpenedFilesList
  51430. {
  51431. public:
  51432. /** Creates an empty list.
  51433. */
  51434. RecentlyOpenedFilesList();
  51435. /** Destructor. */
  51436. ~RecentlyOpenedFilesList();
  51437. /** Sets a limit for the number of files that will be stored in the list.
  51438. When addFile() is called, then if there is no more space in the list, the
  51439. least-recently added file will be dropped.
  51440. @see getMaxNumberOfItems
  51441. */
  51442. void setMaxNumberOfItems (int newMaxNumber);
  51443. /** Returns the number of items that this list will store.
  51444. @see setMaxNumberOfItems
  51445. */
  51446. int getMaxNumberOfItems() const noexcept { return maxNumberOfItems; }
  51447. /** Returns the number of files in the list.
  51448. The most recently added file is always at index 0.
  51449. */
  51450. int getNumFiles() const;
  51451. /** Returns one of the files in the list.
  51452. The most recently added file is always at index 0.
  51453. */
  51454. const File getFile (int index) const;
  51455. /** Returns an array of all the absolute pathnames in the list.
  51456. */
  51457. const StringArray& getAllFilenames() const noexcept { return files; }
  51458. /** Clears all the files from the list. */
  51459. void clear();
  51460. /** Adds a file to the list.
  51461. The file will be added at index 0. If this file is already in the list, it will
  51462. be moved up to index 0, but a file can only appear once in the list.
  51463. If the list already contains the maximum number of items that is permitted, the
  51464. least-recently added file will be dropped from the end.
  51465. */
  51466. void addFile (const File& file);
  51467. /** Removes a file from the list. */
  51468. void removeFile (const File& file);
  51469. /** Checks each of the files in the list, removing any that don't exist.
  51470. You might want to call this after reloading a list of files, or before putting them
  51471. on a menu.
  51472. */
  51473. void removeNonExistentFiles();
  51474. /** Adds entries to a menu, representing each of the files in the list.
  51475. This is handy for creating an "open recent file..." menu in your app. The
  51476. menu items are numbered consecutively starting with the baseItemId value,
  51477. and can either be added as complete pathnames, or just the last part of the
  51478. filename.
  51479. If dontAddNonExistentFiles is true, then each file will be checked and only those
  51480. that exist will be added.
  51481. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  51482. pointers to file objects. Any files that appear in this list will not be added to the
  51483. menu - the reason for this is that you might have a number of files already open, so
  51484. might not want these to be shown in the menu.
  51485. It returns the number of items that were added.
  51486. */
  51487. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  51488. int baseItemId,
  51489. bool showFullPaths,
  51490. bool dontAddNonExistentFiles,
  51491. const File** filesToAvoid = nullptr);
  51492. /** Returns a string that encapsulates all the files in the list.
  51493. The string that is returned can later be passed into restoreFromString() in
  51494. order to recreate the list. This is handy for persisting your list, e.g. in
  51495. a PropertiesFile object.
  51496. @see restoreFromString
  51497. */
  51498. const String toString() const;
  51499. /** Restores the list from a previously stringified version of the list.
  51500. Pass in a stringified version created with toString() in order to persist/restore
  51501. your list.
  51502. @see toString
  51503. */
  51504. void restoreFromString (const String& stringifiedVersion);
  51505. private:
  51506. StringArray files;
  51507. int maxNumberOfItems;
  51508. JUCE_LEAK_DETECTOR (RecentlyOpenedFilesList);
  51509. };
  51510. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  51511. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  51512. #endif
  51513. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  51514. #endif
  51515. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  51516. /*** Start of inlined file: juce_SystemClipboard.h ***/
  51517. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  51518. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  51519. /**
  51520. Handles reading/writing to the system's clipboard.
  51521. */
  51522. class JUCE_API SystemClipboard
  51523. {
  51524. public:
  51525. /** Copies a string of text onto the clipboard */
  51526. static void copyTextToClipboard (const String& text);
  51527. /** Gets the current clipboard's contents.
  51528. Obviously this might have come from another app, so could contain
  51529. anything..
  51530. */
  51531. static const String getTextFromClipboard();
  51532. };
  51533. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  51534. /*** End of inlined file: juce_SystemClipboard.h ***/
  51535. #endif
  51536. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  51537. #endif
  51538. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  51539. #endif
  51540. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  51541. /*** Start of inlined file: juce_UnitTest.h ***/
  51542. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  51543. #define __JUCE_UNITTEST_JUCEHEADER__
  51544. class UnitTestRunner;
  51545. /**
  51546. This is a base class for classes that perform a unit test.
  51547. To write a test using this class, your code should look something like this:
  51548. @code
  51549. class MyTest : public UnitTest
  51550. {
  51551. public:
  51552. MyTest() : UnitTest ("Foobar testing") {}
  51553. void runTest()
  51554. {
  51555. beginTest ("Part 1");
  51556. expect (myFoobar.doesSomething());
  51557. expect (myFoobar.doesSomethingElse());
  51558. beginTest ("Part 2");
  51559. expect (myOtherFoobar.doesSomething());
  51560. expect (myOtherFoobar.doesSomethingElse());
  51561. ...etc..
  51562. }
  51563. };
  51564. // Creating a static instance will automatically add the instance to the array
  51565. // returned by UnitTest::getAllTests(), so the test will be included when you call
  51566. // UnitTestRunner::runAllTests()
  51567. static MyTest test;
  51568. @endcode
  51569. To run a test, use the UnitTestRunner class.
  51570. @see UnitTestRunner
  51571. */
  51572. class JUCE_API UnitTest
  51573. {
  51574. public:
  51575. /** Creates a test with the given name. */
  51576. explicit UnitTest (const String& name);
  51577. /** Destructor. */
  51578. virtual ~UnitTest();
  51579. /** Returns the name of the test. */
  51580. const String getName() const noexcept { return name; }
  51581. /** Runs the test, using the specified UnitTestRunner.
  51582. You shouldn't need to call this method directly - use
  51583. UnitTestRunner::runTests() instead.
  51584. */
  51585. void performTest (UnitTestRunner* runner);
  51586. /** Returns the set of all UnitTest objects that currently exist. */
  51587. static Array<UnitTest*>& getAllTests();
  51588. /** You can optionally implement this method to set up your test.
  51589. This method will be called before runTest().
  51590. */
  51591. virtual void initialise();
  51592. /** You can optionally implement this method to clear up after your test has been run.
  51593. This method will be called after runTest() has returned.
  51594. */
  51595. virtual void shutdown();
  51596. /** Implement this method in your subclass to actually run your tests.
  51597. The content of your implementation should call beginTest() and expect()
  51598. to perform the tests.
  51599. */
  51600. virtual void runTest() = 0;
  51601. /** Tells the system that a new subsection of tests is beginning.
  51602. This should be called from your runTest() method, and may be called
  51603. as many times as you like, to demarcate different sets of tests.
  51604. */
  51605. void beginTest (const String& testName);
  51606. /** Checks that the result of a test is true, and logs this result.
  51607. In your runTest() method, you should call this method for each condition that
  51608. you want to check, e.g.
  51609. @code
  51610. void runTest()
  51611. {
  51612. beginTest ("basic tests");
  51613. expect (x + y == 2);
  51614. expect (getThing() == someThing);
  51615. ...etc...
  51616. }
  51617. @endcode
  51618. If testResult is true, a pass is logged; if it's false, a failure is logged.
  51619. If the failure message is specified, it will be written to the log if the test fails.
  51620. */
  51621. void expect (bool testResult, const String& failureMessage = String::empty);
  51622. /** Compares two values, and if they don't match, prints out a message containing the
  51623. expected and actual result values.
  51624. */
  51625. template <class ValueType>
  51626. void expectEquals (ValueType actual, ValueType expected, String failureMessage = String::empty)
  51627. {
  51628. const bool result = (actual == expected);
  51629. if (! result)
  51630. {
  51631. if (failureMessage.isNotEmpty())
  51632. failureMessage << " -- ";
  51633. failureMessage << "Expected value: " << expected << ", Actual value: " << actual;
  51634. }
  51635. expect (result, failureMessage);
  51636. }
  51637. /** Writes a message to the test log.
  51638. This can only be called from within your runTest() method.
  51639. */
  51640. void logMessage (const String& message);
  51641. private:
  51642. const String name;
  51643. UnitTestRunner* runner;
  51644. JUCE_DECLARE_NON_COPYABLE (UnitTest);
  51645. };
  51646. /**
  51647. Runs a set of unit tests.
  51648. You can instantiate one of these objects and use it to invoke tests on a set of
  51649. UnitTest objects.
  51650. By using a subclass of UnitTestRunner, you can intercept logging messages and
  51651. perform custom behaviour when each test completes.
  51652. @see UnitTest
  51653. */
  51654. class JUCE_API UnitTestRunner
  51655. {
  51656. public:
  51657. /** */
  51658. UnitTestRunner();
  51659. /** Destructor. */
  51660. virtual ~UnitTestRunner();
  51661. /** Runs a set of tests.
  51662. The tests are performed in order, and the results are logged. To run all the
  51663. registered UnitTest objects that exist, use runAllTests().
  51664. */
  51665. void runTests (const Array<UnitTest*>& tests, bool assertOnFailure);
  51666. /** Runs all the UnitTest objects that currently exist.
  51667. This calls runTests() for all the objects listed in UnitTest::getAllTests().
  51668. */
  51669. void runAllTests (bool assertOnFailure);
  51670. /** Contains the results of a test.
  51671. One of these objects is instantiated each time UnitTest::beginTest() is called, and
  51672. it contains details of the number of subsequent UnitTest::expect() calls that are
  51673. made.
  51674. */
  51675. struct TestResult
  51676. {
  51677. /** The main name of this test (i.e. the name of the UnitTest object being run). */
  51678. String unitTestName;
  51679. /** The name of the current subcategory (i.e. the name that was set when UnitTest::beginTest() was called). */
  51680. String subcategoryName;
  51681. /** The number of UnitTest::expect() calls that succeeded. */
  51682. int passes;
  51683. /** The number of UnitTest::expect() calls that failed. */
  51684. int failures;
  51685. /** A list of messages describing the failed tests. */
  51686. StringArray messages;
  51687. };
  51688. /** Returns the number of TestResult objects that have been performed.
  51689. @see getResult
  51690. */
  51691. int getNumResults() const noexcept;
  51692. /** Returns one of the TestResult objects that describes a test that has been run.
  51693. @see getNumResults
  51694. */
  51695. const TestResult* getResult (int index) const noexcept;
  51696. protected:
  51697. /** Called when the list of results changes.
  51698. You can override this to perform some sort of behaviour when results are added.
  51699. */
  51700. virtual void resultsUpdated();
  51701. /** Logs a message about the current test progress.
  51702. By default this just writes the message to the Logger class, but you could override
  51703. this to do something else with the data.
  51704. */
  51705. virtual void logMessage (const String& message);
  51706. private:
  51707. friend class UnitTest;
  51708. UnitTest* currentTest;
  51709. String currentSubCategory;
  51710. OwnedArray <TestResult, CriticalSection> results;
  51711. bool assertOnFailure;
  51712. void beginNewTest (UnitTest* test, const String& subCategory);
  51713. void endTest();
  51714. void addPass();
  51715. void addFail (const String& failureMessage);
  51716. JUCE_DECLARE_NON_COPYABLE (UnitTestRunner);
  51717. };
  51718. #endif // __JUCE_UNITTEST_JUCEHEADER__
  51719. /*** End of inlined file: juce_UnitTest.h ***/
  51720. #endif
  51721. #endif
  51722. /*** End of inlined file: juce_app_includes.h ***/
  51723. #endif
  51724. #if JUCE_MSVC
  51725. #pragma warning (pop)
  51726. #pragma pack (pop)
  51727. #endif
  51728. END_JUCE_NAMESPACE
  51729. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  51730. #ifdef JUCE_NAMESPACE
  51731. // this will obviously save a lot of typing, but can be disabled by
  51732. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  51733. using namespace JUCE_NAMESPACE;
  51734. /* On the Mac, these symbols are defined in the Mac libraries, so
  51735. these macros make it easier to reference them without writing out
  51736. the namespace every time.
  51737. If you run into difficulties where these macros interfere with the contents
  51738. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  51739. the comments in that file for more information.
  51740. */
  51741. #if (JUCE_MAC || JUCE_IOS) && ! JUCE_DONT_DEFINE_MACROS
  51742. #define Component JUCE_NAMESPACE::Component
  51743. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  51744. #define Point JUCE_NAMESPACE::Point
  51745. #define Button JUCE_NAMESPACE::Button
  51746. #endif
  51747. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  51748. it easier to use the juce version explicitly.
  51749. If you run into difficulties where this macro interferes with other 3rd party header
  51750. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  51751. file for more information.
  51752. */
  51753. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  51754. #define Rectangle JUCE_NAMESPACE::Rectangle
  51755. #endif
  51756. #endif
  51757. #endif
  51758. /* Easy autolinking to the right JUCE libraries under win32.
  51759. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  51760. including this header file.
  51761. */
  51762. #if JUCE_MSVC
  51763. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  51764. /** If you want your application to link to Juce as a DLL instead of
  51765. a static library (on win32), just define the JUCE_DLL macro before
  51766. including juce.h
  51767. */
  51768. #ifdef JUCE_DLL
  51769. #if JUCE_DEBUG
  51770. #define AUTOLINKEDLIB "JUCE_debug.lib"
  51771. #else
  51772. #define AUTOLINKEDLIB "JUCE.lib"
  51773. #endif
  51774. #else
  51775. #if JUCE_DEBUG
  51776. #ifdef _WIN64
  51777. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  51778. #else
  51779. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  51780. #endif
  51781. #else
  51782. #ifdef _WIN64
  51783. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  51784. #else
  51785. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  51786. #endif
  51787. #endif
  51788. #endif
  51789. #pragma comment(lib, AUTOLINKEDLIB)
  51790. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  51791. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  51792. #endif
  51793. // Auto-link the other win32 libs that are needed by library calls..
  51794. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  51795. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  51796. // Auto-links to various win32 libs that are needed by library calls..
  51797. #pragma comment(lib, "kernel32.lib")
  51798. #pragma comment(lib, "user32.lib")
  51799. #pragma comment(lib, "shell32.lib")
  51800. #pragma comment(lib, "gdi32.lib")
  51801. #pragma comment(lib, "vfw32.lib")
  51802. #pragma comment(lib, "comdlg32.lib")
  51803. #pragma comment(lib, "winmm.lib")
  51804. #pragma comment(lib, "wininet.lib")
  51805. #pragma comment(lib, "ole32.lib")
  51806. #pragma comment(lib, "oleaut32.lib")
  51807. #pragma comment(lib, "advapi32.lib")
  51808. #pragma comment(lib, "ws2_32.lib")
  51809. #pragma comment(lib, "version.lib")
  51810. #pragma comment(lib, "shlwapi.lib")
  51811. #pragma comment(lib, "imm32.lib")
  51812. #ifdef _NATIVE_WCHAR_T_DEFINED
  51813. #ifdef _DEBUG
  51814. #pragma comment(lib, "comsuppwd.lib")
  51815. #else
  51816. #pragma comment(lib, "comsuppw.lib")
  51817. #endif
  51818. #else
  51819. #ifdef _DEBUG
  51820. #pragma comment(lib, "comsuppd.lib")
  51821. #else
  51822. #pragma comment(lib, "comsupp.lib")
  51823. #endif
  51824. #endif
  51825. #if JUCE_OPENGL
  51826. #pragma comment(lib, "OpenGL32.Lib")
  51827. #pragma comment(lib, "GlU32.Lib")
  51828. #endif
  51829. #if JUCE_QUICKTIME
  51830. #pragma comment (lib, "QTMLClient.lib")
  51831. #endif
  51832. #if JUCE_USE_CAMERA
  51833. #pragma comment (lib, "Strmiids.lib")
  51834. #pragma comment (lib, "wmvcore.lib")
  51835. #endif
  51836. #if JUCE_DIRECT2D
  51837. #pragma comment (lib, "Dwrite.lib")
  51838. #pragma comment (lib, "D2d1.lib")
  51839. #endif
  51840. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  51841. #endif
  51842. #endif
  51843. #endif
  51844. #endif // __JUCE_JUCEHEADER__
  51845. /*** End of inlined file: juce.h ***/
  51846. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__