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.

69845 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 107
  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_DIRECTSHOW: Enables DirectShow media-streaming architecture (MS Windows only).
  233. */
  234. #ifndef JUCE_DIRECTSHOW
  235. #define JUCE_DIRECTSHOW 0
  236. #endif
  237. /** JUCE_MEDIAFOUNDATION: Enables Media Foundation multimedia platform (Windows Vista and above).
  238. */
  239. #ifndef JUCE_MEDIAFOUNDATION
  240. #define JUCE_MEDIAFOUNDATION 0
  241. #endif
  242. #if ! JUCE_WINDOWS
  243. #undef JUCE_DIRECTSHOW
  244. #undef JUCE_MEDIAFOUNDATION
  245. #endif
  246. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  247. #ifndef JUCE_ALSA
  248. #define JUCE_ALSA 1
  249. #endif
  250. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  251. #ifndef JUCE_JACK
  252. #define JUCE_JACK 0
  253. #endif
  254. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  255. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  256. installed, and its header files will need to be on your include path.
  257. */
  258. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || JUCE_ANDROID || (JUCE_WINDOWS && ! JUCE_MSVC))
  259. #define JUCE_QUICKTIME 0
  260. #endif
  261. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  262. #undef JUCE_QUICKTIME
  263. #endif
  264. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  265. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  266. */
  267. #if ! (defined (JUCE_OPENGL) || JUCE_ANDROID)
  268. #define JUCE_OPENGL 1
  269. #endif
  270. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  271. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  272. */
  273. #ifndef JUCE_DIRECT2D
  274. #define JUCE_DIRECT2D 0
  275. #endif
  276. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  277. If your app doesn't need to read FLAC files, you might want to disable this to
  278. reduce the size of your codebase and build time.
  279. */
  280. #ifndef JUCE_USE_FLAC
  281. #define JUCE_USE_FLAC 1
  282. #endif
  283. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  284. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  285. reduce the size of your codebase and build time.
  286. */
  287. #ifndef JUCE_USE_OGGVORBIS
  288. #define JUCE_USE_OGGVORBIS 1
  289. #endif
  290. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  291. Unless you're using CD-burning, you should probably turn this flag off to
  292. reduce code size.
  293. */
  294. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  295. #define JUCE_USE_CDBURNER 1
  296. #endif
  297. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  298. Unless you're using CD-reading, you should probably turn this flag off to
  299. reduce code size.
  300. */
  301. #ifndef JUCE_USE_CDREADER
  302. #define JUCE_USE_CDREADER 1
  303. #endif
  304. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  305. */
  306. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  307. #define JUCE_USE_CAMERA 0
  308. #endif
  309. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  310. gets repainted will flash in a random colour, so that you can check exactly how much and how
  311. often your components are being drawn.
  312. */
  313. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  314. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  315. #endif
  316. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  317. Unless you specifically want to disable this, it's best to leave this option turned on.
  318. */
  319. #ifndef JUCE_USE_XINERAMA
  320. #define JUCE_USE_XINERAMA 1
  321. #endif
  322. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  323. turned on unless you have a good reason to disable it.
  324. */
  325. #ifndef JUCE_USE_XSHM
  326. #define JUCE_USE_XSHM 1
  327. #endif
  328. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  329. */
  330. #ifndef JUCE_USE_XRENDER
  331. #define JUCE_USE_XRENDER 0
  332. #endif
  333. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  334. unless you have a good reason to disable it.
  335. */
  336. #ifndef JUCE_USE_XCURSOR
  337. #define JUCE_USE_XCURSOR 1
  338. #endif
  339. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  340. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  341. you're building a plugin hosting app.
  342. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  343. */
  344. #ifndef JUCE_PLUGINHOST_VST
  345. #define JUCE_PLUGINHOST_VST 0
  346. #endif
  347. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  348. of course, and should only be enabled if you're building a plugin hosting app.
  349. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  350. */
  351. #ifndef JUCE_PLUGINHOST_AU
  352. #define JUCE_PLUGINHOST_AU 0
  353. #endif
  354. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  355. This should be enabled if you're writing a console application.
  356. */
  357. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  358. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  359. #endif
  360. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  361. If you're not using any embedded web-pages, turning this off may reduce your code size.
  362. */
  363. #ifndef JUCE_WEB_BROWSER
  364. #define JUCE_WEB_BROWSER 1
  365. #endif
  366. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  367. Carbon isn't required for a normal app, but may be needed by specialised classes like
  368. plugin-hosts, which support older APIs.
  369. */
  370. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  371. #define JUCE_SUPPORT_CARBON 1
  372. #endif
  373. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  374. You might need to tweak this if you're linking to an external zlib library in your app,
  375. but for normal apps, this option should be left alone.
  376. */
  377. #ifndef JUCE_INCLUDE_ZLIB_CODE
  378. #define JUCE_INCLUDE_ZLIB_CODE 1
  379. #endif
  380. #ifndef JUCE_INCLUDE_FLAC_CODE
  381. #define JUCE_INCLUDE_FLAC_CODE 1
  382. #endif
  383. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  384. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  385. #endif
  386. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  387. #define JUCE_INCLUDE_PNGLIB_CODE 1
  388. #endif
  389. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  390. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  391. #endif
  392. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check for certain objects when
  393. the app terminates. See the LeakedObjectDetector class and the JUCE_LEAK_DETECTOR
  394. macro for more details about enabling leak checking for specific classes.
  395. */
  396. #if JUCE_DEBUG && ! defined (JUCE_CHECK_MEMORY_LEAKS)
  397. #define JUCE_CHECK_MEMORY_LEAKS 1
  398. #endif
  399. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  400. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  401. are passed to the JUCEApplication::unhandledException() callback for logging.
  402. */
  403. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  404. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  405. #endif
  406. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  407. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  408. #undef JUCE_QUICKTIME
  409. #define JUCE_QUICKTIME 0
  410. #undef JUCE_OPENGL
  411. #define JUCE_OPENGL 0
  412. #undef JUCE_USE_CDBURNER
  413. #define JUCE_USE_CDBURNER 0
  414. #undef JUCE_USE_CDREADER
  415. #define JUCE_USE_CDREADER 0
  416. #undef JUCE_WEB_BROWSER
  417. #define JUCE_WEB_BROWSER 0
  418. #undef JUCE_PLUGINHOST_AU
  419. #define JUCE_PLUGINHOST_AU 0
  420. #undef JUCE_PLUGINHOST_VST
  421. #define JUCE_PLUGINHOST_VST 0
  422. #endif
  423. #endif
  424. /*** End of inlined file: juce_Config.h ***/
  425. #ifdef JUCE_NAMESPACE
  426. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  427. #define END_JUCE_NAMESPACE }
  428. #else
  429. #define BEGIN_JUCE_NAMESPACE
  430. #define END_JUCE_NAMESPACE
  431. #endif
  432. /*** Start of inlined file: juce_PlatformDefs.h ***/
  433. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  434. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  435. /* This file defines miscellaneous macros for debugging, assertions, etc.
  436. */
  437. #ifdef JUCE_FORCE_DEBUG
  438. #undef JUCE_DEBUG
  439. #if JUCE_FORCE_DEBUG
  440. #define JUCE_DEBUG 1
  441. #endif
  442. #endif
  443. /** This macro defines the C calling convention used as the standard for Juce calls. */
  444. #if JUCE_MSVC
  445. #define JUCE_CALLTYPE __stdcall
  446. #define JUCE_CDECL __cdecl
  447. #else
  448. #define JUCE_CALLTYPE
  449. #define JUCE_CDECL
  450. #endif
  451. // Debugging and assertion macros
  452. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  453. #if JUCE_LOG_ASSERTIONS
  454. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  455. #elif JUCE_DEBUG
  456. #define juce_LogCurrentAssertion std::cerr << "JUCE Assertion failure in " << __FILE__ << ", line " << __LINE__ << std::endl;
  457. #else
  458. #define juce_LogCurrentAssertion
  459. #endif
  460. #if JUCE_MAC || DOXYGEN
  461. /** This will try to break into the debugger if the app is currently being debugged.
  462. If called by an app that's not being debugged, the behaiour isn't defined - it may crash or not, depending
  463. on the platform.
  464. @see jassert()
  465. */
  466. #define juce_breakDebugger { Debugger(); }
  467. #elif JUCE_IOS || JUCE_LINUX || JUCE_ANDROID
  468. #define juce_breakDebugger { kill (0, SIGTRAP); }
  469. #elif JUCE_USE_INTRINSICS
  470. #ifndef __INTEL_COMPILER
  471. #pragma intrinsic (__debugbreak)
  472. #endif
  473. #define juce_breakDebugger { __debugbreak(); }
  474. #elif JUCE_GCC
  475. #define juce_breakDebugger { asm("int $3"); }
  476. #else
  477. #define juce_breakDebugger { __asm int 3 }
  478. #endif
  479. #if JUCE_DEBUG || DOXYGEN
  480. /** Writes a string to the standard error stream.
  481. This is only compiled in a debug build.
  482. @see Logger::outputDebugString
  483. */
  484. #define DBG(dbgtext) { JUCE_NAMESPACE::String tempDbgBuf; tempDbgBuf << dbgtext; JUCE_NAMESPACE::Logger::outputDebugString (tempDbgBuf); }
  485. /** This will always cause an assertion failure.
  486. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled for your build).
  487. @see jassert
  488. */
  489. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  490. /** Platform-independent assertion macro.
  491. This macro gets turned into a no-op when you're building with debugging turned off, so be
  492. careful that the expression you pass to it doesn't perform any actions that are vital for the
  493. correct behaviour of your program!
  494. @see jassertfalse
  495. */
  496. #define jassert(expression) { if (! (expression)) jassertfalse; }
  497. #else
  498. // If debugging is disabled, these dummy debug and assertion macros are used..
  499. #define DBG(dbgtext)
  500. #define jassertfalse { juce_LogCurrentAssertion }
  501. #if JUCE_LOG_ASSERTIONS
  502. #define jassert(expression) { if (! (expression)) jassertfalse; }
  503. #else
  504. #define jassert(a) {}
  505. #endif
  506. #endif
  507. #ifndef DOXYGEN
  508. BEGIN_JUCE_NAMESPACE
  509. template <bool b> struct JuceStaticAssert;
  510. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  511. END_JUCE_NAMESPACE
  512. #endif
  513. /** A compile-time assertion macro.
  514. If the expression parameter is false, the macro will cause a compile error. (The actual error
  515. message that the compiler generates may be completely bizarre and seem to have no relation to
  516. the place where you put the static_assert though!)
  517. */
  518. #define static_jassert(expression) JUCE_NAMESPACE::JuceStaticAssert<expression>::dummy();
  519. /** This is a shorthand macro for declaring stubs for a class's copy constructor and operator=.
  520. For example, instead of
  521. @code
  522. class MyClass
  523. {
  524. etc..
  525. private:
  526. MyClass (const MyClass&);
  527. MyClass& operator= (const MyClass&);
  528. };@endcode
  529. ..you can just write:
  530. @code
  531. class MyClass
  532. {
  533. etc..
  534. private:
  535. JUCE_DECLARE_NON_COPYABLE (MyClass);
  536. };@endcode
  537. */
  538. #define JUCE_DECLARE_NON_COPYABLE(className) \
  539. className (const className&);\
  540. className& operator= (const className&)
  541. /** This is a shorthand way of writing both a JUCE_DECLARE_NON_COPYABLE and
  542. JUCE_LEAK_DETECTOR macro for a class.
  543. */
  544. #define JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(className) \
  545. JUCE_DECLARE_NON_COPYABLE(className);\
  546. JUCE_LEAK_DETECTOR(className)
  547. #if ! DOXYGEN
  548. #define JUCE_JOIN_MACRO_HELPER(a, b) a ## b
  549. #endif
  550. /** A good old-fashioned C macro concatenation helper.
  551. This combines two items (which may themselves be macros) into a single string,
  552. avoiding the pitfalls of the ## macro operator.
  553. */
  554. #define JUCE_JOIN_MACRO(a, b) JUCE_JOIN_MACRO_HELPER (a, b)
  555. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  556. #define JUCE_TRY try
  557. #define JUCE_CATCH_ALL catch (...) {}
  558. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse; }
  559. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  560. #define JUCE_CATCH_EXCEPTION JUCE_CATCH_ALL
  561. #else
  562. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  563. object so they can be logged by the application if it wants to.
  564. */
  565. #define JUCE_CATCH_EXCEPTION \
  566. catch (const std::exception& e) \
  567. { \
  568. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  569. } \
  570. catch (...) \
  571. { \
  572. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  573. }
  574. #endif
  575. #else
  576. #define JUCE_TRY
  577. #define JUCE_CATCH_EXCEPTION
  578. #define JUCE_CATCH_ALL
  579. #define JUCE_CATCH_ALL_ASSERT
  580. #endif
  581. #if JUCE_DEBUG || DOXYGEN
  582. /** A platform-independent way of forcing an inline function.
  583. Use the syntax: @code
  584. forcedinline void myfunction (int x)
  585. @endcode
  586. */
  587. #define forcedinline inline
  588. #else
  589. #if JUCE_MSVC
  590. #define forcedinline __forceinline
  591. #else
  592. #define forcedinline inline __attribute__((always_inline))
  593. #endif
  594. #endif
  595. #if JUCE_MSVC || DOXYGEN
  596. /** This can be placed before a stack or member variable declaration to tell the compiler
  597. to align it to the specified number of bytes. */
  598. #define JUCE_ALIGN(bytes) __declspec (align (bytes))
  599. #else
  600. #define JUCE_ALIGN(bytes) __attribute__ ((aligned (bytes)))
  601. #endif
  602. // Cross-compiler deprecation macros..
  603. #if DOXYGEN || (JUCE_MSVC && ! JUCE_NO_DEPRECATION_WARNINGS)
  604. /** This can be used to wrap a function which has been deprecated. */
  605. #define JUCE_DEPRECATED(functionDef) __declspec(deprecated) functionDef
  606. #elif JUCE_GCC && ! JUCE_NO_DEPRECATION_WARNINGS
  607. #define JUCE_DEPRECATED(functionDef) functionDef __attribute__ ((deprecated))
  608. #else
  609. #define JUCE_DEPRECATED(functionDef) functionDef
  610. #endif
  611. #if JUCE_ANDROID && ! DOXYGEN
  612. #define JUCE_MODAL_LOOPS_PERMITTED 0
  613. #else
  614. /** Some operating environments don't provide a modal loop mechanism, so this flag can be
  615. used to disable any functions that try to run a modal loop. */
  616. #define JUCE_MODAL_LOOPS_PERMITTED 1
  617. #endif
  618. // Here, we'll check for C++2011 compiler support, and if it's not available, define
  619. // a few workarounds, so that we can still use a few of the newer language features.
  620. #if defined (__GXX_EXPERIMENTAL_CXX0X__) && defined (__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
  621. #define JUCE_COMPILER_SUPPORTS_CXX2011 1
  622. #endif
  623. #if defined (__clang__) && defined (__has_feature)
  624. #if __has_feature (cxx_noexcept) // (NB: do not add this test to the previous line)
  625. #define JUCE_COMPILER_SUPPORTS_CXX2011 1
  626. #endif
  627. #endif
  628. #if defined (_MSC_VER) && _MSC_VER >= 1600
  629. //#define JUCE_COMPILER_SUPPORTS_CXX2011 1
  630. #endif
  631. #if ! (DOXYGEN || JUCE_COMPILER_SUPPORTS_CXX2011)
  632. #define noexcept throw() // for c++98 compilers, we can fake these newer language features.
  633. #define nullptr (0)
  634. #endif
  635. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  636. /*** End of inlined file: juce_PlatformDefs.h ***/
  637. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  638. #if JUCE_MSVC
  639. #if JUCE_VC6
  640. #pragma warning (disable: 4284 4786) // (spurious VC6 warnings)
  641. namespace std // VC6 doesn't have sqrt/sin/cos/tan/abs in std, so declare them here:
  642. {
  643. template <typename Type> Type abs (Type a) { if (a < 0) return -a; return a; }
  644. template <typename Type> Type tan (Type a) { return static_cast<Type> (::tan (static_cast<double> (a))); }
  645. template <typename Type> Type sin (Type a) { return static_cast<Type> (::sin (static_cast<double> (a))); }
  646. template <typename Type> Type cos (Type a) { return static_cast<Type> (::cos (static_cast<double> (a))); }
  647. template <typename Type> Type sqrt (Type a) { return static_cast<Type> (::sqrt (static_cast<double> (a))); }
  648. template <typename Type> Type floor (Type a) { return static_cast<Type> (::floor (static_cast<double> (a))); }
  649. template <typename Type> Type ceil (Type a) { return static_cast<Type> (::ceil (static_cast<double> (a))); }
  650. template <typename Type> Type atan2 (Type a, Type b) { return static_cast<Type> (::atan2 (static_cast<double> (a), static_cast<double> (b))); }
  651. }
  652. #endif
  653. #pragma warning (push)
  654. #pragma warning (disable: 4514 4245 4100)
  655. #endif
  656. #include <cstdlib>
  657. #include <cstdarg>
  658. #include <climits>
  659. #include <limits>
  660. #include <cmath>
  661. #include <cwchar>
  662. #include <stdexcept>
  663. #include <typeinfo>
  664. #include <cstring>
  665. #include <cstdio>
  666. #include <iostream>
  667. #include <vector>
  668. #if JUCE_USE_INTRINSICS
  669. #include <intrin.h>
  670. #endif
  671. #if JUCE_MAC || JUCE_IOS
  672. #include <libkern/OSAtomic.h>
  673. #endif
  674. #if JUCE_LINUX
  675. #include <signal.h>
  676. #if __INTEL_COMPILER
  677. #if __ia64__
  678. #include <ia64intrin.h>
  679. #else
  680. #include <ia32intrin.h>
  681. #endif
  682. #endif
  683. #endif
  684. #if JUCE_MSVC && JUCE_DEBUG
  685. #include <crtdbg.h>
  686. #endif
  687. #if JUCE_MSVC
  688. #include <malloc.h>
  689. #pragma warning (pop)
  690. #if ! JUCE_PUBLIC_INCLUDES
  691. #pragma warning (4: 4511 4512 4100) // (enable some warnings that are turned off in VC8)
  692. #endif
  693. #endif
  694. #if JUCE_ANDROID
  695. #include <sys/atomics.h>
  696. #include <byteswap.h>
  697. #endif
  698. // DLL building settings on Win32
  699. #if JUCE_MSVC
  700. #ifdef JUCE_DLL_BUILD
  701. #define JUCE_API __declspec (dllexport)
  702. #pragma warning (disable: 4251)
  703. #elif defined (JUCE_DLL)
  704. #define JUCE_API __declspec (dllimport)
  705. #pragma warning (disable: 4251)
  706. #endif
  707. #ifdef __INTEL_COMPILER
  708. #pragma warning (disable: 1125) // (virtual override warning)
  709. #endif
  710. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  711. #ifdef JUCE_DLL_BUILD
  712. #define JUCE_API __attribute__ ((visibility("default")))
  713. #endif
  714. #endif
  715. #ifndef JUCE_API
  716. /** This macro is added to all juce public class declarations. */
  717. #define JUCE_API
  718. #endif
  719. /** This macro is added to all juce public function declarations. */
  720. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  721. /** This turns on some non-essential bits of code that should prevent old code from compiling
  722. in cases where method signatures have changed, etc.
  723. */
  724. #if (! defined (JUCE_CATCH_DEPRECATED_CODE_MISUSE)) && JUCE_DEBUG && ! DOXYGEN
  725. #define JUCE_CATCH_DEPRECATED_CODE_MISUSE 1
  726. #endif
  727. // Now include some basics that are needed by most of the Juce classes...
  728. BEGIN_JUCE_NAMESPACE
  729. extern JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger();
  730. #if JUCE_LOG_ASSERTIONS
  731. extern JUCE_API void juce_LogAssertion (const char* filename, int lineNum) noexcept;
  732. #endif
  733. /*** Start of inlined file: juce_Memory.h ***/
  734. #ifndef __JUCE_MEMORY_JUCEHEADER__
  735. #define __JUCE_MEMORY_JUCEHEADER__
  736. #if JUCE_MSVC || DOXYGEN
  737. /** This is a compiler-independent way of declaring a variable as being thread-local.
  738. E.g.
  739. @code
  740. juce_ThreadLocal int myVariable;
  741. @endcode
  742. */
  743. #define juce_ThreadLocal __declspec(thread)
  744. #else
  745. #define juce_ThreadLocal __thread
  746. #endif
  747. #if JUCE_MINGW
  748. /** This allocator is not defined in mingw gcc. */
  749. #define alloca __builtin_alloca
  750. #endif
  751. /** Fills a block of memory with zeros. */
  752. inline void zeromem (void* memory, size_t numBytes) noexcept { memset (memory, 0, numBytes); }
  753. /** Overwrites a structure or object with zeros. */
  754. template <typename Type>
  755. inline void zerostruct (Type& structure) noexcept { memset (&structure, 0, sizeof (structure)); }
  756. /** Delete an object pointer, and sets the pointer to null.
  757. Remember that it's not good c++ practice to use delete directly - always try to use a ScopedPointer
  758. or other automatic lieftime-management system rather than resorting to deleting raw pointers!
  759. */
  760. template <typename Type>
  761. inline void deleteAndZero (Type& pointer) { delete pointer; pointer = nullptr; }
  762. /** A handy function which adds a number of bytes to any type of pointer and returns the result.
  763. This can be useful to avoid casting pointers to a char* and back when you want to move them by
  764. a specific number of bytes,
  765. */
  766. template <typename Type>
  767. inline Type* addBytesToPointer (Type* pointer, int bytes) noexcept { return (Type*) (((char*) pointer) + bytes); }
  768. /** A handy function which returns the difference between any two pointers, in bytes.
  769. The address of the second pointer is subtracted from the first, and the difference in bytes is returned.
  770. */
  771. template <typename Type1, typename Type2>
  772. inline int getAddressDifference (Type1* pointer1, Type2* pointer2) noexcept { return (int) (((const char*) pointer1) - (const char*) pointer2); }
  773. /* In a win32 DLL build, we'll expose some malloc/free functions that live inside the DLL, and use these for
  774. allocating all the objects - that way all juce objects in the DLL and in the host will live in the same heap,
  775. avoiding problems when an object is created in one module and passed across to another where it is deleted.
  776. By piggy-backing on the JUCE_LEAK_DETECTOR macro, these allocators can be injected into most juce classes.
  777. */
  778. #if JUCE_MSVC && defined (JUCE_DLL) && ! DOXYGEN
  779. extern JUCE_API void* juceDLL_malloc (size_t);
  780. extern JUCE_API void juceDLL_free (void*);
  781. #define JUCE_LEAK_DETECTOR(OwnerClass) public:\
  782. static void* operator new (size_t sz) { return JUCE_NAMESPACE::juceDLL_malloc ((int) sz); } \
  783. static void* operator new (size_t, void* p) { return p; } \
  784. static void operator delete (void* p) { JUCE_NAMESPACE::juceDLL_free (p); } \
  785. static void operator delete (void*, void*) {}
  786. #endif
  787. /** (Deprecated) This was a win32-specific way of checking for object leaks - now please
  788. use the JUCE_LEAK_DETECTOR instead.
  789. */
  790. #ifndef juce_UseDebuggingNewOperator
  791. #define juce_UseDebuggingNewOperator
  792. #endif
  793. #endif // __JUCE_MEMORY_JUCEHEADER__
  794. /*** End of inlined file: juce_Memory.h ***/
  795. /*** Start of inlined file: juce_MathsFunctions.h ***/
  796. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  797. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  798. /*
  799. This file sets up some handy mathematical typdefs and functions.
  800. */
  801. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  802. /** A platform-independent 8-bit signed integer type. */
  803. typedef signed char int8;
  804. /** A platform-independent 8-bit unsigned integer type. */
  805. typedef unsigned char uint8;
  806. /** A platform-independent 16-bit signed integer type. */
  807. typedef signed short int16;
  808. /** A platform-independent 16-bit unsigned integer type. */
  809. typedef unsigned short uint16;
  810. /** A platform-independent 32-bit signed integer type. */
  811. typedef signed int int32;
  812. /** A platform-independent 32-bit unsigned integer type. */
  813. typedef unsigned int uint32;
  814. #if JUCE_MSVC
  815. /** A platform-independent 64-bit integer type. */
  816. typedef __int64 int64;
  817. /** A platform-independent 64-bit unsigned integer type. */
  818. typedef unsigned __int64 uint64;
  819. /** A platform-independent macro for writing 64-bit literals, needed because
  820. different compilers have different syntaxes for this.
  821. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  822. GCC, or 0x1000000000 for MSVC.
  823. */
  824. #define literal64bit(longLiteral) ((__int64) longLiteral)
  825. #else
  826. /** A platform-independent 64-bit integer type. */
  827. typedef long long int64;
  828. /** A platform-independent 64-bit unsigned integer type. */
  829. typedef unsigned long long uint64;
  830. /** A platform-independent macro for writing 64-bit literals, needed because
  831. different compilers have different syntaxes for this.
  832. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  833. GCC, or 0x1000000000 for MSVC.
  834. */
  835. #define literal64bit(longLiteral) (longLiteral##LL)
  836. #endif
  837. #if JUCE_64BIT
  838. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  839. typedef int64 pointer_sized_int;
  840. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  841. typedef uint64 pointer_sized_uint;
  842. #elif JUCE_MSVC && ! JUCE_VC6
  843. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  844. typedef _W64 int pointer_sized_int;
  845. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  846. typedef _W64 unsigned int pointer_sized_uint;
  847. #else
  848. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  849. typedef int pointer_sized_int;
  850. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  851. typedef unsigned int pointer_sized_uint;
  852. #endif
  853. // Some indispensible min/max functions
  854. /** Returns the larger of two values. */
  855. template <typename Type>
  856. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  857. /** Returns the larger of three values. */
  858. template <typename Type>
  859. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  860. /** Returns the larger of four values. */
  861. template <typename Type>
  862. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  863. /** Returns the smaller of two values. */
  864. template <typename Type>
  865. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  866. /** Returns the smaller of three values. */
  867. template <typename Type>
  868. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  869. /** Returns the smaller of four values. */
  870. template <typename Type>
  871. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  872. /** Scans an array of values, returning the minimum value that it contains. */
  873. template <typename Type>
  874. const Type findMinimum (const Type* data, int numValues)
  875. {
  876. if (numValues <= 0)
  877. return Type();
  878. Type result (*data++);
  879. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  880. {
  881. const Type& v = *data++;
  882. if (v < result) result = v;
  883. }
  884. return result;
  885. }
  886. /** Scans an array of values, returning the minimum value that it contains. */
  887. template <typename Type>
  888. const Type findMaximum (const Type* values, int numValues)
  889. {
  890. if (numValues <= 0)
  891. return Type();
  892. Type result (*values++);
  893. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  894. {
  895. const Type& v = *values++;
  896. if (result > v) result = v;
  897. }
  898. return result;
  899. }
  900. /** Scans an array of values, returning the minimum and maximum values that it contains. */
  901. template <typename Type>
  902. void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
  903. {
  904. if (numValues <= 0)
  905. {
  906. lowest = Type();
  907. highest = Type();
  908. }
  909. else
  910. {
  911. Type mn (*values++);
  912. Type mx (mn);
  913. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  914. {
  915. const Type& v = *values++;
  916. if (mx < v) mx = v;
  917. if (v < mn) mn = v;
  918. }
  919. lowest = mn;
  920. highest = mx;
  921. }
  922. }
  923. /** Constrains a value to keep it within a given range.
  924. This will check that the specified value lies between the lower and upper bounds
  925. specified, and if not, will return the nearest value that would be in-range. Effectively,
  926. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  927. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  928. the results will be unpredictable.
  929. @param lowerLimit the minimum value to return
  930. @param upperLimit the maximum value to return
  931. @param valueToConstrain the value to try to return
  932. @returns the closest value to valueToConstrain which lies between lowerLimit
  933. and upperLimit (inclusive)
  934. @see jlimit0To, jmin, jmax
  935. */
  936. template <typename Type>
  937. inline Type jlimit (const Type lowerLimit,
  938. const Type upperLimit,
  939. const Type valueToConstrain) noexcept
  940. {
  941. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  942. return (valueToConstrain < lowerLimit) ? lowerLimit
  943. : ((upperLimit < valueToConstrain) ? upperLimit
  944. : valueToConstrain);
  945. }
  946. /** Returns true if a value is at least zero, and also below a specified upper limit.
  947. This is basically a quicker way to write:
  948. @code valueToTest >= 0 && valueToTest < upperLimit
  949. @endcode
  950. */
  951. template <typename Type>
  952. inline bool isPositiveAndBelow (Type valueToTest, Type upperLimit) noexcept
  953. {
  954. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  955. return Type() <= valueToTest && valueToTest < upperLimit;
  956. }
  957. #if ! JUCE_VC6
  958. template <>
  959. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) noexcept
  960. {
  961. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  962. return static_cast <unsigned int> (valueToTest) < static_cast <unsigned int> (upperLimit);
  963. }
  964. #endif
  965. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  966. This is basically a quicker way to write:
  967. @code valueToTest >= 0 && valueToTest <= upperLimit
  968. @endcode
  969. */
  970. template <typename Type>
  971. inline bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) noexcept
  972. {
  973. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  974. return Type() <= valueToTest && valueToTest <= upperLimit;
  975. }
  976. #if ! JUCE_VC6
  977. template <>
  978. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) noexcept
  979. {
  980. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  981. return static_cast <unsigned int> (valueToTest) <= static_cast <unsigned int> (upperLimit);
  982. }
  983. #endif
  984. /** Handy function to swap two values. */
  985. template <typename Type>
  986. inline void swapVariables (Type& variable1, Type& variable2)
  987. {
  988. std::swap (variable1, variable2);
  989. }
  990. #if JUCE_VC6
  991. #define numElementsInArray(X) (sizeof((X)) / sizeof(0[X]))
  992. #else
  993. /** Handy function for getting the number of elements in a simple const C array.
  994. E.g.
  995. @code
  996. static int myArray[] = { 1, 2, 3 };
  997. int numElements = numElementsInArray (myArray) // returns 3
  998. @endcode
  999. */
  1000. template <typename Type, int N>
  1001. inline int numElementsInArray (Type (&array)[N])
  1002. {
  1003. (void) array; // (required to avoid a spurious warning in MS compilers)
  1004. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  1005. return N;
  1006. }
  1007. #endif
  1008. // Some useful maths functions that aren't always present with all compilers and build settings.
  1009. /** Using juce_hypot is easier than dealing with the different types of hypot function
  1010. that are provided by the various platforms and compilers. */
  1011. template <typename Type>
  1012. inline Type juce_hypot (Type a, Type b) noexcept
  1013. {
  1014. #if JUCE_WINDOWS
  1015. return static_cast <Type> (_hypot (a, b));
  1016. #else
  1017. return static_cast <Type> (hypot (a, b));
  1018. #endif
  1019. }
  1020. /** 64-bit abs function. */
  1021. inline int64 abs64 (const int64 n) noexcept
  1022. {
  1023. return (n >= 0) ? n : -n;
  1024. }
  1025. /** This templated negate function will negate pointers as well as integers */
  1026. template <typename Type>
  1027. inline Type juce_negate (Type n) noexcept
  1028. {
  1029. return sizeof (Type) == 1 ? (Type) -(signed char) n
  1030. : (sizeof (Type) == 2 ? (Type) -(short) n
  1031. : (sizeof (Type) == 4 ? (Type) -(int) n
  1032. : ((Type) -(int64) n)));
  1033. }
  1034. /** This templated negate function will negate pointers as well as integers */
  1035. template <typename Type>
  1036. inline Type* juce_negate (Type* n) noexcept
  1037. {
  1038. return (Type*) -(pointer_sized_int) n;
  1039. }
  1040. /** A predefined value for Pi, at double-precision.
  1041. @see float_Pi
  1042. */
  1043. const double double_Pi = 3.1415926535897932384626433832795;
  1044. /** A predefined value for Pi, at sngle-precision.
  1045. @see double_Pi
  1046. */
  1047. const float float_Pi = 3.14159265358979323846f;
  1048. /** The isfinite() method seems to vary between platforms, so this is a
  1049. platform-independent function for it.
  1050. */
  1051. template <typename FloatingPointType>
  1052. inline bool juce_isfinite (FloatingPointType value)
  1053. {
  1054. #if JUCE_WINDOWS
  1055. return _finite (value);
  1056. #elif JUCE_ANDROID
  1057. return isfinite (value);
  1058. #else
  1059. return std::isfinite (value);
  1060. #endif
  1061. }
  1062. /** Fast floating-point-to-integer conversion.
  1063. This is faster than using the normal c++ cast to convert a float to an int, and
  1064. it will round the value to the nearest integer, rather than rounding it down
  1065. like the normal cast does.
  1066. Note that this routine gets its speed at the expense of some accuracy, and when
  1067. rounding values whose floating point component is exactly 0.5, odd numbers and
  1068. even numbers will be rounded up or down differently.
  1069. */
  1070. template <typename FloatType>
  1071. inline int roundToInt (const FloatType value) noexcept
  1072. {
  1073. union { int asInt[2]; double asDouble; } n;
  1074. n.asDouble = ((double) value) + 6755399441055744.0;
  1075. #if JUCE_BIG_ENDIAN
  1076. return n.asInt [1];
  1077. #else
  1078. return n.asInt [0];
  1079. #endif
  1080. }
  1081. /** Fast floating-point-to-integer conversion.
  1082. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  1083. fine for values above zero, but negative numbers are rounded the wrong way.
  1084. */
  1085. inline int roundToIntAccurate (const double value) noexcept
  1086. {
  1087. return roundToInt (value + 1.5e-8);
  1088. }
  1089. /** Fast floating-point-to-integer conversion.
  1090. This is faster than using the normal c++ cast to convert a double to an int, and
  1091. it will round the value to the nearest integer, rather than rounding it down
  1092. like the normal cast does.
  1093. Note that this routine gets its speed at the expense of some accuracy, and when
  1094. rounding values whose floating point component is exactly 0.5, odd numbers and
  1095. even numbers will be rounded up or down differently. For a more accurate conversion,
  1096. see roundDoubleToIntAccurate().
  1097. */
  1098. inline int roundDoubleToInt (const double value) noexcept
  1099. {
  1100. return roundToInt (value);
  1101. }
  1102. /** Fast floating-point-to-integer conversion.
  1103. This is faster than using the normal c++ cast to convert a float to an int, and
  1104. it will round the value to the nearest integer, rather than rounding it down
  1105. like the normal cast does.
  1106. Note that this routine gets its speed at the expense of some accuracy, and when
  1107. rounding values whose floating point component is exactly 0.5, odd numbers and
  1108. even numbers will be rounded up or down differently.
  1109. */
  1110. inline int roundFloatToInt (const float value) noexcept
  1111. {
  1112. return roundToInt (value);
  1113. }
  1114. #if (JUCE_INTEL && JUCE_32BIT) || defined (DOXYGEN)
  1115. /** This macro can be applied to a float variable to check whether it contains a denormalised
  1116. value, and to normalise it if necessary.
  1117. On CPUs that aren't vulnerable to denormalisation problems, this will have no effect.
  1118. */
  1119. #define JUCE_UNDENORMALISE(x) x += 1.0f; x -= 1.0f;
  1120. #else
  1121. #define JUCE_UNDENORMALISE(x)
  1122. #endif
  1123. /** This namespace contains a few template classes for helping work out class type variations.
  1124. */
  1125. namespace TypeHelpers
  1126. {
  1127. #if JUCE_VC8_OR_EARLIER
  1128. #define PARAMETER_TYPE(type) const type&
  1129. #else
  1130. /** The ParameterType struct is used to find the best type to use when passing some kind
  1131. of object as a parameter.
  1132. Of course, this is only likely to be useful in certain esoteric template situations.
  1133. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  1134. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  1135. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  1136. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  1137. pass-by-value, but passing objects as a const reference, to avoid copying.
  1138. */
  1139. template <typename Type> struct ParameterType { typedef const Type& type; };
  1140. #if ! DOXYGEN
  1141. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  1142. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  1143. template <> struct ParameterType <char> { typedef char type; };
  1144. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  1145. template <> struct ParameterType <short> { typedef short type; };
  1146. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  1147. template <> struct ParameterType <int> { typedef int type; };
  1148. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  1149. template <> struct ParameterType <long> { typedef long type; };
  1150. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  1151. template <> struct ParameterType <int64> { typedef int64 type; };
  1152. template <> struct ParameterType <uint64> { typedef uint64 type; };
  1153. template <> struct ParameterType <bool> { typedef bool type; };
  1154. template <> struct ParameterType <float> { typedef float type; };
  1155. template <> struct ParameterType <double> { typedef double type; };
  1156. #endif
  1157. /** A helpful macro to simplify the use of the ParameterType template.
  1158. @see ParameterType
  1159. */
  1160. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  1161. #endif
  1162. }
  1163. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1164. /*** End of inlined file: juce_MathsFunctions.h ***/
  1165. /*** Start of inlined file: juce_ByteOrder.h ***/
  1166. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  1167. #define __JUCE_BYTEORDER_JUCEHEADER__
  1168. /** Contains static methods for converting the byte order between different
  1169. endiannesses.
  1170. */
  1171. class JUCE_API ByteOrder
  1172. {
  1173. public:
  1174. /** Swaps the upper and lower bytes of a 16-bit integer. */
  1175. static uint16 swap (uint16 value);
  1176. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  1177. static uint32 swap (uint32 value);
  1178. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  1179. static uint64 swap (uint64 value);
  1180. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  1181. static uint16 swapIfBigEndian (uint16 value);
  1182. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  1183. static uint32 swapIfBigEndian (uint32 value);
  1184. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  1185. static uint64 swapIfBigEndian (uint64 value);
  1186. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  1187. static uint16 swapIfLittleEndian (uint16 value);
  1188. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1189. static uint32 swapIfLittleEndian (uint32 value);
  1190. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1191. static uint64 swapIfLittleEndian (uint64 value);
  1192. /** Turns 4 bytes into a little-endian integer. */
  1193. static uint32 littleEndianInt (const void* bytes);
  1194. /** Turns 2 bytes into a little-endian integer. */
  1195. static uint16 littleEndianShort (const void* bytes);
  1196. /** Turns 4 bytes into a big-endian integer. */
  1197. static uint32 bigEndianInt (const void* bytes);
  1198. /** Turns 2 bytes into a big-endian integer. */
  1199. static uint16 bigEndianShort (const void* bytes);
  1200. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1201. static int littleEndian24Bit (const char* bytes);
  1202. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1203. static int bigEndian24Bit (const char* bytes);
  1204. /** Copies a 24-bit number to 3 little-endian bytes. */
  1205. static void littleEndian24BitToChars (int value, char* destBytes);
  1206. /** Copies a 24-bit number to 3 big-endian bytes. */
  1207. static void bigEndian24BitToChars (int value, char* destBytes);
  1208. /** Returns true if the current CPU is big-endian. */
  1209. static bool isBigEndian();
  1210. private:
  1211. ByteOrder();
  1212. JUCE_DECLARE_NON_COPYABLE (ByteOrder);
  1213. };
  1214. #if JUCE_USE_INTRINSICS && ! defined (__INTEL_COMPILER)
  1215. #pragma intrinsic (_byteswap_ulong)
  1216. #endif
  1217. inline uint16 ByteOrder::swap (uint16 n)
  1218. {
  1219. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1220. return static_cast <uint16> (_byteswap_ushort (n));
  1221. #else
  1222. return static_cast <uint16> ((n << 8) | (n >> 8));
  1223. #endif
  1224. }
  1225. inline uint32 ByteOrder::swap (uint32 n)
  1226. {
  1227. #if JUCE_MAC || JUCE_IOS
  1228. return OSSwapInt32 (n);
  1229. #elif JUCE_GCC && JUCE_INTEL
  1230. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1231. return n;
  1232. #elif JUCE_USE_INTRINSICS
  1233. return _byteswap_ulong (n);
  1234. #elif JUCE_MSVC
  1235. __asm {
  1236. mov eax, n
  1237. bswap eax
  1238. mov n, eax
  1239. }
  1240. return n;
  1241. #elif JUCE_ANDROID
  1242. return bswap_32 (n);
  1243. #else
  1244. return (n << 24) | (n >> 24) | ((n & 0xff00) << 8) | ((n & 0xff0000) >> 8);
  1245. #endif
  1246. }
  1247. inline uint64 ByteOrder::swap (uint64 value)
  1248. {
  1249. #if JUCE_MAC || JUCE_IOS
  1250. return OSSwapInt64 (value);
  1251. #elif JUCE_USE_INTRINSICS
  1252. return _byteswap_uint64 (value);
  1253. #else
  1254. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1255. #endif
  1256. }
  1257. #if JUCE_LITTLE_ENDIAN
  1258. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1259. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1260. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1261. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1262. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1263. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1264. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1265. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1266. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1267. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1268. inline bool ByteOrder::isBigEndian() { return false; }
  1269. #else
  1270. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1271. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1272. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1273. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1274. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1275. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1276. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1277. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1278. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1279. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1280. inline bool ByteOrder::isBigEndian() { return true; }
  1281. #endif
  1282. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1283. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1284. 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); }
  1285. 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); }
  1286. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1287. /*** End of inlined file: juce_ByteOrder.h ***/
  1288. /*** Start of inlined file: juce_Logger.h ***/
  1289. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1290. #define __JUCE_LOGGER_JUCEHEADER__
  1291. /*** Start of inlined file: juce_String.h ***/
  1292. #ifndef __JUCE_STRING_JUCEHEADER__
  1293. #define __JUCE_STRING_JUCEHEADER__
  1294. /*** Start of inlined file: juce_CharacterFunctions.h ***/
  1295. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1296. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1297. #if JUCE_WINDOWS && ! DOXYGEN
  1298. #define JUCE_NATIVE_WCHAR_IS_UTF8 0
  1299. #define JUCE_NATIVE_WCHAR_IS_UTF16 1
  1300. #define JUCE_NATIVE_WCHAR_IS_UTF32 0
  1301. #else
  1302. /** This macro will be set to 1 if the compiler's native wchar_t is an 8-bit type. */
  1303. #define JUCE_NATIVE_WCHAR_IS_UTF8 0
  1304. /** This macro will be set to 1 if the compiler's native wchar_t is a 16-bit type. */
  1305. #define JUCE_NATIVE_WCHAR_IS_UTF16 0
  1306. /** This macro will be set to 1 if the compiler's native wchar_t is a 32-bit type. */
  1307. #define JUCE_NATIVE_WCHAR_IS_UTF32 1
  1308. #endif
  1309. #if JUCE_NATIVE_WCHAR_IS_UTF32 || DOXYGEN
  1310. /** A platform-independent 32-bit unicode character type. */
  1311. typedef wchar_t juce_wchar;
  1312. #else
  1313. typedef uint32 juce_wchar;
  1314. #endif
  1315. /** This macro is deprecated, but preserved for compatibility with old code.*/
  1316. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1317. #if ! JUCE_DONT_DEFINE_MACROS
  1318. /** The 'T' macro is an alternative for using the "L" prefix in front of a string literal.
  1319. This macro is deprectated, but kept here for compatibility with old code. The best (i.e.
  1320. most portable) way to encode your string literals is just as standard 8-bit strings, but
  1321. using escaped utf-8 character codes for extended characters.
  1322. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1323. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1324. the juce/src directory) to avoid defining this macro. See the comments in
  1325. juce_withoutMacros.h for more info.
  1326. */
  1327. #define T(stringLiteral) JUCE_T(stringLiteral)
  1328. #endif
  1329. #undef max
  1330. #undef min
  1331. /**
  1332. A set of methods for manipulating characters and character strings.
  1333. These are defined as wrappers around the basic C string handlers, to provide
  1334. a clean, cross-platform layer, (because various platforms differ in the
  1335. range of C library calls that they provide).
  1336. @see String
  1337. */
  1338. class JUCE_API CharacterFunctions
  1339. {
  1340. public:
  1341. static juce_wchar toUpperCase (juce_wchar character) noexcept;
  1342. static juce_wchar toLowerCase (juce_wchar character) noexcept;
  1343. static bool isUpperCase (juce_wchar character) noexcept;
  1344. static bool isLowerCase (juce_wchar character) noexcept;
  1345. static bool isWhitespace (char character) noexcept;
  1346. static bool isWhitespace (juce_wchar character) noexcept;
  1347. static bool isDigit (char character) noexcept;
  1348. static bool isDigit (juce_wchar character) noexcept;
  1349. static bool isLetter (char character) noexcept;
  1350. static bool isLetter (juce_wchar character) noexcept;
  1351. static bool isLetterOrDigit (char character) noexcept;
  1352. static bool isLetterOrDigit (juce_wchar character) noexcept;
  1353. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legal hex digit. */
  1354. static int getHexDigitValue (juce_wchar digit) noexcept;
  1355. template <typename CharPointerType>
  1356. static double readDoubleValue (CharPointerType& text) noexcept
  1357. {
  1358. double result[3] = { 0 }, accumulator[2] = { 0 };
  1359. int exponentAdjustment[2] = { 0 }, exponentAccumulator[2] = { -1, -1 };
  1360. int exponent = 0, decPointIndex = 0, digit = 0;
  1361. int lastDigit = 0, numSignificantDigits = 0;
  1362. bool isNegative = false, digitsFound = false;
  1363. const int maxSignificantDigits = 15 + 2;
  1364. text = text.findEndOfWhitespace();
  1365. juce_wchar c = *text;
  1366. switch (c)
  1367. {
  1368. case '-': isNegative = true; // fall-through..
  1369. case '+': c = *++text;
  1370. }
  1371. switch (c)
  1372. {
  1373. case 'n':
  1374. case 'N':
  1375. if ((text[1] == 'a' || text[1] == 'A') && (text[2] == 'n' || text[2] == 'N'))
  1376. return std::numeric_limits<double>::quiet_NaN();
  1377. break;
  1378. case 'i':
  1379. case 'I':
  1380. if ((text[1] == 'n' || text[1] == 'N') && (text[2] == 'f' || text[2] == 'F'))
  1381. return std::numeric_limits<double>::infinity();
  1382. break;
  1383. }
  1384. for (;;)
  1385. {
  1386. if (text.isDigit())
  1387. {
  1388. lastDigit = digit;
  1389. digit = text.getAndAdvance() - '0';
  1390. digitsFound = true;
  1391. if (decPointIndex != 0)
  1392. exponentAdjustment[1]++;
  1393. if (numSignificantDigits == 0 && digit == 0)
  1394. continue;
  1395. if (++numSignificantDigits > maxSignificantDigits)
  1396. {
  1397. if (digit > 5)
  1398. ++accumulator [decPointIndex];
  1399. else if (digit == 5 && (lastDigit & 1) != 0)
  1400. ++accumulator [decPointIndex];
  1401. if (decPointIndex > 0)
  1402. exponentAdjustment[1]--;
  1403. else
  1404. exponentAdjustment[0]++;
  1405. while (text.isDigit())
  1406. {
  1407. ++text;
  1408. if (decPointIndex == 0)
  1409. exponentAdjustment[0]++;
  1410. }
  1411. }
  1412. else
  1413. {
  1414. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  1415. if (accumulator [decPointIndex] > maxAccumulatorValue)
  1416. {
  1417. result [decPointIndex] = mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  1418. + accumulator [decPointIndex];
  1419. accumulator [decPointIndex] = 0;
  1420. exponentAccumulator [decPointIndex] = 0;
  1421. }
  1422. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  1423. exponentAccumulator [decPointIndex]++;
  1424. }
  1425. }
  1426. else if (decPointIndex == 0 && *text == '.')
  1427. {
  1428. ++text;
  1429. decPointIndex = 1;
  1430. if (numSignificantDigits > maxSignificantDigits)
  1431. {
  1432. while (text.isDigit())
  1433. ++text;
  1434. break;
  1435. }
  1436. }
  1437. else
  1438. {
  1439. break;
  1440. }
  1441. }
  1442. result[0] = mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  1443. if (decPointIndex != 0)
  1444. result[1] = mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  1445. c = *text;
  1446. if ((c == 'e' || c == 'E') && digitsFound)
  1447. {
  1448. bool negativeExponent = false;
  1449. switch (*++text)
  1450. {
  1451. case '-': negativeExponent = true; // fall-through..
  1452. case '+': ++text;
  1453. }
  1454. while (text.isDigit())
  1455. exponent = (exponent * 10) + (text.getAndAdvance() - '0');
  1456. if (negativeExponent)
  1457. exponent = -exponent;
  1458. }
  1459. double r = mulexp10 (result[0], exponent + exponentAdjustment[0]);
  1460. if (decPointIndex != 0)
  1461. r += mulexp10 (result[1], exponent - exponentAdjustment[1]);
  1462. return isNegative ? -r : r;
  1463. }
  1464. template <typename CharPointerType>
  1465. static double getDoubleValue (const CharPointerType& text) noexcept
  1466. {
  1467. CharPointerType t (text);
  1468. return readDoubleValue (t);
  1469. }
  1470. template <typename IntType, typename CharPointerType>
  1471. static IntType getIntValue (const CharPointerType& text) noexcept
  1472. {
  1473. IntType v = 0;
  1474. CharPointerType s (text.findEndOfWhitespace());
  1475. const bool isNeg = *s == '-';
  1476. if (isNeg)
  1477. ++s;
  1478. for (;;)
  1479. {
  1480. const juce_wchar c = s.getAndAdvance();
  1481. if (c >= '0' && c <= '9')
  1482. v = v * 10 + (IntType) (c - '0');
  1483. else
  1484. break;
  1485. }
  1486. return isNeg ? -v : v;
  1487. }
  1488. template <typename CharPointerType>
  1489. static size_t lengthUpTo (CharPointerType text, const size_t maxCharsToCount) noexcept
  1490. {
  1491. size_t len = 0;
  1492. while (len < maxCharsToCount && text.getAndAdvance() != 0)
  1493. ++len;
  1494. return len;
  1495. }
  1496. template <typename CharPointerType>
  1497. static size_t lengthUpTo (CharPointerType start, const CharPointerType& end) noexcept
  1498. {
  1499. size_t len = 0;
  1500. while (start < end && start.getAndAdvance() != 0)
  1501. ++len;
  1502. return len;
  1503. }
  1504. template <typename DestCharPointerType, typename SrcCharPointerType>
  1505. static void copyAll (DestCharPointerType& dest, SrcCharPointerType src) noexcept
  1506. {
  1507. for (;;)
  1508. {
  1509. const juce_wchar c = src.getAndAdvance();
  1510. if (c == 0)
  1511. break;
  1512. dest.write (c);
  1513. }
  1514. dest.writeNull();
  1515. }
  1516. template <typename DestCharPointerType, typename SrcCharPointerType>
  1517. static int copyWithDestByteLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxBytes) noexcept
  1518. {
  1519. typename DestCharPointerType::CharType const* const startAddress = dest.getAddress();
  1520. maxBytes -= sizeof (typename DestCharPointerType::CharType); // (allow for a terminating null)
  1521. for (;;)
  1522. {
  1523. const juce_wchar c = src.getAndAdvance();
  1524. const int bytesNeeded = (int) DestCharPointerType::getBytesRequiredFor (c);
  1525. maxBytes -= bytesNeeded;
  1526. if (c == 0 || maxBytes < 0)
  1527. break;
  1528. dest.write (c);
  1529. }
  1530. dest.writeNull();
  1531. return getAddressDifference (dest.getAddress(), startAddress);
  1532. }
  1533. template <typename DestCharPointerType, typename SrcCharPointerType>
  1534. static void copyWithCharLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxChars) noexcept
  1535. {
  1536. while (--maxChars > 0)
  1537. {
  1538. const juce_wchar c = src.getAndAdvance();
  1539. if (c == 0)
  1540. break;
  1541. dest.write (c);
  1542. }
  1543. dest.writeNull();
  1544. }
  1545. template <typename CharPointerType1, typename CharPointerType2>
  1546. static int compare (CharPointerType1 s1, CharPointerType2 s2) noexcept
  1547. {
  1548. for (;;)
  1549. {
  1550. const int c1 = (int) s1.getAndAdvance();
  1551. const int c2 = (int) s2.getAndAdvance();
  1552. const int diff = c1 - c2;
  1553. if (diff != 0)
  1554. return diff < 0 ? -1 : 1;
  1555. else if (c1 == 0)
  1556. break;
  1557. }
  1558. return 0;
  1559. }
  1560. template <typename CharPointerType1, typename CharPointerType2>
  1561. static int compareUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) noexcept
  1562. {
  1563. while (--maxChars >= 0)
  1564. {
  1565. const int c1 = (int) s1.getAndAdvance();
  1566. const int c2 = (int) s2.getAndAdvance();
  1567. const int diff = c1 - c2;
  1568. if (diff != 0)
  1569. return diff < 0 ? -1 : 1;
  1570. else if (c1 == 0)
  1571. break;
  1572. }
  1573. return 0;
  1574. }
  1575. template <typename CharPointerType1, typename CharPointerType2>
  1576. static int compareIgnoreCase (CharPointerType1 s1, CharPointerType2 s2) noexcept
  1577. {
  1578. for (;;)
  1579. {
  1580. int c1 = s1.toUpperCase();
  1581. int c2 = s2.toUpperCase();
  1582. ++s1;
  1583. ++s2;
  1584. const int diff = c1 - c2;
  1585. if (diff != 0)
  1586. return diff < 0 ? -1 : 1;
  1587. else if (c1 == 0)
  1588. break;
  1589. }
  1590. return 0;
  1591. }
  1592. template <typename CharPointerType1, typename CharPointerType2>
  1593. static int compareIgnoreCaseUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) noexcept
  1594. {
  1595. while (--maxChars >= 0)
  1596. {
  1597. int c1 = s1.toUpperCase();
  1598. int c2 = s2.toUpperCase();
  1599. ++s1;
  1600. ++s2;
  1601. const int diff = c1 - c2;
  1602. if (diff != 0)
  1603. return diff < 0 ? -1 : 1;
  1604. else if (c1 == 0)
  1605. break;
  1606. }
  1607. return 0;
  1608. }
  1609. template <typename CharPointerType1, typename CharPointerType2>
  1610. static int indexOf (CharPointerType1 haystack, const CharPointerType2& needle) noexcept
  1611. {
  1612. int index = 0;
  1613. const int needleLength = (int) needle.length();
  1614. for (;;)
  1615. {
  1616. if (haystack.compareUpTo (needle, needleLength) == 0)
  1617. return index;
  1618. if (haystack.getAndAdvance() == 0)
  1619. return -1;
  1620. ++index;
  1621. }
  1622. }
  1623. template <typename CharPointerType1, typename CharPointerType2>
  1624. static int indexOfIgnoreCase (CharPointerType1 haystack, const CharPointerType2& needle) noexcept
  1625. {
  1626. int index = 0;
  1627. const int needleLength = (int) needle.length();
  1628. for (;;)
  1629. {
  1630. if (haystack.compareIgnoreCaseUpTo (needle, needleLength) == 0)
  1631. return index;
  1632. if (haystack.getAndAdvance() == 0)
  1633. return -1;
  1634. ++index;
  1635. }
  1636. }
  1637. template <typename Type>
  1638. static int indexOfChar (Type text, const juce_wchar charToFind) noexcept
  1639. {
  1640. int i = 0;
  1641. while (! text.isEmpty())
  1642. {
  1643. if (text.getAndAdvance() == charToFind)
  1644. return i;
  1645. ++i;
  1646. }
  1647. return -1;
  1648. }
  1649. template <typename Type>
  1650. static int indexOfCharIgnoreCase (Type text, juce_wchar charToFind) noexcept
  1651. {
  1652. charToFind = CharacterFunctions::toLowerCase (charToFind);
  1653. int i = 0;
  1654. while (! text.isEmpty())
  1655. {
  1656. if (text.toLowerCase() == charToFind)
  1657. return i;
  1658. ++text;
  1659. ++i;
  1660. }
  1661. return -1;
  1662. }
  1663. template <typename Type>
  1664. static Type findEndOfWhitespace (const Type& text) noexcept
  1665. {
  1666. Type p (text);
  1667. while (p.isWhitespace())
  1668. ++p;
  1669. return p;
  1670. }
  1671. template <typename Type>
  1672. static Type findEndOfToken (const Type& text, const Type& breakCharacters, const Type& quoteCharacters)
  1673. {
  1674. Type t (text);
  1675. juce_wchar currentQuoteChar = 0;
  1676. while (! t.isEmpty())
  1677. {
  1678. const juce_wchar c = t.getAndAdvance();
  1679. if (currentQuoteChar == 0 && breakCharacters.indexOf (c) >= 0)
  1680. {
  1681. --t;
  1682. break;
  1683. }
  1684. if (quoteCharacters.indexOf (c) >= 0)
  1685. {
  1686. if (currentQuoteChar == 0)
  1687. currentQuoteChar = c;
  1688. else if (currentQuoteChar == c)
  1689. currentQuoteChar = 0;
  1690. }
  1691. }
  1692. return t;
  1693. }
  1694. private:
  1695. static double mulexp10 (const double value, int exponent) noexcept;
  1696. };
  1697. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1698. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1699. #ifndef JUCE_STRING_UTF_TYPE
  1700. #define JUCE_STRING_UTF_TYPE 8
  1701. #endif
  1702. #if JUCE_MSVC
  1703. #pragma warning (push)
  1704. #pragma warning (disable: 4514 4996)
  1705. #endif
  1706. /*** Start of inlined file: juce_Atomic.h ***/
  1707. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1708. #define __JUCE_ATOMIC_JUCEHEADER__
  1709. /**
  1710. Simple class to hold a primitive value and perform atomic operations on it.
  1711. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  1712. There are methods to perform most of the basic atomic operations.
  1713. */
  1714. template <typename Type>
  1715. class Atomic
  1716. {
  1717. public:
  1718. /** Creates a new value, initialised to zero. */
  1719. inline Atomic() noexcept
  1720. : value (0)
  1721. {
  1722. }
  1723. /** Creates a new value, with a given initial value. */
  1724. inline Atomic (const Type initialValue) noexcept
  1725. : value (initialValue)
  1726. {
  1727. }
  1728. /** Copies another value (atomically). */
  1729. inline Atomic (const Atomic& other) noexcept
  1730. : value (other.get())
  1731. {
  1732. }
  1733. /** Destructor. */
  1734. inline ~Atomic() noexcept
  1735. {
  1736. // This class can only be used for types which are 32 or 64 bits in size.
  1737. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  1738. }
  1739. /** Atomically reads and returns the current value. */
  1740. Type get() const noexcept;
  1741. /** Copies another value onto this one (atomically). */
  1742. inline Atomic& operator= (const Atomic& other) noexcept { exchange (other.get()); return *this; }
  1743. /** Copies another value onto this one (atomically). */
  1744. inline Atomic& operator= (const Type newValue) noexcept { exchange (newValue); return *this; }
  1745. /** Atomically sets the current value. */
  1746. void set (Type newValue) noexcept { exchange (newValue); }
  1747. /** Atomically sets the current value, returning the value that was replaced. */
  1748. Type exchange (Type value) noexcept;
  1749. /** Atomically adds a number to this value, returning the new value. */
  1750. Type operator+= (Type amountToAdd) noexcept;
  1751. /** Atomically subtracts a number from this value, returning the new value. */
  1752. Type operator-= (Type amountToSubtract) noexcept;
  1753. /** Atomically increments this value, returning the new value. */
  1754. Type operator++() noexcept;
  1755. /** Atomically decrements this value, returning the new value. */
  1756. Type operator--() noexcept;
  1757. /** Atomically compares this value with a target value, and if it is equal, sets
  1758. this to be equal to a new value.
  1759. This operation is the atomic equivalent of doing this:
  1760. @code
  1761. bool compareAndSetBool (Type newValue, Type valueToCompare)
  1762. {
  1763. if (get() == valueToCompare)
  1764. {
  1765. set (newValue);
  1766. return true;
  1767. }
  1768. return false;
  1769. }
  1770. @endcode
  1771. @returns true if the comparison was true and the value was replaced; false if
  1772. the comparison failed and the value was left unchanged.
  1773. @see compareAndSetValue
  1774. */
  1775. bool compareAndSetBool (Type newValue, Type valueToCompare) noexcept;
  1776. /** Atomically compares this value with a target value, and if it is equal, sets
  1777. this to be equal to a new value.
  1778. This operation is the atomic equivalent of doing this:
  1779. @code
  1780. Type compareAndSetValue (Type newValue, Type valueToCompare)
  1781. {
  1782. Type oldValue = get();
  1783. if (oldValue == valueToCompare)
  1784. set (newValue);
  1785. return oldValue;
  1786. }
  1787. @endcode
  1788. @returns the old value before it was changed.
  1789. @see compareAndSetBool
  1790. */
  1791. Type compareAndSetValue (Type newValue, Type valueToCompare) noexcept;
  1792. /** Implements a memory read/write barrier. */
  1793. static void memoryBarrier() noexcept;
  1794. #if JUCE_64BIT
  1795. JUCE_ALIGN (8)
  1796. #else
  1797. JUCE_ALIGN (4)
  1798. #endif
  1799. /** The raw value that this class operates on.
  1800. This is exposed publically in case you need to manipulate it directly
  1801. for performance reasons.
  1802. */
  1803. volatile Type value;
  1804. private:
  1805. static inline Type castFrom32Bit (int32 value) noexcept { return *(Type*) &value; }
  1806. static inline Type castFrom64Bit (int64 value) noexcept { return *(Type*) &value; }
  1807. static inline int32 castTo32Bit (Type value) noexcept { return *(int32*) &value; }
  1808. static inline int64 castTo64Bit (Type value) noexcept { return *(int64*) &value; }
  1809. Type operator++ (int); // better to just use pre-increment with atomics..
  1810. Type operator-- (int);
  1811. };
  1812. /*
  1813. The following code is in the header so that the atomics can be inlined where possible...
  1814. */
  1815. #if (JUCE_IOS && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  1816. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  1817. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  1818. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1819. #define JUCE_MAC_ATOMICS_VOLATILE
  1820. #else
  1821. #define JUCE_MAC_ATOMICS_VOLATILE volatile
  1822. #endif
  1823. #if JUCE_PPC || JUCE_IOS
  1824. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  1825. template <typename Type> static Type OSAtomicAdd64Barrier (Type b, JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return *a += b; }
  1826. template <typename Type> static Type OSAtomicIncrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return ++*a; }
  1827. template <typename Type> static Type OSAtomicDecrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) noexcept { jassertfalse; return --*a; }
  1828. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, JUCE_MAC_ATOMICS_VOLATILE Type* value) noexcept
  1829. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  1830. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1831. #endif
  1832. #elif JUCE_ANDROID
  1833. #define JUCE_ATOMICS_ANDROID 1 // Android atomic functions
  1834. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1835. #elif JUCE_GCC
  1836. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  1837. #if JUCE_IOS
  1838. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1 // (on the iphone, the 64-bit ops will compile but not link)
  1839. #endif
  1840. #else
  1841. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  1842. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  1843. #ifndef __INTEL_COMPILER
  1844. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  1845. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  1846. #endif
  1847. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  1848. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  1849. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  1850. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  1851. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  1852. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  1853. #define juce_MemoryBarrier _ReadWriteBarrier
  1854. #else
  1855. // (these are defined in juce_win32_Threads.cpp)
  1856. long juce_InterlockedExchange (volatile long* a, long b) noexcept;
  1857. long juce_InterlockedIncrement (volatile long* a) noexcept;
  1858. long juce_InterlockedDecrement (volatile long* a) noexcept;
  1859. long juce_InterlockedExchangeAdd (volatile long* a, long b) noexcept;
  1860. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) noexcept;
  1861. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) noexcept;
  1862. inline void juce_MemoryBarrier() noexcept { long x = 0; juce_InterlockedIncrement (&x); }
  1863. #endif
  1864. #if JUCE_64BIT
  1865. #ifndef __INTEL_COMPILER
  1866. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  1867. #endif
  1868. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  1869. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  1870. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  1871. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  1872. #else
  1873. // None of these atomics are available in a 32-bit Windows build!!
  1874. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) noexcept { jassertfalse; Type old = *a; *a += b; return old; }
  1875. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) noexcept { jassertfalse; Type old = *a; *a = b; return old; }
  1876. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) noexcept { jassertfalse; return ++*a; }
  1877. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) noexcept { jassertfalse; return --*a; }
  1878. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1879. #endif
  1880. #endif
  1881. #if JUCE_MSVC
  1882. #pragma warning (push)
  1883. #pragma warning (disable: 4311) // (truncation warning)
  1884. #endif
  1885. template <typename Type>
  1886. inline Type Atomic<Type>::get() const noexcept
  1887. {
  1888. #if JUCE_ATOMICS_MAC
  1889. return sizeof (Type) == 4 ? castFrom32Bit ((int32) OSAtomicAdd32Barrier ((int32_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value))
  1890. : castFrom64Bit ((int64) OSAtomicAdd64Barrier ((int64_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value));
  1891. #elif JUCE_ATOMICS_WINDOWS
  1892. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchangeAdd ((volatile long*) &value, (long) 0))
  1893. : castFrom64Bit ((int64) juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0));
  1894. #elif JUCE_ATOMICS_ANDROID
  1895. return value;
  1896. #elif JUCE_ATOMICS_GCC
  1897. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_add_and_fetch ((volatile int32*) &value, 0))
  1898. : castFrom64Bit ((int64) __sync_add_and_fetch ((volatile int64*) &value, 0));
  1899. #endif
  1900. }
  1901. template <typename Type>
  1902. inline Type Atomic<Type>::exchange (const Type newValue) noexcept
  1903. {
  1904. #if JUCE_ATOMICS_ANDROID
  1905. return castFrom32Bit (__atomic_swap (castTo32Bit (newValue), (volatile int*) &value));
  1906. #elif JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  1907. Type currentVal = value;
  1908. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  1909. return currentVal;
  1910. #elif JUCE_ATOMICS_WINDOWS
  1911. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue)))
  1912. : castFrom64Bit ((int64) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue)));
  1913. #endif
  1914. }
  1915. template <typename Type>
  1916. inline Type Atomic<Type>::operator+= (const Type amountToAdd) noexcept
  1917. {
  1918. #if JUCE_ATOMICS_MAC
  1919. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32Barrier ((int32_t) castTo32Bit (amountToAdd), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1920. : (Type) OSAtomicAdd64Barrier ((int64_t) amountToAdd, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1921. #elif JUCE_ATOMICS_WINDOWS
  1922. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  1923. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  1924. #elif JUCE_ATOMICS_ANDROID
  1925. for (;;)
  1926. {
  1927. const Type oldValue (value);
  1928. const Type newValue (castFrom32Bit (castTo32Bit (oldValue) + castTo32Bit (amountToAdd)));
  1929. if (compareAndSetBool (newValue, oldValue))
  1930. return newValue;
  1931. }
  1932. #elif JUCE_ATOMICS_GCC
  1933. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  1934. #endif
  1935. }
  1936. template <typename Type>
  1937. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) noexcept
  1938. {
  1939. return operator+= (juce_negate (amountToSubtract));
  1940. }
  1941. template <typename Type>
  1942. inline Type Atomic<Type>::operator++() noexcept
  1943. {
  1944. #if JUCE_ATOMICS_MAC
  1945. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1946. : (Type) OSAtomicIncrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1947. #elif JUCE_ATOMICS_WINDOWS
  1948. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  1949. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  1950. #elif JUCE_ATOMICS_ANDROID
  1951. return (Type) (__atomic_inc ((volatile int*) &value) + 1);
  1952. #elif JUCE_ATOMICS_GCC
  1953. return (Type) __sync_add_and_fetch (&value, 1);
  1954. #endif
  1955. }
  1956. template <typename Type>
  1957. inline Type Atomic<Type>::operator--() noexcept
  1958. {
  1959. #if JUCE_ATOMICS_MAC
  1960. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1961. : (Type) OSAtomicDecrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1962. #elif JUCE_ATOMICS_WINDOWS
  1963. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  1964. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  1965. #elif JUCE_ATOMICS_ANDROID
  1966. return (Type) (__atomic_dec ((volatile int*) &value) - 1);
  1967. #elif JUCE_ATOMICS_GCC
  1968. return (Type) __sync_add_and_fetch (&value, -1);
  1969. #endif
  1970. }
  1971. template <typename Type>
  1972. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) noexcept
  1973. {
  1974. #if JUCE_ATOMICS_MAC
  1975. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) castTo32Bit (valueToCompare), (int32_t) castTo32Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1976. : OSAtomicCompareAndSwap64Barrier ((int64_t) castTo64Bit (valueToCompare), (int64_t) castTo64Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1977. #elif JUCE_ATOMICS_WINDOWS
  1978. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  1979. #elif JUCE_ATOMICS_ANDROID
  1980. return __atomic_cmpxchg (castTo32Bit (valueToCompare), castTo32Bit (newValue), (volatile int*) &value) == 0;
  1981. #elif JUCE_ATOMICS_GCC
  1982. return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))
  1983. : __sync_bool_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue));
  1984. #endif
  1985. }
  1986. template <typename Type>
  1987. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) noexcept
  1988. {
  1989. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_ANDROID
  1990. for (;;) // Annoying workaround for only having a bool CAS operation..
  1991. {
  1992. if (compareAndSetBool (newValue, valueToCompare))
  1993. return valueToCompare;
  1994. const Type result = value;
  1995. if (result != valueToCompare)
  1996. return result;
  1997. }
  1998. #elif JUCE_ATOMICS_WINDOWS
  1999. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare)))
  2000. : castFrom64Bit ((int64) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare)));
  2001. #elif JUCE_ATOMICS_GCC
  2002. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_val_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)))
  2003. : castFrom64Bit ((int64) __sync_val_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)));
  2004. #endif
  2005. }
  2006. template <typename Type>
  2007. inline void Atomic<Type>::memoryBarrier() noexcept
  2008. {
  2009. #if JUCE_ATOMICS_MAC
  2010. OSMemoryBarrier();
  2011. #elif JUCE_ATOMICS_GCC
  2012. __sync_synchronize();
  2013. #elif JUCE_ATOMICS_WINDOWS
  2014. juce_MemoryBarrier();
  2015. #endif
  2016. }
  2017. #if JUCE_MSVC
  2018. #pragma warning (pop)
  2019. #endif
  2020. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2021. /*** End of inlined file: juce_Atomic.h ***/
  2022. /*** Start of inlined file: juce_CharPointer_UTF8.h ***/
  2023. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2024. #define __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2025. /**
  2026. Wraps a pointer to a null-terminated UTF-8 character string, and provides
  2027. various methods to operate on the data.
  2028. @see CharPointer_UTF16, CharPointer_UTF32
  2029. */
  2030. class CharPointer_UTF8
  2031. {
  2032. public:
  2033. typedef char CharType;
  2034. inline explicit CharPointer_UTF8 (const CharType* const rawPointer) noexcept
  2035. : data (const_cast <CharType*> (rawPointer))
  2036. {
  2037. }
  2038. inline CharPointer_UTF8 (const CharPointer_UTF8& other) noexcept
  2039. : data (other.data)
  2040. {
  2041. }
  2042. inline CharPointer_UTF8& operator= (const CharPointer_UTF8& other) noexcept
  2043. {
  2044. data = other.data;
  2045. return *this;
  2046. }
  2047. inline CharPointer_UTF8& operator= (const CharType* text) noexcept
  2048. {
  2049. data = const_cast <CharType*> (text);
  2050. return *this;
  2051. }
  2052. /** This is a pointer comparison, it doesn't compare the actual text. */
  2053. inline bool operator== (const CharPointer_UTF8& other) const noexcept { return data == other.data; }
  2054. inline bool operator!= (const CharPointer_UTF8& other) const noexcept { return data != other.data; }
  2055. inline bool operator<= (const CharPointer_UTF8& other) const noexcept { return data <= other.data; }
  2056. inline bool operator< (const CharPointer_UTF8& other) const noexcept { return data < other.data; }
  2057. inline bool operator>= (const CharPointer_UTF8& other) const noexcept { return data >= other.data; }
  2058. inline bool operator> (const CharPointer_UTF8& other) const noexcept { return data > other.data; }
  2059. /** Returns the address that this pointer is pointing to. */
  2060. inline CharType* getAddress() const noexcept { return data; }
  2061. /** Returns the address that this pointer is pointing to. */
  2062. inline operator const CharType*() const noexcept { return data; }
  2063. /** Returns true if this pointer is pointing to a null character. */
  2064. inline bool isEmpty() const noexcept { return *data == 0; }
  2065. /** Returns the unicode character that this pointer is pointing to. */
  2066. juce_wchar operator*() const noexcept
  2067. {
  2068. const signed char byte = (signed char) *data;
  2069. if (byte >= 0)
  2070. return byte;
  2071. uint32 n = (uint32) (uint8) byte;
  2072. uint32 mask = 0x7f;
  2073. uint32 bit = 0x40;
  2074. size_t numExtraValues = 0;
  2075. while ((n & bit) != 0 && bit > 0x10)
  2076. {
  2077. mask >>= 1;
  2078. ++numExtraValues;
  2079. bit >>= 1;
  2080. }
  2081. n &= mask;
  2082. for (size_t i = 1; i <= numExtraValues; ++i)
  2083. {
  2084. const juce_wchar nextByte = data [i];
  2085. if ((nextByte & 0xc0) != 0x80)
  2086. break;
  2087. n <<= 6;
  2088. n |= (nextByte & 0x3f);
  2089. }
  2090. return (juce_wchar) n;
  2091. }
  2092. /** Moves this pointer along to the next character in the string. */
  2093. CharPointer_UTF8& operator++() noexcept
  2094. {
  2095. const signed char n = (signed char) *data++;
  2096. if (n < 0)
  2097. {
  2098. juce_wchar bit = 0x40;
  2099. while ((n & bit) != 0 && bit > 0x8)
  2100. {
  2101. ++data;
  2102. bit >>= 1;
  2103. }
  2104. }
  2105. return *this;
  2106. }
  2107. /** Moves this pointer back to the previous character in the string. */
  2108. CharPointer_UTF8& operator--() noexcept
  2109. {
  2110. const char n = *--data;
  2111. if ((n & 0xc0) == 0xc0)
  2112. {
  2113. int count = 3;
  2114. do
  2115. {
  2116. --data;
  2117. }
  2118. while ((*data & 0xc0) == 0xc0 && --count >= 0);
  2119. }
  2120. return *this;
  2121. }
  2122. /** Returns the character that this pointer is currently pointing to, and then
  2123. advances the pointer to point to the next character. */
  2124. juce_wchar getAndAdvance() noexcept
  2125. {
  2126. const signed char byte = (signed char) *data++;
  2127. if (byte >= 0)
  2128. return byte;
  2129. uint32 n = (uint32) (uint8) byte;
  2130. uint32 mask = 0x7f;
  2131. uint32 bit = 0x40;
  2132. int numExtraValues = 0;
  2133. while ((n & bit) != 0 && bit > 0x8)
  2134. {
  2135. mask >>= 1;
  2136. ++numExtraValues;
  2137. bit >>= 1;
  2138. }
  2139. n &= mask;
  2140. while (--numExtraValues >= 0)
  2141. {
  2142. const uint32 nextByte = (uint32) (uint8) *data++;
  2143. if ((nextByte & 0xc0) != 0x80)
  2144. break;
  2145. n <<= 6;
  2146. n |= (nextByte & 0x3f);
  2147. }
  2148. return (juce_wchar) n;
  2149. }
  2150. /** Moves this pointer along to the next character in the string. */
  2151. CharPointer_UTF8 operator++ (int) noexcept
  2152. {
  2153. CharPointer_UTF8 temp (*this);
  2154. ++*this;
  2155. return temp;
  2156. }
  2157. /** Moves this pointer forwards by the specified number of characters. */
  2158. void operator+= (int numToSkip) noexcept
  2159. {
  2160. if (numToSkip < 0)
  2161. {
  2162. while (++numToSkip <= 0)
  2163. --*this;
  2164. }
  2165. else
  2166. {
  2167. while (--numToSkip >= 0)
  2168. ++*this;
  2169. }
  2170. }
  2171. /** Moves this pointer backwards by the specified number of characters. */
  2172. void operator-= (int numToSkip) noexcept
  2173. {
  2174. operator+= (-numToSkip);
  2175. }
  2176. /** Returns the character at a given character index from the start of the string. */
  2177. juce_wchar operator[] (int characterIndex) const noexcept
  2178. {
  2179. CharPointer_UTF8 p (*this);
  2180. p += characterIndex;
  2181. return *p;
  2182. }
  2183. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2184. CharPointer_UTF8 operator+ (int numToSkip) const noexcept
  2185. {
  2186. CharPointer_UTF8 p (*this);
  2187. p += numToSkip;
  2188. return p;
  2189. }
  2190. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2191. CharPointer_UTF8 operator- (int numToSkip) const noexcept
  2192. {
  2193. CharPointer_UTF8 p (*this);
  2194. p += -numToSkip;
  2195. return p;
  2196. }
  2197. /** Returns the number of characters in this string. */
  2198. size_t length() const noexcept
  2199. {
  2200. const CharType* d = data;
  2201. size_t count = 0;
  2202. for (;;)
  2203. {
  2204. const uint32 n = (uint32) (uint8) *d++;
  2205. if ((n & 0x80) != 0)
  2206. {
  2207. uint32 bit = 0x40;
  2208. while ((n & bit) != 0)
  2209. {
  2210. ++d;
  2211. bit >>= 1;
  2212. if (bit == 0)
  2213. break; // illegal utf-8 sequence
  2214. }
  2215. }
  2216. else if (n == 0)
  2217. break;
  2218. ++count;
  2219. }
  2220. return count;
  2221. }
  2222. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2223. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  2224. {
  2225. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2226. }
  2227. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2228. size_t lengthUpTo (const CharPointer_UTF8& end) const noexcept
  2229. {
  2230. return CharacterFunctions::lengthUpTo (*this, end);
  2231. }
  2232. /** Returns the number of bytes that are used to represent this string.
  2233. This includes the terminating null character.
  2234. */
  2235. size_t sizeInBytes() const noexcept
  2236. {
  2237. return strlen (data) + 1;
  2238. }
  2239. /** Returns the number of bytes that would be needed to represent the given
  2240. unicode character in this encoding format.
  2241. */
  2242. static size_t getBytesRequiredFor (const juce_wchar charToWrite) noexcept
  2243. {
  2244. size_t num = 1;
  2245. const uint32 c = (uint32) charToWrite;
  2246. if (c >= 0x80)
  2247. {
  2248. ++num;
  2249. if (c >= 0x800)
  2250. {
  2251. ++num;
  2252. if (c >= 0x10000)
  2253. ++num;
  2254. }
  2255. }
  2256. return num;
  2257. }
  2258. /** Returns the number of bytes that would be needed to represent the given
  2259. string in this encoding format.
  2260. The value returned does NOT include the terminating null character.
  2261. */
  2262. template <class CharPointer>
  2263. static size_t getBytesRequiredFor (CharPointer text) noexcept
  2264. {
  2265. size_t count = 0;
  2266. juce_wchar n;
  2267. while ((n = text.getAndAdvance()) != 0)
  2268. count += getBytesRequiredFor (n);
  2269. return count;
  2270. }
  2271. /** Returns a pointer to the null character that terminates this string. */
  2272. CharPointer_UTF8 findTerminatingNull() const noexcept
  2273. {
  2274. return CharPointer_UTF8 (data + strlen (data));
  2275. }
  2276. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2277. void write (const juce_wchar charToWrite) noexcept
  2278. {
  2279. const uint32 c = (uint32) charToWrite;
  2280. if (c >= 0x80)
  2281. {
  2282. int numExtraBytes = 1;
  2283. if (c >= 0x800)
  2284. {
  2285. ++numExtraBytes;
  2286. if (c >= 0x10000)
  2287. ++numExtraBytes;
  2288. }
  2289. *data++ = (CharType) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  2290. while (--numExtraBytes >= 0)
  2291. *data++ = (CharType) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  2292. }
  2293. else
  2294. {
  2295. *data++ = (CharType) c;
  2296. }
  2297. }
  2298. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2299. inline void writeNull() const noexcept
  2300. {
  2301. *data = 0;
  2302. }
  2303. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2304. template <typename CharPointer>
  2305. void writeAll (const CharPointer& src) noexcept
  2306. {
  2307. CharacterFunctions::copyAll (*this, src);
  2308. }
  2309. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2310. void writeAll (const CharPointer_UTF8& src) noexcept
  2311. {
  2312. const CharType* s = src.data;
  2313. while ((*data = *s) != 0)
  2314. {
  2315. ++data;
  2316. ++s;
  2317. }
  2318. }
  2319. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2320. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2321. to the destination buffer before stopping.
  2322. */
  2323. template <typename CharPointer>
  2324. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  2325. {
  2326. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2327. }
  2328. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2329. The maxChars parameter specifies the maximum number of characters that can be
  2330. written to the destination buffer before stopping (including the terminating null).
  2331. */
  2332. template <typename CharPointer>
  2333. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  2334. {
  2335. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2336. }
  2337. /** Compares this string with another one. */
  2338. template <typename CharPointer>
  2339. int compare (const CharPointer& other) const noexcept
  2340. {
  2341. return CharacterFunctions::compare (*this, other);
  2342. }
  2343. /** Compares this string with another one, up to a specified number of characters. */
  2344. template <typename CharPointer>
  2345. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  2346. {
  2347. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2348. }
  2349. /** Compares this string with another one. */
  2350. template <typename CharPointer>
  2351. int compareIgnoreCase (const CharPointer& other) const noexcept
  2352. {
  2353. return CharacterFunctions::compareIgnoreCase (*this, other);
  2354. }
  2355. /** Compares this string with another one. */
  2356. int compareIgnoreCase (const CharPointer_UTF8& other) const noexcept
  2357. {
  2358. #if JUCE_WINDOWS
  2359. return stricmp (data, other.data);
  2360. #else
  2361. return strcasecmp (data, other.data);
  2362. #endif
  2363. }
  2364. /** Compares this string with another one, up to a specified number of characters. */
  2365. template <typename CharPointer>
  2366. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  2367. {
  2368. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2369. }
  2370. /** Compares this string with another one, up to a specified number of characters. */
  2371. int compareIgnoreCaseUpTo (const CharPointer_UTF8& other, const int maxChars) const noexcept
  2372. {
  2373. #if JUCE_WINDOWS
  2374. return strnicmp (data, other.data, maxChars);
  2375. #else
  2376. return strncasecmp (data, other.data, maxChars);
  2377. #endif
  2378. }
  2379. /** Returns the character index of a substring, or -1 if it isn't found. */
  2380. template <typename CharPointer>
  2381. int indexOf (const CharPointer& stringToFind) const noexcept
  2382. {
  2383. return CharacterFunctions::indexOf (*this, stringToFind);
  2384. }
  2385. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2386. int indexOf (const juce_wchar charToFind) const noexcept
  2387. {
  2388. return CharacterFunctions::indexOfChar (*this, charToFind);
  2389. }
  2390. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2391. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  2392. {
  2393. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2394. : CharacterFunctions::indexOfChar (*this, charToFind);
  2395. }
  2396. /** Returns true if the first character of this string is whitespace. */
  2397. bool isWhitespace() const noexcept { return *data == ' ' || (*data <= 13 && *data >= 9); }
  2398. /** Returns true if the first character of this string is a digit. */
  2399. bool isDigit() const noexcept { return *data >= '0' && *data <= '9'; }
  2400. /** Returns true if the first character of this string is a letter. */
  2401. bool isLetter() const noexcept { return CharacterFunctions::isLetter (operator*()) != 0; }
  2402. /** Returns true if the first character of this string is a letter or digit. */
  2403. bool isLetterOrDigit() const noexcept { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2404. /** Returns true if the first character of this string is upper-case. */
  2405. bool isUpperCase() const noexcept { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2406. /** Returns true if the first character of this string is lower-case. */
  2407. bool isLowerCase() const noexcept { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2408. /** Returns an upper-case version of the first character of this string. */
  2409. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (operator*()); }
  2410. /** Returns a lower-case version of the first character of this string. */
  2411. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (operator*()); }
  2412. /** Parses this string as a 32-bit integer. */
  2413. int getIntValue32() const noexcept { return atoi (data); }
  2414. /** Parses this string as a 64-bit integer. */
  2415. int64 getIntValue64() const noexcept
  2416. {
  2417. #if JUCE_LINUX || JUCE_ANDROID
  2418. return atoll (data);
  2419. #elif JUCE_WINDOWS
  2420. return _atoi64 (data);
  2421. #else
  2422. return CharacterFunctions::getIntValue <int64, CharPointer_UTF8> (*this);
  2423. #endif
  2424. }
  2425. /** Parses this string as a floating point double. */
  2426. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  2427. /** Returns the first non-whitespace character in the string. */
  2428. CharPointer_UTF8 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  2429. /** Returns true if the given unicode character can be represented in this encoding. */
  2430. static bool canRepresent (juce_wchar character) noexcept
  2431. {
  2432. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  2433. }
  2434. /** Returns true if this data contains a valid string in this encoding. */
  2435. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2436. {
  2437. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2438. {
  2439. const signed char byte = (signed char) *dataToTest;
  2440. if (byte < 0)
  2441. {
  2442. uint32 n = (uint32) (uint8) byte;
  2443. uint32 mask = 0x7f;
  2444. uint32 bit = 0x40;
  2445. int numExtraValues = 0;
  2446. while ((n & bit) != 0)
  2447. {
  2448. if (bit <= 0x10)
  2449. return false;
  2450. mask >>= 1;
  2451. ++numExtraValues;
  2452. bit >>= 1;
  2453. }
  2454. n &= mask;
  2455. while (--numExtraValues >= 0)
  2456. {
  2457. const uint32 nextByte = (uint32) (uint8) *dataToTest++;
  2458. if ((nextByte & 0xc0) != 0x80)
  2459. return false;
  2460. }
  2461. }
  2462. }
  2463. return true;
  2464. }
  2465. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2466. CharPointer_UTF8 atomicSwap (const CharPointer_UTF8& newValue)
  2467. {
  2468. return CharPointer_UTF8 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2469. }
  2470. /** These values are the byte-order-mark (BOM) values for a UTF-8 stream. */
  2471. enum
  2472. {
  2473. byteOrderMark1 = 0xef,
  2474. byteOrderMark2 = 0xbb,
  2475. byteOrderMark3 = 0xbf
  2476. };
  2477. private:
  2478. CharType* data;
  2479. };
  2480. #endif // __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2481. /*** End of inlined file: juce_CharPointer_UTF8.h ***/
  2482. /*** Start of inlined file: juce_CharPointer_UTF16.h ***/
  2483. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2484. #define __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2485. /**
  2486. Wraps a pointer to a null-terminated UTF-16 character string, and provides
  2487. various methods to operate on the data.
  2488. @see CharPointer_UTF8, CharPointer_UTF32
  2489. */
  2490. class CharPointer_UTF16
  2491. {
  2492. public:
  2493. #if JUCE_NATIVE_WCHAR_IS_UTF16
  2494. typedef wchar_t CharType;
  2495. #else
  2496. typedef int16 CharType;
  2497. #endif
  2498. inline explicit CharPointer_UTF16 (const CharType* const rawPointer) noexcept
  2499. : data (const_cast <CharType*> (rawPointer))
  2500. {
  2501. }
  2502. inline CharPointer_UTF16 (const CharPointer_UTF16& other) noexcept
  2503. : data (other.data)
  2504. {
  2505. }
  2506. inline CharPointer_UTF16& operator= (const CharPointer_UTF16& other) noexcept
  2507. {
  2508. data = other.data;
  2509. return *this;
  2510. }
  2511. inline CharPointer_UTF16& operator= (const CharType* text) noexcept
  2512. {
  2513. data = const_cast <CharType*> (text);
  2514. return *this;
  2515. }
  2516. /** This is a pointer comparison, it doesn't compare the actual text. */
  2517. inline bool operator== (const CharPointer_UTF16& other) const noexcept { return data == other.data; }
  2518. inline bool operator!= (const CharPointer_UTF16& other) const noexcept { return data != other.data; }
  2519. inline bool operator<= (const CharPointer_UTF16& other) const noexcept { return data <= other.data; }
  2520. inline bool operator< (const CharPointer_UTF16& other) const noexcept { return data < other.data; }
  2521. inline bool operator>= (const CharPointer_UTF16& other) const noexcept { return data >= other.data; }
  2522. inline bool operator> (const CharPointer_UTF16& other) const noexcept { return data > other.data; }
  2523. /** Returns the address that this pointer is pointing to. */
  2524. inline CharType* getAddress() const noexcept { return data; }
  2525. /** Returns the address that this pointer is pointing to. */
  2526. inline operator const CharType*() const noexcept { return data; }
  2527. /** Returns true if this pointer is pointing to a null character. */
  2528. inline bool isEmpty() const noexcept { return *data == 0; }
  2529. /** Returns the unicode character that this pointer is pointing to. */
  2530. juce_wchar operator*() const noexcept
  2531. {
  2532. uint32 n = (uint32) (uint16) *data;
  2533. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) data[1]) >= 0xdc00)
  2534. n = 0x10000 + (((n - 0xd800) << 10) | (((uint32) (uint16) data[1]) - 0xdc00));
  2535. return (juce_wchar) n;
  2536. }
  2537. /** Moves this pointer along to the next character in the string. */
  2538. CharPointer_UTF16& operator++() noexcept
  2539. {
  2540. const juce_wchar n = *data++;
  2541. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2542. ++data;
  2543. return *this;
  2544. }
  2545. /** Moves this pointer back to the previous character in the string. */
  2546. CharPointer_UTF16& operator--() noexcept
  2547. {
  2548. const juce_wchar n = *--data;
  2549. if (n >= 0xdc00 && n <= 0xdfff)
  2550. --data;
  2551. return *this;
  2552. }
  2553. /** Returns the character that this pointer is currently pointing to, and then
  2554. advances the pointer to point to the next character. */
  2555. juce_wchar getAndAdvance() noexcept
  2556. {
  2557. uint32 n = (uint32) (uint16) *data++;
  2558. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2559. n = 0x10000 + ((((n - 0xd800) << 10) | (((uint32) (uint16) *data++) - 0xdc00)));
  2560. return (juce_wchar) n;
  2561. }
  2562. /** Moves this pointer along to the next character in the string. */
  2563. CharPointer_UTF16 operator++ (int) noexcept
  2564. {
  2565. CharPointer_UTF16 temp (*this);
  2566. ++*this;
  2567. return temp;
  2568. }
  2569. /** Moves this pointer forwards by the specified number of characters. */
  2570. void operator+= (int numToSkip) noexcept
  2571. {
  2572. if (numToSkip < 0)
  2573. {
  2574. while (++numToSkip <= 0)
  2575. --*this;
  2576. }
  2577. else
  2578. {
  2579. while (--numToSkip >= 0)
  2580. ++*this;
  2581. }
  2582. }
  2583. /** Moves this pointer backwards by the specified number of characters. */
  2584. void operator-= (int numToSkip) noexcept
  2585. {
  2586. operator+= (-numToSkip);
  2587. }
  2588. /** Returns the character at a given character index from the start of the string. */
  2589. juce_wchar operator[] (const int characterIndex) const noexcept
  2590. {
  2591. CharPointer_UTF16 p (*this);
  2592. p += characterIndex;
  2593. return *p;
  2594. }
  2595. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2596. CharPointer_UTF16 operator+ (const int numToSkip) const noexcept
  2597. {
  2598. CharPointer_UTF16 p (*this);
  2599. p += numToSkip;
  2600. return p;
  2601. }
  2602. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2603. CharPointer_UTF16 operator- (const int numToSkip) const noexcept
  2604. {
  2605. CharPointer_UTF16 p (*this);
  2606. p += -numToSkip;
  2607. return p;
  2608. }
  2609. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2610. void write (juce_wchar charToWrite) noexcept
  2611. {
  2612. if (charToWrite >= 0x10000)
  2613. {
  2614. charToWrite -= 0x10000;
  2615. *data++ = (CharType) (0xd800 + (charToWrite >> 10));
  2616. *data++ = (CharType) (0xdc00 + (charToWrite & 0x3ff));
  2617. }
  2618. else
  2619. {
  2620. *data++ = (CharType) charToWrite;
  2621. }
  2622. }
  2623. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2624. inline void writeNull() const noexcept
  2625. {
  2626. *data = 0;
  2627. }
  2628. /** Returns the number of characters in this string. */
  2629. size_t length() const noexcept
  2630. {
  2631. const CharType* d = data;
  2632. size_t count = 0;
  2633. for (;;)
  2634. {
  2635. const int n = *d++;
  2636. if (n >= 0xd800 && n <= 0xdfff)
  2637. {
  2638. if (*d++ == 0)
  2639. break;
  2640. }
  2641. else if (n == 0)
  2642. break;
  2643. ++count;
  2644. }
  2645. return count;
  2646. }
  2647. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2648. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  2649. {
  2650. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2651. }
  2652. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2653. size_t lengthUpTo (const CharPointer_UTF16& end) const noexcept
  2654. {
  2655. return CharacterFunctions::lengthUpTo (*this, end);
  2656. }
  2657. /** Returns the number of bytes that are used to represent this string.
  2658. This includes the terminating null character.
  2659. */
  2660. size_t sizeInBytes() const noexcept
  2661. {
  2662. return sizeof (CharType) * (findNullIndex (data) + 1);
  2663. }
  2664. /** Returns the number of bytes that would be needed to represent the given
  2665. unicode character in this encoding format.
  2666. */
  2667. static size_t getBytesRequiredFor (const juce_wchar charToWrite) noexcept
  2668. {
  2669. return (charToWrite >= 0x10000) ? (sizeof (CharType) * 2) : sizeof (CharType);
  2670. }
  2671. /** Returns the number of bytes that would be needed to represent the given
  2672. string in this encoding format.
  2673. The value returned does NOT include the terminating null character.
  2674. */
  2675. template <class CharPointer>
  2676. static size_t getBytesRequiredFor (CharPointer text) noexcept
  2677. {
  2678. size_t count = 0;
  2679. juce_wchar n;
  2680. while ((n = text.getAndAdvance()) != 0)
  2681. count += getBytesRequiredFor (n);
  2682. return count;
  2683. }
  2684. /** Returns a pointer to the null character that terminates this string. */
  2685. CharPointer_UTF16 findTerminatingNull() const noexcept
  2686. {
  2687. const CharType* t = data;
  2688. while (*t != 0)
  2689. ++t;
  2690. return CharPointer_UTF16 (t);
  2691. }
  2692. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2693. template <typename CharPointer>
  2694. void writeAll (const CharPointer& src) noexcept
  2695. {
  2696. CharacterFunctions::copyAll (*this, src);
  2697. }
  2698. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2699. void writeAll (const CharPointer_UTF16& src) noexcept
  2700. {
  2701. const CharType* s = src.data;
  2702. while ((*data = *s) != 0)
  2703. {
  2704. ++data;
  2705. ++s;
  2706. }
  2707. }
  2708. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2709. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2710. to the destination buffer before stopping.
  2711. */
  2712. template <typename CharPointer>
  2713. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  2714. {
  2715. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2716. }
  2717. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2718. The maxChars parameter specifies the maximum number of characters that can be
  2719. written to the destination buffer before stopping (including the terminating null).
  2720. */
  2721. template <typename CharPointer>
  2722. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  2723. {
  2724. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2725. }
  2726. /** Compares this string with another one. */
  2727. template <typename CharPointer>
  2728. int compare (const CharPointer& other) const noexcept
  2729. {
  2730. return CharacterFunctions::compare (*this, other);
  2731. }
  2732. /** Compares this string with another one, up to a specified number of characters. */
  2733. template <typename CharPointer>
  2734. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  2735. {
  2736. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2737. }
  2738. /** Compares this string with another one. */
  2739. template <typename CharPointer>
  2740. int compareIgnoreCase (const CharPointer& other) const noexcept
  2741. {
  2742. return CharacterFunctions::compareIgnoreCase (*this, other);
  2743. }
  2744. /** Compares this string with another one, up to a specified number of characters. */
  2745. template <typename CharPointer>
  2746. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  2747. {
  2748. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2749. }
  2750. #if JUCE_WINDOWS && ! DOXYGEN
  2751. int compareIgnoreCase (const CharPointer_UTF16& other) const noexcept
  2752. {
  2753. return _wcsicmp (data, other.data);
  2754. }
  2755. int compareIgnoreCaseUpTo (const CharPointer_UTF16& other, int maxChars) const noexcept
  2756. {
  2757. return _wcsnicmp (data, other.data, maxChars);
  2758. }
  2759. int indexOf (const CharPointer_UTF16& stringToFind) const noexcept
  2760. {
  2761. const CharType* const t = wcsstr (data, stringToFind.getAddress());
  2762. return t == nullptr ? -1 : (int) (t - data);
  2763. }
  2764. #endif
  2765. /** Returns the character index of a substring, or -1 if it isn't found. */
  2766. template <typename CharPointer>
  2767. int indexOf (const CharPointer& stringToFind) const noexcept
  2768. {
  2769. return CharacterFunctions::indexOf (*this, stringToFind);
  2770. }
  2771. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2772. int indexOf (const juce_wchar charToFind) const noexcept
  2773. {
  2774. return CharacterFunctions::indexOfChar (*this, charToFind);
  2775. }
  2776. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2777. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  2778. {
  2779. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2780. : CharacterFunctions::indexOfChar (*this, charToFind);
  2781. }
  2782. /** Returns true if the first character of this string is whitespace. */
  2783. bool isWhitespace() const noexcept { return CharacterFunctions::isWhitespace (operator*()) != 0; }
  2784. /** Returns true if the first character of this string is a digit. */
  2785. bool isDigit() const noexcept { return CharacterFunctions::isDigit (operator*()) != 0; }
  2786. /** Returns true if the first character of this string is a letter. */
  2787. bool isLetter() const noexcept { return CharacterFunctions::isLetter (operator*()) != 0; }
  2788. /** Returns true if the first character of this string is a letter or digit. */
  2789. bool isLetterOrDigit() const noexcept { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2790. /** Returns true if the first character of this string is upper-case. */
  2791. bool isUpperCase() const noexcept { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2792. /** Returns true if the first character of this string is lower-case. */
  2793. bool isLowerCase() const noexcept { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2794. /** Returns an upper-case version of the first character of this string. */
  2795. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (operator*()); }
  2796. /** Returns a lower-case version of the first character of this string. */
  2797. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (operator*()); }
  2798. /** Parses this string as a 32-bit integer. */
  2799. int getIntValue32() const noexcept
  2800. {
  2801. #if JUCE_WINDOWS
  2802. return _wtoi (data);
  2803. #else
  2804. return CharacterFunctions::getIntValue <int, CharPointer_UTF16> (*this);
  2805. #endif
  2806. }
  2807. /** Parses this string as a 64-bit integer. */
  2808. int64 getIntValue64() const noexcept
  2809. {
  2810. #if JUCE_WINDOWS
  2811. return _wtoi64 (data);
  2812. #else
  2813. return CharacterFunctions::getIntValue <int64, CharPointer_UTF16> (*this);
  2814. #endif
  2815. }
  2816. /** Parses this string as a floating point double. */
  2817. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  2818. /** Returns the first non-whitespace character in the string. */
  2819. CharPointer_UTF16 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  2820. /** Returns true if the given unicode character can be represented in this encoding. */
  2821. static bool canRepresent (juce_wchar character) noexcept
  2822. {
  2823. return ((unsigned int) character) < (unsigned int) 0x10ffff
  2824. && (((unsigned int) character) < 0xd800 || ((unsigned int) character) > 0xdfff);
  2825. }
  2826. /** Returns true if this data contains a valid string in this encoding. */
  2827. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2828. {
  2829. maxBytesToRead /= sizeof (CharType);
  2830. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2831. {
  2832. const uint32 n = (uint32) (uint16) *dataToTest++;
  2833. if (n >= 0xd800)
  2834. {
  2835. if (n > 0x10ffff)
  2836. return false;
  2837. if (n <= 0xdfff)
  2838. {
  2839. if (n > 0xdc00)
  2840. return false;
  2841. const uint32 nextChar = (uint32) (uint16) *dataToTest++;
  2842. if (nextChar < 0xdc00 || nextChar > 0xdfff)
  2843. return false;
  2844. }
  2845. }
  2846. }
  2847. return true;
  2848. }
  2849. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2850. CharPointer_UTF16 atomicSwap (const CharPointer_UTF16& newValue)
  2851. {
  2852. return CharPointer_UTF16 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2853. }
  2854. /** These values are the byte-order-mark (BOM) values for a UTF-16 stream. */
  2855. enum
  2856. {
  2857. byteOrderMarkBE1 = 0xfe,
  2858. byteOrderMarkBE2 = 0xff,
  2859. byteOrderMarkLE1 = 0xff,
  2860. byteOrderMarkLE2 = 0xfe
  2861. };
  2862. private:
  2863. CharType* data;
  2864. static int findNullIndex (const CharType* const t) noexcept
  2865. {
  2866. int n = 0;
  2867. while (t[n] != 0)
  2868. ++n;
  2869. return n;
  2870. }
  2871. };
  2872. #endif // __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2873. /*** End of inlined file: juce_CharPointer_UTF16.h ***/
  2874. /*** Start of inlined file: juce_CharPointer_UTF32.h ***/
  2875. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2876. #define __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2877. /**
  2878. Wraps a pointer to a null-terminated UTF-32 character string, and provides
  2879. various methods to operate on the data.
  2880. @see CharPointer_UTF8, CharPointer_UTF16
  2881. */
  2882. class CharPointer_UTF32
  2883. {
  2884. public:
  2885. typedef juce_wchar CharType;
  2886. inline explicit CharPointer_UTF32 (const CharType* const rawPointer) noexcept
  2887. : data (const_cast <CharType*> (rawPointer))
  2888. {
  2889. }
  2890. inline CharPointer_UTF32 (const CharPointer_UTF32& other) noexcept
  2891. : data (other.data)
  2892. {
  2893. }
  2894. inline CharPointer_UTF32& operator= (const CharPointer_UTF32& other) noexcept
  2895. {
  2896. data = other.data;
  2897. return *this;
  2898. }
  2899. inline CharPointer_UTF32& operator= (const CharType* text) noexcept
  2900. {
  2901. data = const_cast <CharType*> (text);
  2902. return *this;
  2903. }
  2904. /** This is a pointer comparison, it doesn't compare the actual text. */
  2905. inline bool operator== (const CharPointer_UTF32& other) const noexcept { return data == other.data; }
  2906. inline bool operator!= (const CharPointer_UTF32& other) const noexcept { return data != other.data; }
  2907. inline bool operator<= (const CharPointer_UTF32& other) const noexcept { return data <= other.data; }
  2908. inline bool operator< (const CharPointer_UTF32& other) const noexcept { return data < other.data; }
  2909. inline bool operator>= (const CharPointer_UTF32& other) const noexcept { return data >= other.data; }
  2910. inline bool operator> (const CharPointer_UTF32& other) const noexcept { return data > other.data; }
  2911. /** Returns the address that this pointer is pointing to. */
  2912. inline CharType* getAddress() const noexcept { return data; }
  2913. /** Returns the address that this pointer is pointing to. */
  2914. inline operator const CharType*() const noexcept { return data; }
  2915. /** Returns true if this pointer is pointing to a null character. */
  2916. inline bool isEmpty() const noexcept { return *data == 0; }
  2917. /** Returns the unicode character that this pointer is pointing to. */
  2918. inline juce_wchar operator*() const noexcept { return *data; }
  2919. /** Moves this pointer along to the next character in the string. */
  2920. inline CharPointer_UTF32& operator++() noexcept
  2921. {
  2922. ++data;
  2923. return *this;
  2924. }
  2925. /** Moves this pointer to the previous character in the string. */
  2926. inline CharPointer_UTF32& operator--() noexcept
  2927. {
  2928. --data;
  2929. return *this;
  2930. }
  2931. /** Returns the character that this pointer is currently pointing to, and then
  2932. advances the pointer to point to the next character. */
  2933. inline juce_wchar getAndAdvance() noexcept { return *data++; }
  2934. /** Moves this pointer along to the next character in the string. */
  2935. CharPointer_UTF32 operator++ (int) noexcept
  2936. {
  2937. CharPointer_UTF32 temp (*this);
  2938. ++data;
  2939. return temp;
  2940. }
  2941. /** Moves this pointer forwards by the specified number of characters. */
  2942. inline void operator+= (const int numToSkip) noexcept
  2943. {
  2944. data += numToSkip;
  2945. }
  2946. inline void operator-= (const int numToSkip) noexcept
  2947. {
  2948. data -= numToSkip;
  2949. }
  2950. /** Returns the character at a given character index from the start of the string. */
  2951. inline juce_wchar& operator[] (const int characterIndex) const noexcept
  2952. {
  2953. return data [characterIndex];
  2954. }
  2955. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2956. CharPointer_UTF32 operator+ (const int numToSkip) const noexcept
  2957. {
  2958. return CharPointer_UTF32 (data + numToSkip);
  2959. }
  2960. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2961. CharPointer_UTF32 operator- (const int numToSkip) const noexcept
  2962. {
  2963. return CharPointer_UTF32 (data - numToSkip);
  2964. }
  2965. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2966. inline void write (const juce_wchar charToWrite) noexcept
  2967. {
  2968. *data++ = charToWrite;
  2969. }
  2970. inline void replaceChar (const juce_wchar newChar) noexcept
  2971. {
  2972. *data = newChar;
  2973. }
  2974. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2975. inline void writeNull() const noexcept
  2976. {
  2977. *data = 0;
  2978. }
  2979. /** Returns the number of characters in this string. */
  2980. size_t length() const noexcept
  2981. {
  2982. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  2983. return wcslen (data);
  2984. #else
  2985. size_t n = 0;
  2986. while (data[n] != 0)
  2987. ++n;
  2988. return n;
  2989. #endif
  2990. }
  2991. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2992. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  2993. {
  2994. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2995. }
  2996. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2997. size_t lengthUpTo (const CharPointer_UTF32& end) const noexcept
  2998. {
  2999. return CharacterFunctions::lengthUpTo (*this, end);
  3000. }
  3001. /** Returns the number of bytes that are used to represent this string.
  3002. This includes the terminating null character.
  3003. */
  3004. size_t sizeInBytes() const noexcept
  3005. {
  3006. return sizeof (CharType) * (length() + 1);
  3007. }
  3008. /** Returns the number of bytes that would be needed to represent the given
  3009. unicode character in this encoding format.
  3010. */
  3011. static inline size_t getBytesRequiredFor (const juce_wchar) noexcept
  3012. {
  3013. return sizeof (CharType);
  3014. }
  3015. /** Returns the number of bytes that would be needed to represent the given
  3016. string in this encoding format.
  3017. The value returned does NOT include the terminating null character.
  3018. */
  3019. template <class CharPointer>
  3020. static size_t getBytesRequiredFor (const CharPointer& text) noexcept
  3021. {
  3022. return sizeof (CharType) * text.length();
  3023. }
  3024. /** Returns a pointer to the null character that terminates this string. */
  3025. CharPointer_UTF32 findTerminatingNull() const noexcept
  3026. {
  3027. return CharPointer_UTF32 (data + length());
  3028. }
  3029. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3030. template <typename CharPointer>
  3031. void writeAll (const CharPointer& src) noexcept
  3032. {
  3033. CharacterFunctions::copyAll (*this, src);
  3034. }
  3035. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3036. void writeAll (const CharPointer_UTF32& src) noexcept
  3037. {
  3038. const CharType* s = src.data;
  3039. while ((*data = *s) != 0)
  3040. {
  3041. ++data;
  3042. ++s;
  3043. }
  3044. }
  3045. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3046. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3047. to the destination buffer before stopping.
  3048. */
  3049. template <typename CharPointer>
  3050. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  3051. {
  3052. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3053. }
  3054. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3055. The maxChars parameter specifies the maximum number of characters that can be
  3056. written to the destination buffer before stopping (including the terminating null).
  3057. */
  3058. template <typename CharPointer>
  3059. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  3060. {
  3061. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3062. }
  3063. /** Compares this string with another one. */
  3064. template <typename CharPointer>
  3065. int compare (const CharPointer& other) const noexcept
  3066. {
  3067. return CharacterFunctions::compare (*this, other);
  3068. }
  3069. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  3070. /** Compares this string with another one. */
  3071. int compare (const CharPointer_UTF32& other) const noexcept
  3072. {
  3073. return wcscmp (data, other.data);
  3074. }
  3075. #endif
  3076. /** Compares this string with another one, up to a specified number of characters. */
  3077. template <typename CharPointer>
  3078. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  3079. {
  3080. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3081. }
  3082. /** Compares this string with another one. */
  3083. template <typename CharPointer>
  3084. int compareIgnoreCase (const CharPointer& other) const
  3085. {
  3086. return CharacterFunctions::compareIgnoreCase (*this, other);
  3087. }
  3088. /** Compares this string with another one, up to a specified number of characters. */
  3089. template <typename CharPointer>
  3090. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  3091. {
  3092. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3093. }
  3094. /** Returns the character index of a substring, or -1 if it isn't found. */
  3095. template <typename CharPointer>
  3096. int indexOf (const CharPointer& stringToFind) const noexcept
  3097. {
  3098. return CharacterFunctions::indexOf (*this, stringToFind);
  3099. }
  3100. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3101. int indexOf (const juce_wchar charToFind) const noexcept
  3102. {
  3103. int i = 0;
  3104. while (data[i] != 0)
  3105. {
  3106. if (data[i] == charToFind)
  3107. return i;
  3108. ++i;
  3109. }
  3110. return -1;
  3111. }
  3112. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3113. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  3114. {
  3115. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3116. : CharacterFunctions::indexOfChar (*this, charToFind);
  3117. }
  3118. /** Returns true if the first character of this string is whitespace. */
  3119. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3120. /** Returns true if the first character of this string is a digit. */
  3121. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3122. /** Returns true if the first character of this string is a letter. */
  3123. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3124. /** Returns true if the first character of this string is a letter or digit. */
  3125. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3126. /** Returns true if the first character of this string is upper-case. */
  3127. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3128. /** Returns true if the first character of this string is lower-case. */
  3129. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3130. /** Returns an upper-case version of the first character of this string. */
  3131. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (*data); }
  3132. /** Returns a lower-case version of the first character of this string. */
  3133. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (*data); }
  3134. /** Parses this string as a 32-bit integer. */
  3135. int getIntValue32() const noexcept { return CharacterFunctions::getIntValue <int, CharPointer_UTF32> (*this); }
  3136. /** Parses this string as a 64-bit integer. */
  3137. int64 getIntValue64() const noexcept { return CharacterFunctions::getIntValue <int64, CharPointer_UTF32> (*this); }
  3138. /** Parses this string as a floating point double. */
  3139. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  3140. /** Returns the first non-whitespace character in the string. */
  3141. CharPointer_UTF32 findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  3142. /** Returns true if the given unicode character can be represented in this encoding. */
  3143. static bool canRepresent (juce_wchar character) noexcept
  3144. {
  3145. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  3146. }
  3147. /** Returns true if this data contains a valid string in this encoding. */
  3148. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3149. {
  3150. maxBytesToRead /= sizeof (CharType);
  3151. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  3152. if (! canRepresent (*dataToTest++))
  3153. return false;
  3154. return true;
  3155. }
  3156. /** Atomically swaps this pointer for a new value, returning the previous value. */
  3157. CharPointer_UTF32 atomicSwap (const CharPointer_UTF32& newValue)
  3158. {
  3159. return CharPointer_UTF32 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  3160. }
  3161. private:
  3162. CharType* data;
  3163. };
  3164. #endif // __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  3165. /*** End of inlined file: juce_CharPointer_UTF32.h ***/
  3166. /*** Start of inlined file: juce_CharPointer_ASCII.h ***/
  3167. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3168. #define __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3169. /**
  3170. Wraps a pointer to a null-terminated ASCII character string, and provides
  3171. various methods to operate on the data.
  3172. A valid ASCII string is assumed to not contain any characters above 127.
  3173. @see CharPointer_UTF8, CharPointer_UTF16, CharPointer_UTF32
  3174. */
  3175. class CharPointer_ASCII
  3176. {
  3177. public:
  3178. typedef char CharType;
  3179. inline explicit CharPointer_ASCII (const CharType* const rawPointer) noexcept
  3180. : data (const_cast <CharType*> (rawPointer))
  3181. {
  3182. }
  3183. inline CharPointer_ASCII (const CharPointer_ASCII& other) noexcept
  3184. : data (other.data)
  3185. {
  3186. }
  3187. inline CharPointer_ASCII& operator= (const CharPointer_ASCII& other) noexcept
  3188. {
  3189. data = other.data;
  3190. return *this;
  3191. }
  3192. inline CharPointer_ASCII& operator= (const CharType* text) noexcept
  3193. {
  3194. data = const_cast <CharType*> (text);
  3195. return *this;
  3196. }
  3197. /** This is a pointer comparison, it doesn't compare the actual text. */
  3198. inline bool operator== (const CharPointer_ASCII& other) const noexcept { return data == other.data; }
  3199. inline bool operator!= (const CharPointer_ASCII& other) const noexcept { return data != other.data; }
  3200. inline bool operator<= (const CharPointer_ASCII& other) const noexcept { return data <= other.data; }
  3201. inline bool operator< (const CharPointer_ASCII& other) const noexcept { return data < other.data; }
  3202. inline bool operator>= (const CharPointer_ASCII& other) const noexcept { return data >= other.data; }
  3203. inline bool operator> (const CharPointer_ASCII& other) const noexcept { return data > other.data; }
  3204. /** Returns the address that this pointer is pointing to. */
  3205. inline CharType* getAddress() const noexcept { return data; }
  3206. /** Returns the address that this pointer is pointing to. */
  3207. inline operator const CharType*() const noexcept { return data; }
  3208. /** Returns true if this pointer is pointing to a null character. */
  3209. inline bool isEmpty() const noexcept { return *data == 0; }
  3210. /** Returns the unicode character that this pointer is pointing to. */
  3211. inline juce_wchar operator*() const noexcept { return *data; }
  3212. /** Moves this pointer along to the next character in the string. */
  3213. inline CharPointer_ASCII& operator++() noexcept
  3214. {
  3215. ++data;
  3216. return *this;
  3217. }
  3218. /** Moves this pointer to the previous character in the string. */
  3219. inline CharPointer_ASCII& operator--() noexcept
  3220. {
  3221. --data;
  3222. return *this;
  3223. }
  3224. /** Returns the character that this pointer is currently pointing to, and then
  3225. advances the pointer to point to the next character. */
  3226. inline juce_wchar getAndAdvance() noexcept { return *data++; }
  3227. /** Moves this pointer along to the next character in the string. */
  3228. CharPointer_ASCII operator++ (int) noexcept
  3229. {
  3230. CharPointer_ASCII temp (*this);
  3231. ++data;
  3232. return temp;
  3233. }
  3234. /** Moves this pointer forwards by the specified number of characters. */
  3235. inline void operator+= (const int numToSkip) noexcept
  3236. {
  3237. data += numToSkip;
  3238. }
  3239. inline void operator-= (const int numToSkip) noexcept
  3240. {
  3241. data -= numToSkip;
  3242. }
  3243. /** Returns the character at a given character index from the start of the string. */
  3244. inline juce_wchar operator[] (const int characterIndex) const noexcept
  3245. {
  3246. return (juce_wchar) (unsigned char) data [characterIndex];
  3247. }
  3248. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  3249. CharPointer_ASCII operator+ (const int numToSkip) const noexcept
  3250. {
  3251. return CharPointer_ASCII (data + numToSkip);
  3252. }
  3253. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  3254. CharPointer_ASCII operator- (const int numToSkip) const noexcept
  3255. {
  3256. return CharPointer_ASCII (data - numToSkip);
  3257. }
  3258. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  3259. inline void write (const juce_wchar charToWrite) noexcept
  3260. {
  3261. *data++ = (char) charToWrite;
  3262. }
  3263. inline void replaceChar (const juce_wchar newChar) noexcept
  3264. {
  3265. *data = (char) newChar;
  3266. }
  3267. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  3268. inline void writeNull() const noexcept
  3269. {
  3270. *data = 0;
  3271. }
  3272. /** Returns the number of characters in this string. */
  3273. size_t length() const noexcept
  3274. {
  3275. return (size_t) strlen (data);
  3276. }
  3277. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  3278. size_t lengthUpTo (const size_t maxCharsToCount) const noexcept
  3279. {
  3280. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  3281. }
  3282. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  3283. size_t lengthUpTo (const CharPointer_ASCII& end) const noexcept
  3284. {
  3285. return CharacterFunctions::lengthUpTo (*this, end);
  3286. }
  3287. /** Returns the number of bytes that are used to represent this string.
  3288. This includes the terminating null character.
  3289. */
  3290. size_t sizeInBytes() const noexcept
  3291. {
  3292. return length() + 1;
  3293. }
  3294. /** Returns the number of bytes that would be needed to represent the given
  3295. unicode character in this encoding format.
  3296. */
  3297. static inline size_t getBytesRequiredFor (const juce_wchar) noexcept
  3298. {
  3299. return 1;
  3300. }
  3301. /** Returns the number of bytes that would be needed to represent the given
  3302. string in this encoding format.
  3303. The value returned does NOT include the terminating null character.
  3304. */
  3305. template <class CharPointer>
  3306. static size_t getBytesRequiredFor (const CharPointer& text) noexcept
  3307. {
  3308. return text.length();
  3309. }
  3310. /** Returns a pointer to the null character that terminates this string. */
  3311. CharPointer_ASCII findTerminatingNull() const noexcept
  3312. {
  3313. return CharPointer_ASCII (data + length());
  3314. }
  3315. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3316. template <typename CharPointer>
  3317. void writeAll (const CharPointer& src) noexcept
  3318. {
  3319. CharacterFunctions::copyAll (*this, src);
  3320. }
  3321. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3322. void writeAll (const CharPointer_ASCII& src) noexcept
  3323. {
  3324. strcpy (data, src.data);
  3325. }
  3326. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3327. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3328. to the destination buffer before stopping.
  3329. */
  3330. template <typename CharPointer>
  3331. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) noexcept
  3332. {
  3333. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3334. }
  3335. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3336. The maxChars parameter specifies the maximum number of characters that can be
  3337. written to the destination buffer before stopping (including the terminating null).
  3338. */
  3339. template <typename CharPointer>
  3340. void writeWithCharLimit (const CharPointer& src, const int maxChars) noexcept
  3341. {
  3342. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3343. }
  3344. /** Compares this string with another one. */
  3345. template <typename CharPointer>
  3346. int compare (const CharPointer& other) const noexcept
  3347. {
  3348. return CharacterFunctions::compare (*this, other);
  3349. }
  3350. /** Compares this string with another one. */
  3351. int compare (const CharPointer_ASCII& other) const noexcept
  3352. {
  3353. return strcmp (data, other.data);
  3354. }
  3355. /** Compares this string with another one, up to a specified number of characters. */
  3356. template <typename CharPointer>
  3357. int compareUpTo (const CharPointer& other, const int maxChars) const noexcept
  3358. {
  3359. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3360. }
  3361. /** Compares this string with another one, up to a specified number of characters. */
  3362. int compareUpTo (const CharPointer_ASCII& other, const int maxChars) const noexcept
  3363. {
  3364. return strncmp (data, other.data, (size_t) maxChars);
  3365. }
  3366. /** Compares this string with another one. */
  3367. template <typename CharPointer>
  3368. int compareIgnoreCase (const CharPointer& other) const
  3369. {
  3370. return CharacterFunctions::compareIgnoreCase (*this, other);
  3371. }
  3372. int compareIgnoreCase (const CharPointer_ASCII& other) const
  3373. {
  3374. #if JUCE_WINDOWS
  3375. return stricmp (data, other.data);
  3376. #else
  3377. return strcasecmp (data, other.data);
  3378. #endif
  3379. }
  3380. /** Compares this string with another one, up to a specified number of characters. */
  3381. template <typename CharPointer>
  3382. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const noexcept
  3383. {
  3384. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3385. }
  3386. /** Returns the character index of a substring, or -1 if it isn't found. */
  3387. template <typename CharPointer>
  3388. int indexOf (const CharPointer& stringToFind) const noexcept
  3389. {
  3390. return CharacterFunctions::indexOf (*this, stringToFind);
  3391. }
  3392. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3393. int indexOf (const juce_wchar charToFind) const noexcept
  3394. {
  3395. int i = 0;
  3396. while (data[i] != 0)
  3397. {
  3398. if (data[i] == (char) charToFind)
  3399. return i;
  3400. ++i;
  3401. }
  3402. return -1;
  3403. }
  3404. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3405. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const noexcept
  3406. {
  3407. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3408. : CharacterFunctions::indexOfChar (*this, charToFind);
  3409. }
  3410. /** Returns true if the first character of this string is whitespace. */
  3411. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3412. /** Returns true if the first character of this string is a digit. */
  3413. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3414. /** Returns true if the first character of this string is a letter. */
  3415. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3416. /** Returns true if the first character of this string is a letter or digit. */
  3417. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3418. /** Returns true if the first character of this string is upper-case. */
  3419. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3420. /** Returns true if the first character of this string is lower-case. */
  3421. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3422. /** Returns an upper-case version of the first character of this string. */
  3423. juce_wchar toUpperCase() const noexcept { return CharacterFunctions::toUpperCase (*data); }
  3424. /** Returns a lower-case version of the first character of this string. */
  3425. juce_wchar toLowerCase() const noexcept { return CharacterFunctions::toLowerCase (*data); }
  3426. /** Parses this string as a 32-bit integer. */
  3427. int getIntValue32() const noexcept { return atoi (data); }
  3428. /** Parses this string as a 64-bit integer. */
  3429. int64 getIntValue64() const noexcept
  3430. {
  3431. #if JUCE_LINUX || JUCE_ANDROID
  3432. return atoll (data);
  3433. #elif JUCE_WINDOWS
  3434. return _atoi64 (data);
  3435. #else
  3436. return CharacterFunctions::getIntValue <int64, CharPointer_ASCII> (*this);
  3437. #endif
  3438. }
  3439. /** Parses this string as a floating point double. */
  3440. double getDoubleValue() const noexcept { return CharacterFunctions::getDoubleValue (*this); }
  3441. /** Returns the first non-whitespace character in the string. */
  3442. CharPointer_ASCII findEndOfWhitespace() const noexcept { return CharacterFunctions::findEndOfWhitespace (*this); }
  3443. /** Returns true if the given unicode character can be represented in this encoding. */
  3444. static bool canRepresent (juce_wchar character) noexcept
  3445. {
  3446. return ((unsigned int) character) < (unsigned int) 128;
  3447. }
  3448. /** Returns true if this data contains a valid string in this encoding. */
  3449. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3450. {
  3451. while (--maxBytesToRead >= 0)
  3452. {
  3453. if (((signed char) *dataToTest) <= 0)
  3454. return *dataToTest == 0;
  3455. ++dataToTest;
  3456. }
  3457. return true;
  3458. }
  3459. private:
  3460. CharType* data;
  3461. };
  3462. #endif // __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3463. /*** End of inlined file: juce_CharPointer_ASCII.h ***/
  3464. #if JUCE_MSVC
  3465. #pragma warning (pop)
  3466. #endif
  3467. class OutputStream;
  3468. /**
  3469. The JUCE String class!
  3470. Using a reference-counted internal representation, these strings are fast
  3471. and efficient, and there are methods to do just about any operation you'll ever
  3472. dream of.
  3473. @see StringArray, StringPairArray
  3474. */
  3475. class JUCE_API String
  3476. {
  3477. public:
  3478. /** Creates an empty string.
  3479. @see empty
  3480. */
  3481. String() noexcept;
  3482. /** Creates a copy of another string. */
  3483. String (const String& other) noexcept;
  3484. /** Creates a string from a zero-terminated ascii text string.
  3485. The string passed-in must not contain any characters with a value above 127, because
  3486. these can't be converted to unicode without knowing the original encoding that was
  3487. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3488. assertion.
  3489. To create strings with extended characters from UTF-8, you should explicitly call
  3490. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3491. use UTF-8 with escape characters in your source code to represent extended characters,
  3492. because there's no other way to represent unicode strings in a way that isn't dependent
  3493. on the compiler, source code editor and platform.
  3494. */
  3495. String (const char* text);
  3496. /** Creates a string from a string of 8-bit ascii characters.
  3497. The string passed-in must not contain any characters with a value above 127, because
  3498. these can't be converted to unicode without knowing the original encoding that was
  3499. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3500. assertion.
  3501. To create strings with extended characters from UTF-8, you should explicitly call
  3502. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3503. use UTF-8 with escape characters in your source code to represent extended characters,
  3504. because there's no other way to represent unicode strings in a way that isn't dependent
  3505. on the compiler, source code editor and platform.
  3506. This will use up the the first maxChars characters of the string (or less if the string
  3507. is actually shorter).
  3508. */
  3509. String (const char* text, size_t maxChars);
  3510. /** Creates a string from a whcar_t character string.
  3511. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3512. */
  3513. String (const wchar_t* text);
  3514. /** Creates a string from a whcar_t character string.
  3515. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3516. */
  3517. String (const wchar_t* text, size_t maxChars);
  3518. /** Creates a string from a UTF-8 character string */
  3519. String (const CharPointer_UTF8& text);
  3520. /** Creates a string from a UTF-8 character string */
  3521. String (const CharPointer_UTF8& text, size_t maxChars);
  3522. /** Creates a string from a UTF-8 character string */
  3523. String (const CharPointer_UTF8& start, const CharPointer_UTF8& end);
  3524. /** Creates a string from a UTF-16 character string */
  3525. String (const CharPointer_UTF16& text);
  3526. /** Creates a string from a UTF-16 character string */
  3527. String (const CharPointer_UTF16& text, size_t maxChars);
  3528. /** Creates a string from a UTF-16 character string */
  3529. String (const CharPointer_UTF16& start, const CharPointer_UTF16& end);
  3530. /** Creates a string from a UTF-32 character string */
  3531. String (const CharPointer_UTF32& text);
  3532. /** Creates a string from a UTF-32 character string */
  3533. String (const CharPointer_UTF32& text, size_t maxChars);
  3534. /** Creates a string from a UTF-32 character string */
  3535. String (const CharPointer_UTF32& start, const CharPointer_UTF32& end);
  3536. /** Creates a string from an ASCII character string */
  3537. String (const CharPointer_ASCII& text);
  3538. /** Creates a string from a single character. */
  3539. static String charToString (juce_wchar character);
  3540. /** Destructor. */
  3541. ~String() noexcept;
  3542. /** This is an empty string that can be used whenever one is needed.
  3543. It's better to use this than String() because it explains what's going on
  3544. and is more efficient.
  3545. */
  3546. static const String empty;
  3547. /** This is the character encoding type used internally to store the string.
  3548. By setting the value of JUCE_STRING_UTF_TYPE to 8, 16, or 32, you can change the
  3549. internal storage format of the String class. UTF-8 uses the least space (if your strings
  3550. contain few extended characters), but call operator[] involves iterating the string to find
  3551. the required index. UTF-32 provides instant random access to its characters, but uses 4 bytes
  3552. per character to store them. UTF-16 uses more space than UTF-8 and is also slow to index,
  3553. but is the native wchar_t format used in Windows.
  3554. It doesn't matter too much which format you pick, because the toUTF8(), toUTF16() and
  3555. toUTF32() methods let you access the string's content in any of the other formats.
  3556. */
  3557. #if (JUCE_STRING_UTF_TYPE == 32)
  3558. typedef CharPointer_UTF32 CharPointerType;
  3559. #elif (JUCE_STRING_UTF_TYPE == 16)
  3560. typedef CharPointer_UTF16 CharPointerType;
  3561. #elif (JUCE_STRING_UTF_TYPE == 8)
  3562. typedef CharPointer_UTF8 CharPointerType;
  3563. #else
  3564. #error "You must set the value of JUCE_STRING_UTF_TYPE to be either 8, 16, or 32!"
  3565. #endif
  3566. /** Generates a probably-unique 32-bit hashcode from this string. */
  3567. int hashCode() const noexcept;
  3568. /** Generates a probably-unique 64-bit hashcode from this string. */
  3569. int64 hashCode64() const noexcept;
  3570. /** Returns the number of characters in the string. */
  3571. int length() const noexcept;
  3572. // Assignment and concatenation operators..
  3573. /** Replaces this string's contents with another string. */
  3574. String& operator= (const String& other) noexcept;
  3575. /** Appends another string at the end of this one. */
  3576. String& operator+= (const String& stringToAppend);
  3577. /** Appends another string at the end of this one. */
  3578. String& operator+= (const char* textToAppend);
  3579. /** Appends another string at the end of this one. */
  3580. String& operator+= (const wchar_t* textToAppend);
  3581. /** Appends a decimal number at the end of this string. */
  3582. String& operator+= (int numberToAppend);
  3583. /** Appends a character at the end of this string. */
  3584. String& operator+= (char characterToAppend);
  3585. /** Appends a character at the end of this string. */
  3586. String& operator+= (wchar_t characterToAppend);
  3587. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  3588. /** Appends a character at the end of this string. */
  3589. String& operator+= (juce_wchar characterToAppend);
  3590. #endif
  3591. /** Appends a string to the end of this one.
  3592. @param textToAppend the string to add
  3593. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3594. */
  3595. void append (const String& textToAppend, size_t maxCharsToTake);
  3596. /** Appends a string to the end of this one.
  3597. @param textToAppend the string to add
  3598. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3599. */
  3600. template <class CharPointer>
  3601. void appendCharPointer (const CharPointer& textToAppend, size_t maxCharsToTake)
  3602. {
  3603. if (textToAppend.getAddress() != nullptr)
  3604. {
  3605. size_t extraBytesNeeded = 0;
  3606. size_t numChars = 0;
  3607. for (CharPointer t (textToAppend); numChars < maxCharsToTake && ! t.isEmpty();)
  3608. {
  3609. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3610. ++numChars;
  3611. }
  3612. if (numChars > 0)
  3613. {
  3614. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3615. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3616. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeWithCharLimit (textToAppend, (int) (numChars + 1));
  3617. }
  3618. }
  3619. }
  3620. /** Appends a string to the end of this one. */
  3621. template <class CharPointer>
  3622. void appendCharPointer (const CharPointer& textToAppend)
  3623. {
  3624. if (textToAppend.getAddress() != nullptr)
  3625. {
  3626. size_t extraBytesNeeded = 0;
  3627. for (CharPointer t (textToAppend); ! t.isEmpty();)
  3628. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3629. if (extraBytesNeeded > 0)
  3630. {
  3631. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3632. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3633. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeAll (textToAppend);
  3634. }
  3635. }
  3636. }
  3637. // Comparison methods..
  3638. /** Returns true if the string contains no characters.
  3639. Note that there's also an isNotEmpty() method to help write readable code.
  3640. @see containsNonWhitespaceChars()
  3641. */
  3642. inline bool isEmpty() const noexcept { return text[0] == 0; }
  3643. /** Returns true if the string contains at least one character.
  3644. Note that there's also an isEmpty() method to help write readable code.
  3645. @see containsNonWhitespaceChars()
  3646. */
  3647. inline bool isNotEmpty() const noexcept { return text[0] != 0; }
  3648. /** Case-insensitive comparison with another string. */
  3649. bool equalsIgnoreCase (const String& other) const noexcept;
  3650. /** Case-insensitive comparison with another string. */
  3651. bool equalsIgnoreCase (const wchar_t* other) const noexcept;
  3652. /** Case-insensitive comparison with another string. */
  3653. bool equalsIgnoreCase (const char* other) const noexcept;
  3654. /** Case-sensitive comparison with another string.
  3655. @returns 0 if the two strings are identical; negative if this string comes before
  3656. the other one alphabetically, or positive if it comes after it.
  3657. */
  3658. int compare (const String& other) const noexcept;
  3659. /** Case-sensitive comparison with another string.
  3660. @returns 0 if the two strings are identical; negative if this string comes before
  3661. the other one alphabetically, or positive if it comes after it.
  3662. */
  3663. int compare (const char* other) const noexcept;
  3664. /** Case-sensitive comparison with another string.
  3665. @returns 0 if the two strings are identical; negative if this string comes before
  3666. the other one alphabetically, or positive if it comes after it.
  3667. */
  3668. int compare (const wchar_t* other) const noexcept;
  3669. /** Case-insensitive comparison with another string.
  3670. @returns 0 if the two strings are identical; negative if this string comes before
  3671. the other one alphabetically, or positive if it comes after it.
  3672. */
  3673. int compareIgnoreCase (const String& other) const noexcept;
  3674. /** Lexicographic comparison with another string.
  3675. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  3676. characters, making it good for sorting human-readable strings.
  3677. @returns 0 if the two strings are identical; negative if this string comes before
  3678. the other one alphabetically, or positive if it comes after it.
  3679. */
  3680. int compareLexicographically (const String& other) const noexcept;
  3681. /** Tests whether the string begins with another string.
  3682. If the parameter is an empty string, this will always return true.
  3683. Uses a case-sensitive comparison.
  3684. */
  3685. bool startsWith (const String& text) const noexcept;
  3686. /** Tests whether the string begins with a particular character.
  3687. If the character is 0, this will always return false.
  3688. Uses a case-sensitive comparison.
  3689. */
  3690. bool startsWithChar (juce_wchar character) const noexcept;
  3691. /** Tests whether the string begins with another string.
  3692. If the parameter is an empty string, this will always return true.
  3693. Uses a case-insensitive comparison.
  3694. */
  3695. bool startsWithIgnoreCase (const String& text) const noexcept;
  3696. /** Tests whether the string ends with another string.
  3697. If the parameter is an empty string, this will always return true.
  3698. Uses a case-sensitive comparison.
  3699. */
  3700. bool endsWith (const String& text) const noexcept;
  3701. /** Tests whether the string ends with a particular character.
  3702. If the character is 0, this will always return false.
  3703. Uses a case-sensitive comparison.
  3704. */
  3705. bool endsWithChar (juce_wchar character) const noexcept;
  3706. /** Tests whether the string ends with another string.
  3707. If the parameter is an empty string, this will always return true.
  3708. Uses a case-insensitive comparison.
  3709. */
  3710. bool endsWithIgnoreCase (const String& text) const noexcept;
  3711. /** Tests whether the string contains another substring.
  3712. If the parameter is an empty string, this will always return true.
  3713. Uses a case-sensitive comparison.
  3714. */
  3715. bool contains (const String& text) const noexcept;
  3716. /** Tests whether the string contains a particular character.
  3717. Uses a case-sensitive comparison.
  3718. */
  3719. bool containsChar (juce_wchar character) const noexcept;
  3720. /** Tests whether the string contains another substring.
  3721. Uses a case-insensitive comparison.
  3722. */
  3723. bool containsIgnoreCase (const String& text) const noexcept;
  3724. /** Tests whether the string contains another substring as a distict word.
  3725. @returns true if the string contains this word, surrounded by
  3726. non-alphanumeric characters
  3727. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3728. */
  3729. bool containsWholeWord (const String& wordToLookFor) const noexcept;
  3730. /** Tests whether the string contains another substring as a distict word.
  3731. @returns true if the string contains this word, surrounded by
  3732. non-alphanumeric characters
  3733. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3734. */
  3735. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const noexcept;
  3736. /** Finds an instance of another substring if it exists as a distict word.
  3737. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3738. then this will return the index of the start of the substring. If it isn't
  3739. found, then it will return -1
  3740. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3741. */
  3742. int indexOfWholeWord (const String& wordToLookFor) const noexcept;
  3743. /** Finds an instance of another substring if it exists as a distict word.
  3744. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3745. then this will return the index of the start of the substring. If it isn't
  3746. found, then it will return -1
  3747. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3748. */
  3749. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const noexcept;
  3750. /** Looks for any of a set of characters in the string.
  3751. Uses a case-sensitive comparison.
  3752. @returns true if the string contains any of the characters from
  3753. the string that is passed in.
  3754. */
  3755. bool containsAnyOf (const String& charactersItMightContain) const noexcept;
  3756. /** Looks for a set of characters in the string.
  3757. Uses a case-sensitive comparison.
  3758. @returns Returns false if any of the characters in this string do not occur in
  3759. the parameter string. If this string is empty, the return value will
  3760. always be true.
  3761. */
  3762. bool containsOnly (const String& charactersItMightContain) const noexcept;
  3763. /** Returns true if this string contains any non-whitespace characters.
  3764. This will return false if the string contains only whitespace characters, or
  3765. if it's empty.
  3766. It is equivalent to calling "myString.trim().isNotEmpty()".
  3767. */
  3768. bool containsNonWhitespaceChars() const noexcept;
  3769. /** Returns true if the string matches this simple wildcard expression.
  3770. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  3771. This isn't a full-blown regex though! The only wildcard characters supported
  3772. are "*" and "?". It's mainly intended for filename pattern matching.
  3773. */
  3774. bool matchesWildcard (const String& wildcard, bool ignoreCase) const noexcept;
  3775. // Substring location methods..
  3776. /** Searches for a character inside this string.
  3777. Uses a case-sensitive comparison.
  3778. @returns the index of the first occurrence of the character in this
  3779. string, or -1 if it's not found.
  3780. */
  3781. int indexOfChar (juce_wchar characterToLookFor) const noexcept;
  3782. /** Searches for a character inside this string.
  3783. Uses a case-sensitive comparison.
  3784. @param startIndex the index from which the search should proceed
  3785. @param characterToLookFor the character to look for
  3786. @returns the index of the first occurrence of the character in this
  3787. string, or -1 if it's not found.
  3788. */
  3789. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const noexcept;
  3790. /** Returns the index of the first character that matches one of the characters
  3791. passed-in to this method.
  3792. This scans the string, beginning from the startIndex supplied, and if it finds
  3793. a character that appears in the string charactersToLookFor, it returns its index.
  3794. If none of these characters are found, it returns -1.
  3795. If ignoreCase is true, the comparison will be case-insensitive.
  3796. @see indexOfChar, lastIndexOfAnyOf
  3797. */
  3798. int indexOfAnyOf (const String& charactersToLookFor,
  3799. int startIndex = 0,
  3800. bool ignoreCase = false) const noexcept;
  3801. /** Searches for a substring within this string.
  3802. Uses a case-sensitive comparison.
  3803. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3804. If textToLookFor is an empty string, this will always return 0.
  3805. */
  3806. int indexOf (const String& textToLookFor) const noexcept;
  3807. /** Searches for a substring within this string.
  3808. Uses a case-sensitive comparison.
  3809. @param startIndex the index from which the search should proceed
  3810. @param textToLookFor the string to search for
  3811. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3812. If textToLookFor is an empty string, this will always return -1.
  3813. */
  3814. int indexOf (int startIndex, const String& textToLookFor) const noexcept;
  3815. /** Searches for a substring within this string.
  3816. Uses a case-insensitive comparison.
  3817. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3818. If textToLookFor is an empty string, this will always return 0.
  3819. */
  3820. int indexOfIgnoreCase (const String& textToLookFor) const noexcept;
  3821. /** Searches for a substring within this string.
  3822. Uses a case-insensitive comparison.
  3823. @param startIndex the index from which the search should proceed
  3824. @param textToLookFor the string to search for
  3825. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3826. If textToLookFor is an empty string, this will always return -1.
  3827. */
  3828. int indexOfIgnoreCase (int startIndex, const String& textToLookFor) const noexcept;
  3829. /** Searches for a character inside this string (working backwards from the end of the string).
  3830. Uses a case-sensitive comparison.
  3831. @returns the index of the last occurrence of the character in this string, or -1 if it's not found.
  3832. */
  3833. int lastIndexOfChar (juce_wchar character) const noexcept;
  3834. /** Searches for a substring inside this string (working backwards from the end of the string).
  3835. Uses a case-sensitive comparison.
  3836. @returns the index of the start of the last occurrence of the substring within this string,
  3837. or -1 if it's not found. If textToLookFor is an empty string, this will always return -1.
  3838. */
  3839. int lastIndexOf (const String& textToLookFor) const noexcept;
  3840. /** Searches for a substring inside this string (working backwards from the end of the string).
  3841. Uses a case-insensitive comparison.
  3842. @returns the index of the start of the last occurrence of the substring within this string, or -1
  3843. if it's not found. If textToLookFor is an empty string, this will always return -1.
  3844. */
  3845. int lastIndexOfIgnoreCase (const String& textToLookFor) const noexcept;
  3846. /** Returns the index of the last character in this string that matches one of the
  3847. characters passed-in to this method.
  3848. This scans the string backwards, starting from its end, and if it finds
  3849. a character that appears in the string charactersToLookFor, it returns its index.
  3850. If none of these characters are found, it returns -1.
  3851. If ignoreCase is true, the comparison will be case-insensitive.
  3852. @see lastIndexOf, indexOfAnyOf
  3853. */
  3854. int lastIndexOfAnyOf (const String& charactersToLookFor,
  3855. bool ignoreCase = false) const noexcept;
  3856. // Substring extraction and manipulation methods..
  3857. /** Returns the character at this index in the string.
  3858. In a release build, no checks are made to see if the index is within a valid range, so be
  3859. careful! In a debug build, the index is checked and an assertion fires if it's out-of-range.
  3860. Also beware that depending on the encoding format that the string is using internally, this
  3861. method may execute in either O(1) or O(n) time, so be careful when using it in your algorithms.
  3862. If you're scanning through a string to inspect its characters, you should never use this operator
  3863. for random access, it's far more efficient to call getCharPointer() to return a pointer, and
  3864. then to use that to iterate the string.
  3865. @see getCharPointer
  3866. */
  3867. const juce_wchar operator[] (int index) const noexcept;
  3868. /** Returns the final character of the string.
  3869. If the string is empty this will return 0.
  3870. */
  3871. juce_wchar getLastCharacter() const noexcept;
  3872. /** Returns a subsection of the string.
  3873. If the range specified is beyond the limits of the string, as much as
  3874. possible is returned.
  3875. @param startIndex the index of the start of the substring needed
  3876. @param endIndex all characters from startIndex up to (but not including)
  3877. this index are returned
  3878. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  3879. */
  3880. String substring (int startIndex, int endIndex) const;
  3881. /** Returns a section of the string, starting from a given position.
  3882. @param startIndex the first character to include. If this is beyond the end
  3883. of the string, an empty string is returned. If it is zero or
  3884. less, the whole string is returned.
  3885. @returns the substring from startIndex up to the end of the string
  3886. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  3887. */
  3888. String substring (int startIndex) const;
  3889. /** Returns a version of this string with a number of characters removed
  3890. from the end.
  3891. @param numberToDrop the number of characters to drop from the end of the
  3892. string. If this is greater than the length of the string,
  3893. an empty string will be returned. If zero or less, the
  3894. original string will be returned.
  3895. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  3896. */
  3897. String dropLastCharacters (int numberToDrop) const;
  3898. /** Returns a number of characters from the end of the string.
  3899. This returns the last numCharacters characters from the end of the string. If the
  3900. string is shorter than numCharacters, the whole string is returned.
  3901. @see substring, dropLastCharacters, getLastCharacter
  3902. */
  3903. String getLastCharacters (int numCharacters) const;
  3904. /** Returns a section of the string starting from a given substring.
  3905. This will search for the first occurrence of the given substring, and
  3906. return the section of the string starting from the point where this is
  3907. found (optionally not including the substring itself).
  3908. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  3909. fromFirstOccurrenceOf ("34", false) would return "56".
  3910. If the substring isn't found, the method will return an empty string.
  3911. If ignoreCase is true, the comparison will be case-insensitive.
  3912. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  3913. */
  3914. String fromFirstOccurrenceOf (const String& substringToStartFrom,
  3915. bool includeSubStringInResult,
  3916. bool ignoreCase) const;
  3917. /** Returns a section of the string starting from the last occurrence of a given substring.
  3918. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  3919. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  3920. return the whole of the original string.
  3921. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  3922. */
  3923. String fromLastOccurrenceOf (const String& substringToFind,
  3924. bool includeSubStringInResult,
  3925. bool ignoreCase) const;
  3926. /** Returns the start of this string, up to the first occurrence of a substring.
  3927. This will search for the first occurrence of a given substring, and then
  3928. return a copy of the string, up to the position of this substring,
  3929. optionally including or excluding the substring itself in the result.
  3930. e.g. for the string "123456", upTo ("34", false) would return "12", and
  3931. upTo ("34", true) would return "1234".
  3932. If the substring isn't found, this will return the whole of the original string.
  3933. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  3934. */
  3935. String upToFirstOccurrenceOf (const String& substringToEndWith,
  3936. bool includeSubStringInResult,
  3937. bool ignoreCase) const;
  3938. /** Returns the start of this string, up to the last occurrence of a substring.
  3939. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  3940. If the substring isn't found, this will return the whole of the original string.
  3941. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  3942. */
  3943. String upToLastOccurrenceOf (const String& substringToFind,
  3944. bool includeSubStringInResult,
  3945. bool ignoreCase) const;
  3946. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  3947. String trim() const;
  3948. /** Returns a copy of this string with any whitespace characters removed from the start. */
  3949. String trimStart() const;
  3950. /** Returns a copy of this string with any whitespace characters removed from the end. */
  3951. String trimEnd() const;
  3952. /** Returns a copy of this string, having removed a specified set of characters from its start.
  3953. Characters are removed from the start of the string until it finds one that is not in the
  3954. specified set, and then it stops.
  3955. @param charactersToTrim the set of characters to remove.
  3956. @see trim, trimStart, trimCharactersAtEnd
  3957. */
  3958. String trimCharactersAtStart (const String& charactersToTrim) const;
  3959. /** Returns a copy of this string, having removed a specified set of characters from its end.
  3960. Characters are removed from the end of the string until it finds one that is not in the
  3961. specified set, and then it stops.
  3962. @param charactersToTrim the set of characters to remove.
  3963. @see trim, trimEnd, trimCharactersAtStart
  3964. */
  3965. String trimCharactersAtEnd (const String& charactersToTrim) const;
  3966. /** Returns an upper-case version of this string. */
  3967. String toUpperCase() const;
  3968. /** Returns an lower-case version of this string. */
  3969. String toLowerCase() const;
  3970. /** Replaces a sub-section of the string with another string.
  3971. This will return a copy of this string, with a set of characters
  3972. from startIndex to startIndex + numCharsToReplace removed, and with
  3973. a new string inserted in their place.
  3974. Note that this is a const method, and won't alter the string itself.
  3975. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  3976. it will be constrained to a valid range.
  3977. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  3978. characters will be taken out.
  3979. @param stringToInsert the new string to insert at startIndex after the characters have been
  3980. removed.
  3981. */
  3982. String replaceSection (int startIndex,
  3983. int numCharactersToReplace,
  3984. const String& stringToInsert) const;
  3985. /** Replaces all occurrences of a substring with another string.
  3986. Returns a copy of this string, with any occurrences of stringToReplace
  3987. swapped for stringToInsertInstead.
  3988. Note that this is a const method, and won't alter the string itself.
  3989. */
  3990. String replace (const String& stringToReplace,
  3991. const String& stringToInsertInstead,
  3992. bool ignoreCase = false) const;
  3993. /** Returns a string with all occurrences of a character replaced with a different one. */
  3994. String replaceCharacter (juce_wchar characterToReplace,
  3995. juce_wchar characterToInsertInstead) const;
  3996. /** Replaces a set of characters with another set.
  3997. Returns a string in which each character from charactersToReplace has been replaced
  3998. by the character at the equivalent position in newCharacters (so the two strings
  3999. passed in must be the same length).
  4000. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  4001. Note that this is a const method, and won't affect the string itself.
  4002. */
  4003. String replaceCharacters (const String& charactersToReplace,
  4004. const String& charactersToInsertInstead) const;
  4005. /** Returns a version of this string that only retains a fixed set of characters.
  4006. This will return a copy of this string, omitting any characters which are not
  4007. found in the string passed-in.
  4008. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  4009. Note that this is a const method, and won't alter the string itself.
  4010. */
  4011. String retainCharacters (const String& charactersToRetain) const;
  4012. /** Returns a version of this string with a set of characters removed.
  4013. This will return a copy of this string, omitting any characters which are
  4014. found in the string passed-in.
  4015. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  4016. Note that this is a const method, and won't alter the string itself.
  4017. */
  4018. String removeCharacters (const String& charactersToRemove) const;
  4019. /** Returns a section from the start of the string that only contains a certain set of characters.
  4020. This returns the leftmost section of the string, up to (and not including) the
  4021. first character that doesn't appear in the string passed in.
  4022. */
  4023. String initialSectionContainingOnly (const String& permittedCharacters) const;
  4024. /** Returns a section from the start of the string that only contains a certain set of characters.
  4025. This returns the leftmost section of the string, up to (and not including) the
  4026. first character that occurs in the string passed in. (If none of the specified
  4027. characters are found in the string, the return value will just be the original string).
  4028. */
  4029. String initialSectionNotContaining (const String& charactersToStopAt) const;
  4030. /** Checks whether the string might be in quotation marks.
  4031. @returns true if the string begins with a quote character (either a double or single quote).
  4032. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  4033. @see unquoted, quoted
  4034. */
  4035. bool isQuotedString() const;
  4036. /** Removes quotation marks from around the string, (if there are any).
  4037. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  4038. at the ends of the string are not affected. If there aren't any quotes, the original string
  4039. is returned.
  4040. Note that this is a const method, and won't alter the string itself.
  4041. @see isQuotedString, quoted
  4042. */
  4043. String unquoted() const;
  4044. /** Adds quotation marks around a string.
  4045. This will return a copy of the string with a quote at the start and end, (but won't
  4046. add the quote if there's already one there, so it's safe to call this on strings that
  4047. may already have quotes around them).
  4048. Note that this is a const method, and won't alter the string itself.
  4049. @param quoteCharacter the character to add at the start and end
  4050. @see isQuotedString, unquoted
  4051. */
  4052. String quoted (juce_wchar quoteCharacter = '"') const;
  4053. /** Creates a string which is a version of a string repeated and joined together.
  4054. @param stringToRepeat the string to repeat
  4055. @param numberOfTimesToRepeat how many times to repeat it
  4056. */
  4057. static String repeatedString (const String& stringToRepeat,
  4058. int numberOfTimesToRepeat);
  4059. /** Returns a copy of this string with the specified character repeatedly added to its
  4060. beginning until the total length is at least the minimum length specified.
  4061. */
  4062. String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  4063. /** Returns a copy of this string with the specified character repeatedly added to its
  4064. end until the total length is at least the minimum length specified.
  4065. */
  4066. String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  4067. /** Creates a string from data in an unknown format.
  4068. This looks at some binary data and tries to guess whether it's Unicode
  4069. or 8-bit characters, then returns a string that represents it correctly.
  4070. Should be able to handle Unicode endianness correctly, by looking at
  4071. the first two bytes.
  4072. */
  4073. static String createStringFromData (const void* data, int size);
  4074. /** Creates a String from a printf-style parameter list.
  4075. I don't like this method. I don't use it myself, and I recommend avoiding it and
  4076. using the operator<< methods or pretty much anything else instead. It's only provided
  4077. here because of the popular unrest that was stirred-up when I tried to remove it...
  4078. If you're really determined to use it, at least make sure that you never, ever,
  4079. pass any String objects to it as parameters. And bear in mind that internally, depending
  4080. on the platform, it may be using wchar_t or char character types, so that even string
  4081. literals can't be safely used as parameters if you're writing portable code.
  4082. */
  4083. static String formatted (const String formatString, ... );
  4084. // Numeric conversions..
  4085. /** Creates a string containing this signed 32-bit integer as a decimal number.
  4086. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4087. */
  4088. explicit String (int decimalInteger);
  4089. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  4090. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4091. */
  4092. explicit String (unsigned int decimalInteger);
  4093. /** Creates a string containing this signed 16-bit integer as a decimal number.
  4094. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4095. */
  4096. explicit String (short decimalInteger);
  4097. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  4098. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4099. */
  4100. explicit String (unsigned short decimalInteger);
  4101. /** Creates a string containing this signed 64-bit integer as a decimal number.
  4102. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4103. */
  4104. explicit String (int64 largeIntegerValue);
  4105. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  4106. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4107. */
  4108. explicit String (uint64 largeIntegerValue);
  4109. /** Creates a string representing this floating-point number.
  4110. @param floatValue the value to convert to a string
  4111. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4112. decimal places, and will not use exponent notation. If 0 or
  4113. less, it will use exponent notation if necessary.
  4114. @see getDoubleValue, getIntValue
  4115. */
  4116. explicit String (float floatValue,
  4117. int numberOfDecimalPlaces = 0);
  4118. /** Creates a string representing this floating-point number.
  4119. @param doubleValue the value to convert to a string
  4120. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4121. decimal places, and will not use exponent notation. If 0 or
  4122. less, it will use exponent notation if necessary.
  4123. @see getFloatValue, getIntValue
  4124. */
  4125. explicit String (double doubleValue,
  4126. int numberOfDecimalPlaces = 0);
  4127. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  4128. @returns the value of the string as a 32 bit signed base-10 integer.
  4129. @see getTrailingIntValue, getHexValue32, getHexValue64
  4130. */
  4131. int getIntValue() const noexcept;
  4132. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  4133. @returns the value of the string as a 64 bit signed base-10 integer.
  4134. */
  4135. int64 getLargeIntValue() const noexcept;
  4136. /** Parses a decimal number from the end of the string.
  4137. This will look for a value at the end of the string.
  4138. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  4139. Negative numbers are not handled, so "xyz-5" returns 5.
  4140. @see getIntValue
  4141. */
  4142. int getTrailingIntValue() const noexcept;
  4143. /** Parses this string as a floating point number.
  4144. @returns the value of the string as a 32-bit floating point value.
  4145. @see getDoubleValue
  4146. */
  4147. float getFloatValue() const noexcept;
  4148. /** Parses this string as a floating point number.
  4149. @returns the value of the string as a 64-bit floating point value.
  4150. @see getFloatValue
  4151. */
  4152. double getDoubleValue() const noexcept;
  4153. /** Parses the string as a hexadecimal number.
  4154. Non-hexadecimal characters in the string are ignored.
  4155. If the string contains too many characters, then the lowest significant
  4156. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  4157. @returns a 32-bit number which is the value of the string in hex.
  4158. */
  4159. int getHexValue32() const noexcept;
  4160. /** Parses the string as a hexadecimal number.
  4161. Non-hexadecimal characters in the string are ignored.
  4162. If the string contains too many characters, then the lowest significant
  4163. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  4164. @returns a 64-bit number which is the value of the string in hex.
  4165. */
  4166. int64 getHexValue64() const noexcept;
  4167. /** Creates a string representing this 32-bit value in hexadecimal. */
  4168. static String toHexString (int number);
  4169. /** Creates a string representing this 64-bit value in hexadecimal. */
  4170. static String toHexString (int64 number);
  4171. /** Creates a string representing this 16-bit value in hexadecimal. */
  4172. static String toHexString (short number);
  4173. /** Creates a string containing a hex dump of a block of binary data.
  4174. @param data the binary data to use as input
  4175. @param size how many bytes of data to use
  4176. @param groupSize how many bytes are grouped together before inserting a
  4177. space into the output. e.g. group size 0 has no spaces,
  4178. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  4179. like "bea1 c2ff".
  4180. */
  4181. static String toHexString (const void* data, int size, int groupSize = 1);
  4182. /** Returns the character pointer currently being used to store this string.
  4183. Because it returns a reference to the string's internal data, the pointer
  4184. that is returned must not be stored anywhere, as it can be deleted whenever the
  4185. string changes.
  4186. */
  4187. inline const CharPointerType& getCharPointer() const noexcept { return text; }
  4188. /** Returns a pointer to a UTF-8 version of this string.
  4189. Because it returns a reference to the string's internal data, the pointer
  4190. that is returned must not be stored anywhere, as it can be deleted whenever the
  4191. string changes.
  4192. To find out how many bytes you need to store this string as UTF-8, you can call
  4193. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4194. @see getCharPointer, toUTF16, toUTF32
  4195. */
  4196. const CharPointer_UTF8 toUTF8() const;
  4197. /** Returns a pointer to a UTF-32 version of this string.
  4198. Because it returns a reference to the string's internal data, the pointer
  4199. that is returned must not be stored anywhere, as it can be deleted whenever the
  4200. string changes.
  4201. To find out how many bytes you need to store this string as UTF-16, you can call
  4202. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4203. @see getCharPointer, toUTF8, toUTF32
  4204. */
  4205. CharPointer_UTF16 toUTF16() const;
  4206. /** Returns a pointer to a UTF-32 version of this string.
  4207. Because it returns a reference to the string's internal data, the pointer
  4208. that is returned must not be stored anywhere, as it can be deleted whenever the
  4209. string changes.
  4210. @see getCharPointer, toUTF8, toUTF16
  4211. */
  4212. CharPointer_UTF32 toUTF32() const;
  4213. /** Returns a pointer to a wchar_t version of this string.
  4214. Because it returns a reference to the string's internal data, the pointer
  4215. that is returned must not be stored anywhere, as it can be deleted whenever the
  4216. string changes.
  4217. Bear in mind that the wchar_t type is different on different platforms, so on
  4218. Windows, this will be equivalent to calling toUTF16(), on unix it'll be the same
  4219. as calling toUTF32(), etc.
  4220. @see getCharPointer, toUTF8, toUTF16, toUTF32
  4221. */
  4222. const wchar_t* toWideCharPointer() const;
  4223. /** Creates a String from a UTF-8 encoded buffer.
  4224. If the size is < 0, it'll keep reading until it hits a zero.
  4225. */
  4226. static String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  4227. /** Returns the number of bytes required to represent this string as UTF8.
  4228. The number returned does NOT include the trailing zero.
  4229. @see toUTF8, copyToUTF8
  4230. */
  4231. int getNumBytesAsUTF8() const noexcept;
  4232. /** Copies the string to a buffer as UTF-8 characters.
  4233. Returns the number of bytes copied to the buffer, including the terminating null
  4234. character.
  4235. To find out how many bytes you need to store this string as UTF-8, you can call
  4236. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4237. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4238. returns the number of bytes required (including the terminating null character).
  4239. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4240. put in as many as it can while still allowing for a terminating null char at the
  4241. end, and will return the number of bytes that were actually used.
  4242. @see CharPointer_UTF8::writeWithDestByteLimit
  4243. */
  4244. int copyToUTF8 (CharPointer_UTF8::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4245. /** Copies the string to a buffer as UTF-16 characters.
  4246. Returns the number of bytes copied to the buffer, including the terminating null
  4247. character.
  4248. To find out how many bytes you need to store this string as UTF-16, you can call
  4249. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4250. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4251. returns the number of bytes required (including the terminating null character).
  4252. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4253. put in as many as it can while still allowing for a terminating null char at the
  4254. end, and will return the number of bytes that were actually used.
  4255. @see CharPointer_UTF16::writeWithDestByteLimit
  4256. */
  4257. int copyToUTF16 (CharPointer_UTF16::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4258. /** Copies the string to a buffer as UTF-16 characters.
  4259. Returns the number of bytes copied to the buffer, including the terminating null
  4260. character.
  4261. To find out how many bytes you need to store this string as UTF-32, you can call
  4262. CharPointer_UTF32::getBytesRequiredFor (myString.getCharPointer())
  4263. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4264. returns the number of bytes required (including the terminating null character).
  4265. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4266. put in as many as it can while still allowing for a terminating null char at the
  4267. end, and will return the number of bytes that were actually used.
  4268. @see CharPointer_UTF32::writeWithDestByteLimit
  4269. */
  4270. int copyToUTF32 (CharPointer_UTF32::CharType* destBuffer, int maxBufferSizeBytes) const noexcept;
  4271. /** Increases the string's internally allocated storage.
  4272. Although the string's contents won't be affected by this call, it will
  4273. increase the amount of memory allocated internally for the string to grow into.
  4274. If you're about to make a large number of calls to methods such
  4275. as += or <<, it's more efficient to preallocate enough extra space
  4276. beforehand, so that these methods won't have to keep resizing the string
  4277. to append the extra characters.
  4278. @param numBytesNeeded the number of bytes to allocate storage for. If this
  4279. value is less than the currently allocated size, it will
  4280. have no effect.
  4281. */
  4282. void preallocateBytes (size_t numBytesNeeded);
  4283. /** Swaps the contents of this string with another one.
  4284. This is a very fast operation, as no allocation or copying needs to be done.
  4285. */
  4286. void swapWith (String& other) noexcept;
  4287. /** A helper class to improve performance when concatenating many large strings
  4288. together.
  4289. Because appending one string to another involves measuring the length of
  4290. both strings, repeatedly doing this for many long strings will become
  4291. an exponentially slow operation. This class uses some internal state to
  4292. avoid that, so that each append operation only needs to measure the length
  4293. of the appended string.
  4294. */
  4295. class JUCE_API Concatenator
  4296. {
  4297. public:
  4298. Concatenator (String& stringToAppendTo);
  4299. ~Concatenator();
  4300. void append (const String& s);
  4301. private:
  4302. String& result;
  4303. int nextIndex;
  4304. JUCE_DECLARE_NON_COPYABLE (Concatenator);
  4305. };
  4306. private:
  4307. CharPointerType text;
  4308. struct PreallocationBytes
  4309. {
  4310. explicit PreallocationBytes (size_t);
  4311. size_t numBytes;
  4312. };
  4313. explicit String (const PreallocationBytes&); // This constructor preallocates a certain amount of memory
  4314. void appendFixedLength (const char* text, int numExtraChars);
  4315. size_t getByteOffsetOfEnd() const noexcept;
  4316. JUCE_DEPRECATED (String (const String& stringToCopy, size_t charsToAllocate));
  4317. // This private cast operator should prevent strings being accidentally cast
  4318. // to bools (this is possible because the compiler can add an implicit cast
  4319. // via a const char*)
  4320. operator bool() const noexcept { return false; }
  4321. };
  4322. /** Concatenates two strings. */
  4323. JUCE_API String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
  4324. /** Concatenates two strings. */
  4325. JUCE_API String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2);
  4326. /** Concatenates two strings. */
  4327. JUCE_API String JUCE_CALLTYPE operator+ (char string1, const String& string2);
  4328. /** Concatenates two strings. */
  4329. JUCE_API String JUCE_CALLTYPE operator+ (wchar_t string1, const String& string2);
  4330. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4331. /** Concatenates two strings. */
  4332. JUCE_API String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
  4333. #endif
  4334. /** Concatenates two strings. */
  4335. JUCE_API String JUCE_CALLTYPE operator+ (String string1, const String& string2);
  4336. /** Concatenates two strings. */
  4337. JUCE_API String JUCE_CALLTYPE operator+ (String string1, const char* string2);
  4338. /** Concatenates two strings. */
  4339. JUCE_API String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2);
  4340. /** Concatenates two strings. */
  4341. JUCE_API String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
  4342. /** Concatenates two strings. */
  4343. JUCE_API String JUCE_CALLTYPE operator+ (String string1, wchar_t characterToAppend);
  4344. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4345. /** Concatenates two strings. */
  4346. JUCE_API String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
  4347. #endif
  4348. /** Appends a character at the end of a string. */
  4349. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
  4350. /** Appends a character at the end of a string. */
  4351. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, wchar_t characterToAppend);
  4352. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4353. /** Appends a character at the end of a string. */
  4354. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
  4355. #endif
  4356. /** Appends a string to the end of the first one. */
  4357. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
  4358. /** Appends a string to the end of the first one. */
  4359. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const wchar_t* string2);
  4360. /** Appends a string to the end of the first one. */
  4361. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
  4362. /** Appends a decimal number at the end of a string. */
  4363. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, short number);
  4364. /** Appends a decimal number at the end of a string. */
  4365. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, int number);
  4366. /** Appends a decimal number at the end of a string. */
  4367. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, long number);
  4368. /** Appends a decimal number at the end of a string. */
  4369. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, float number);
  4370. /** Appends a decimal number at the end of a string. */
  4371. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, double number);
  4372. /** Case-sensitive comparison of two strings. */
  4373. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) noexcept;
  4374. /** Case-sensitive comparison of two strings. */
  4375. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) noexcept;
  4376. /** Case-sensitive comparison of two strings. */
  4377. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const wchar_t* string2) noexcept;
  4378. /** Case-sensitive comparison of two strings. */
  4379. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) noexcept;
  4380. /** Case-sensitive comparison of two strings. */
  4381. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) noexcept;
  4382. /** Case-sensitive comparison of two strings. */
  4383. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) noexcept;
  4384. /** Case-sensitive comparison of two strings. */
  4385. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) noexcept;
  4386. /** Case-sensitive comparison of two strings. */
  4387. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) noexcept;
  4388. /** Case-sensitive comparison of two strings. */
  4389. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const wchar_t* string2) noexcept;
  4390. /** Case-sensitive comparison of two strings. */
  4391. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) noexcept;
  4392. /** Case-sensitive comparison of two strings. */
  4393. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) noexcept;
  4394. /** Case-sensitive comparison of two strings. */
  4395. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) noexcept;
  4396. /** Case-sensitive comparison of two strings. */
  4397. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) noexcept;
  4398. /** Case-sensitive comparison of two strings. */
  4399. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) noexcept;
  4400. /** Case-sensitive comparison of two strings. */
  4401. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) noexcept;
  4402. /** Case-sensitive comparison of two strings. */
  4403. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) noexcept;
  4404. /** This operator allows you to write a juce String directly to std output streams.
  4405. This is handy for writing strings to std::cout, std::cerr, etc.
  4406. */
  4407. template <class traits>
  4408. std::basic_ostream <char, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <char, traits>& stream, const String& stringToWrite)
  4409. {
  4410. return stream << stringToWrite.toUTF8().getAddress();
  4411. }
  4412. /** This operator allows you to write a juce String directly to std output streams.
  4413. This is handy for writing strings to std::wcout, std::wcerr, etc.
  4414. */
  4415. template <class traits>
  4416. std::basic_ostream <wchar_t, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <wchar_t, traits>& stream, const String& stringToWrite)
  4417. {
  4418. return stream << stringToWrite.toWideCharPointer();
  4419. }
  4420. /** Writes a string to an OutputStream as UTF8. */
  4421. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& stringToWrite);
  4422. #endif // __JUCE_STRING_JUCEHEADER__
  4423. /*** End of inlined file: juce_String.h ***/
  4424. /**
  4425. Acts as an application-wide logging class.
  4426. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  4427. method and this will then be used by all calls to writeToLog.
  4428. The logger class also contains methods for writing messages to the debugger's
  4429. output stream.
  4430. @see FileLogger
  4431. */
  4432. class JUCE_API Logger
  4433. {
  4434. public:
  4435. /** Destructor. */
  4436. virtual ~Logger();
  4437. /** Sets the current logging class to use.
  4438. Note that the object passed in won't be deleted when no longer needed.
  4439. A null pointer can be passed-in to disable any logging.
  4440. If deleteOldLogger is set to true, the existing logger will be
  4441. deleted (if there is one).
  4442. */
  4443. static void JUCE_CALLTYPE setCurrentLogger (Logger* newLogger,
  4444. bool deleteOldLogger = false);
  4445. /** Writes a string to the current logger.
  4446. This will pass the string to the logger's logMessage() method if a logger
  4447. has been set.
  4448. @see logMessage
  4449. */
  4450. static void JUCE_CALLTYPE writeToLog (const String& message);
  4451. /** Writes a message to the standard error stream.
  4452. This can be called directly, or by using the DBG() macro in
  4453. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  4454. */
  4455. static void JUCE_CALLTYPE outputDebugString (const String& text);
  4456. protected:
  4457. Logger();
  4458. /** This is overloaded by subclasses to implement custom logging behaviour.
  4459. @see setCurrentLogger
  4460. */
  4461. virtual void logMessage (const String& message) = 0;
  4462. private:
  4463. static Logger* currentLogger;
  4464. };
  4465. #endif // __JUCE_LOGGER_JUCEHEADER__
  4466. /*** End of inlined file: juce_Logger.h ***/
  4467. /*** Start of inlined file: juce_LeakedObjectDetector.h ***/
  4468. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4469. #define __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4470. /**
  4471. Embedding an instance of this class inside another class can be used as a low-overhead
  4472. way of detecting leaked instances.
  4473. This class keeps an internal static count of the number of instances that are
  4474. active, so that when the app is shutdown and the static destructors are called,
  4475. it can check whether there are any left-over instances that may have been leaked.
  4476. To use it, use the JUCE_LEAK_DETECTOR macro as a simple way to put one in your
  4477. class declaration. Have a look through the juce codebase for examples, it's used
  4478. in most of the classes.
  4479. */
  4480. template <class OwnerClass>
  4481. class LeakedObjectDetector
  4482. {
  4483. public:
  4484. LeakedObjectDetector() noexcept { ++(getCounter().numObjects); }
  4485. LeakedObjectDetector (const LeakedObjectDetector&) noexcept { ++(getCounter().numObjects); }
  4486. ~LeakedObjectDetector()
  4487. {
  4488. if (--(getCounter().numObjects) < 0)
  4489. {
  4490. DBG ("*** Dangling pointer deletion! Class: " << getLeakedObjectClassName());
  4491. /** If you hit this, then you've managed to delete more instances of this class than you've
  4492. created.. That indicates that you're deleting some dangling pointers.
  4493. Note that although this assertion will have been triggered during a destructor, it might
  4494. not be this particular deletion that's at fault - the incorrect one may have happened
  4495. at an earlier point in the program, and simply not been detected until now.
  4496. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  4497. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4498. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4499. */
  4500. jassertfalse;
  4501. }
  4502. }
  4503. private:
  4504. class LeakCounter
  4505. {
  4506. public:
  4507. LeakCounter() noexcept {}
  4508. ~LeakCounter()
  4509. {
  4510. if (numObjects.value > 0)
  4511. {
  4512. DBG ("*** Leaked objects detected: " << numObjects.value << " instance(s) of class " << getLeakedObjectClassName());
  4513. /** If you hit this, then you've leaked one or more objects of the type specified by
  4514. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  4515. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  4516. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4517. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4518. */
  4519. jassertfalse;
  4520. }
  4521. }
  4522. Atomic<int> numObjects;
  4523. };
  4524. static const char* getLeakedObjectClassName()
  4525. {
  4526. return OwnerClass::getLeakedObjectClassName();
  4527. }
  4528. static LeakCounter& getCounter() noexcept
  4529. {
  4530. static LeakCounter counter;
  4531. return counter;
  4532. }
  4533. };
  4534. #if DOXYGEN || ! defined (JUCE_LEAK_DETECTOR)
  4535. #if (DOXYGEN || JUCE_CHECK_MEMORY_LEAKS)
  4536. /** This macro lets you embed a leak-detecting object inside a class.
  4537. To use it, simply declare a JUCE_LEAK_DETECTOR(YourClassName) inside a private section
  4538. of the class declaration. E.g.
  4539. @code
  4540. class MyClass
  4541. {
  4542. public:
  4543. MyClass();
  4544. void blahBlah();
  4545. private:
  4546. JUCE_LEAK_DETECTOR (MyClass);
  4547. };@endcode
  4548. @see JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR, LeakedObjectDetector
  4549. */
  4550. #define JUCE_LEAK_DETECTOR(OwnerClass) \
  4551. friend class JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass>; \
  4552. static const char* getLeakedObjectClassName() noexcept { return #OwnerClass; } \
  4553. JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass> JUCE_JOIN_MACRO (leakDetector, __LINE__);
  4554. #else
  4555. #define JUCE_LEAK_DETECTOR(OwnerClass)
  4556. #endif
  4557. #endif
  4558. #endif // __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4559. /*** End of inlined file: juce_LeakedObjectDetector.h ***/
  4560. #undef TYPE_BOOL // (stupidly-named CoreServices definition which interferes with other libraries).
  4561. END_JUCE_NAMESPACE
  4562. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  4563. /*** End of inlined file: juce_StandardHeader.h ***/
  4564. BEGIN_JUCE_NAMESPACE
  4565. #if JUCE_MSVC
  4566. // this is set explicitly in case the app is using a different packing size.
  4567. #pragma pack (push, 8)
  4568. #pragma warning (push)
  4569. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  4570. #ifdef __INTEL_COMPILER
  4571. #pragma warning (disable: 1125)
  4572. #endif
  4573. #endif
  4574. // this is where all the class header files get brought in..
  4575. /*** Start of inlined file: juce_core_includes.h ***/
  4576. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4577. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4578. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4579. /*** Start of inlined file: juce_AbstractFifo.h ***/
  4580. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4581. #define __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4582. /**
  4583. Encapsulates the logic required to implement a lock-free FIFO.
  4584. This class handles the logic needed when building a single-reader, single-writer FIFO.
  4585. It doesn't actually hold any data itself, but your FIFO class can use one of these to manage
  4586. its position and status when reading or writing to it.
  4587. To use it, you can call prepareToWrite() to determine the position within your own buffer that
  4588. an incoming block of data should be stored, and prepareToRead() to find out when the next
  4589. outgoing block should be read from.
  4590. e.g.
  4591. @code
  4592. class MyFifo
  4593. {
  4594. public:
  4595. MyFifo() : abstractFifo (1024)
  4596. {
  4597. }
  4598. void addToFifo (const int* someData, int numItems)
  4599. {
  4600. int start1, size1, start2, size2;
  4601. prepareToWrite (numItems, start1, size1, start2, size2);
  4602. if (size1 > 0)
  4603. copySomeData (myBuffer + start1, someData, size1);
  4604. if (size2 > 0)
  4605. copySomeData (myBuffer + start2, someData + size1, size2);
  4606. finishedWrite (size1 + size2);
  4607. }
  4608. void readFromFifo (int* someData, int numItems)
  4609. {
  4610. int start1, size1, start2, size2;
  4611. prepareToRead (numSamples, start1, size1, start2, size2);
  4612. if (size1 > 0)
  4613. copySomeData (someData, myBuffer + start1, size1);
  4614. if (size2 > 0)
  4615. copySomeData (someData + size1, myBuffer + start2, size2);
  4616. finishedRead (size1 + size2);
  4617. }
  4618. private:
  4619. AbstractFifo abstractFifo;
  4620. int myBuffer [1024];
  4621. };
  4622. @endcode
  4623. */
  4624. class JUCE_API AbstractFifo
  4625. {
  4626. public:
  4627. /** Creates a FIFO to manage a buffer with the specified capacity. */
  4628. AbstractFifo (int capacity) noexcept;
  4629. /** Destructor */
  4630. ~AbstractFifo();
  4631. /** Returns the total size of the buffer being managed. */
  4632. int getTotalSize() const noexcept;
  4633. /** Returns the number of items that can currently be added to the buffer without it overflowing. */
  4634. int getFreeSpace() const noexcept;
  4635. /** Returns the number of items that can currently be read from the buffer. */
  4636. int getNumReady() const noexcept;
  4637. /** Clears the buffer positions, so that it appears empty. */
  4638. void reset() noexcept;
  4639. /** Changes the buffer's total size.
  4640. Note that this isn't thread-safe, so don't call it if there's any danger that it
  4641. might overlap with a call to any other method in this class!
  4642. */
  4643. void setTotalSize (int newSize) noexcept;
  4644. /** Returns the location within the buffer at which an incoming block of data should be written.
  4645. Because the section of data that you want to add to the buffer may overlap the end
  4646. and wrap around to the start, two blocks within your buffer are returned, and you
  4647. should copy your data into the first one, with any remaining data spilling over into
  4648. the second.
  4649. If the number of items you ask for is too large to fit within the buffer's free space, then
  4650. blockSize1 + blockSize2 may add up to a lower value than numToWrite. If this happens, you
  4651. may decide to keep waiting and re-trying the method until there's enough space available.
  4652. After calling this method, if you choose to write your data into the blocks returned, you
  4653. must call finishedWrite() to tell the FIFO how much data you actually added.
  4654. e.g.
  4655. @code
  4656. void addToFifo (const int* someData, int numItems)
  4657. {
  4658. int start1, size1, start2, size2;
  4659. prepareToWrite (numItems, start1, size1, start2, size2);
  4660. if (size1 > 0)
  4661. copySomeData (myBuffer + start1, someData, size1);
  4662. if (size2 > 0)
  4663. copySomeData (myBuffer + start2, someData + size1, size2);
  4664. finishedWrite (size1 + size2);
  4665. }
  4666. @endcode
  4667. @param numToWrite indicates how many items you'd like to add to the buffer
  4668. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4669. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4670. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4671. the first block should be written
  4672. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4673. @see finishedWrite
  4674. */
  4675. void prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept;
  4676. /** Called after reading from the FIFO, to indicate that this many items have been added.
  4677. @see prepareToWrite
  4678. */
  4679. void finishedWrite (int numWritten) noexcept;
  4680. /** Returns the location within the buffer from which the next block of data should be read.
  4681. Because the section of data that you want to read from the buffer may overlap the end
  4682. and wrap around to the start, two blocks within your buffer are returned, and you
  4683. should read from both of them.
  4684. If the number of items you ask for is greater than the amount of data available, then
  4685. blockSize1 + blockSize2 may add up to a lower value than numWanted. If this happens, you
  4686. may decide to keep waiting and re-trying the method until there's enough data available.
  4687. After calling this method, if you choose to read the data, you must call finishedRead() to
  4688. tell the FIFO how much data you have consumed.
  4689. e.g.
  4690. @code
  4691. void readFromFifo (int* someData, int numItems)
  4692. {
  4693. int start1, size1, start2, size2;
  4694. prepareToRead (numSamples, start1, size1, start2, size2);
  4695. if (size1 > 0)
  4696. copySomeData (someData, myBuffer + start1, size1);
  4697. if (size2 > 0)
  4698. copySomeData (someData + size1, myBuffer + start2, size2);
  4699. finishedRead (size1 + size2);
  4700. }
  4701. @endcode
  4702. @param numWanted indicates how many items you'd like to add to the buffer
  4703. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4704. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4705. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4706. the first block should be written
  4707. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4708. @see finishedRead
  4709. */
  4710. void prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept;
  4711. /** Called after reading from the FIFO, to indicate that this many items have now been consumed.
  4712. @see prepareToRead
  4713. */
  4714. void finishedRead (int numRead) noexcept;
  4715. private:
  4716. int bufferSize;
  4717. Atomic <int> validStart, validEnd;
  4718. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AbstractFifo);
  4719. };
  4720. #endif // __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4721. /*** End of inlined file: juce_AbstractFifo.h ***/
  4722. #endif
  4723. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4724. /*** Start of inlined file: juce_Array.h ***/
  4725. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4726. #define __JUCE_ARRAY_JUCEHEADER__
  4727. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  4728. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4729. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4730. /*** Start of inlined file: juce_HeapBlock.h ***/
  4731. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4732. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  4733. /**
  4734. Very simple container class to hold a pointer to some data on the heap.
  4735. When you need to allocate some heap storage for something, always try to use
  4736. this class instead of allocating the memory directly using malloc/free.
  4737. A HeapBlock<char> object can be treated in pretty much exactly the same way
  4738. as an char*, but as long as you allocate it on the stack or as a class member,
  4739. it's almost impossible for it to leak memory.
  4740. It also makes your code much more concise and readable than doing the same thing
  4741. using direct allocations,
  4742. E.g. instead of this:
  4743. @code
  4744. int* temp = (int*) malloc (1024 * sizeof (int));
  4745. memcpy (temp, xyz, 1024 * sizeof (int));
  4746. free (temp);
  4747. temp = (int*) calloc (2048 * sizeof (int));
  4748. temp[0] = 1234;
  4749. memcpy (foobar, temp, 2048 * sizeof (int));
  4750. free (temp);
  4751. @endcode
  4752. ..you could just write this:
  4753. @code
  4754. HeapBlock <int> temp (1024);
  4755. memcpy (temp, xyz, 1024 * sizeof (int));
  4756. temp.calloc (2048);
  4757. temp[0] = 1234;
  4758. memcpy (foobar, temp, 2048 * sizeof (int));
  4759. @endcode
  4760. The class is extremely lightweight, containing only a pointer to the
  4761. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  4762. as their less object-oriented counterparts. Despite adding safety, you probably
  4763. won't sacrifice any performance by using this in place of normal pointers.
  4764. @see Array, OwnedArray, MemoryBlock
  4765. */
  4766. template <class ElementType>
  4767. class HeapBlock
  4768. {
  4769. public:
  4770. /** Creates a HeapBlock which is initially just a null pointer.
  4771. After creation, you can resize the array using the malloc(), calloc(),
  4772. or realloc() methods.
  4773. */
  4774. HeapBlock() noexcept : data (nullptr)
  4775. {
  4776. }
  4777. /** Creates a HeapBlock containing a number of elements.
  4778. The contents of the block are undefined, as it will have been created by a
  4779. malloc call.
  4780. If you want an array of zero values, you can use the calloc() method instead.
  4781. */
  4782. explicit HeapBlock (const size_t numElements)
  4783. : data (static_cast <ElementType*> (::malloc (numElements * sizeof (ElementType))))
  4784. {
  4785. }
  4786. /** Destructor.
  4787. This will free the data, if any has been allocated.
  4788. */
  4789. ~HeapBlock()
  4790. {
  4791. ::free (data);
  4792. }
  4793. /** Returns a raw pointer to the allocated data.
  4794. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4795. freed by calling the free() method.
  4796. */
  4797. inline operator ElementType*() const noexcept { return data; }
  4798. /** Returns a raw pointer to the allocated data.
  4799. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4800. freed by calling the free() method.
  4801. */
  4802. inline ElementType* getData() const noexcept { return data; }
  4803. /** Returns a void pointer to the allocated data.
  4804. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4805. freed by calling the free() method.
  4806. */
  4807. inline operator void*() const noexcept { return static_cast <void*> (data); }
  4808. /** Returns a void pointer to the allocated data.
  4809. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4810. freed by calling the free() method.
  4811. */
  4812. inline operator const void*() const noexcept { return static_cast <const void*> (data); }
  4813. /** Lets you use indirect calls to the first element in the array.
  4814. Obviously this will cause problems if the array hasn't been initialised, because it'll
  4815. be referencing a null pointer.
  4816. */
  4817. inline ElementType* operator->() const noexcept { return data; }
  4818. /** Returns a reference to one of the data elements.
  4819. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  4820. has no idea of the size it currently has allocated.
  4821. */
  4822. template <typename IndexType>
  4823. inline ElementType& operator[] (IndexType index) const noexcept { return data [index]; }
  4824. /** Returns a pointer to a data element at an offset from the start of the array.
  4825. This is the same as doing pointer arithmetic on the raw pointer itself.
  4826. */
  4827. template <typename IndexType>
  4828. inline ElementType* operator+ (IndexType index) const noexcept { return data + index; }
  4829. /** Compares the pointer with another pointer.
  4830. This can be handy for checking whether this is a null pointer.
  4831. */
  4832. inline bool operator== (const ElementType* const otherPointer) const noexcept { return otherPointer == data; }
  4833. /** Compares the pointer with another pointer.
  4834. This can be handy for checking whether this is a null pointer.
  4835. */
  4836. inline bool operator!= (const ElementType* const otherPointer) const noexcept { return otherPointer != data; }
  4837. /** Allocates a specified amount of memory.
  4838. This uses the normal malloc to allocate an amount of memory for this object.
  4839. Any previously allocated memory will be freed by this method.
  4840. The number of bytes allocated will be (newNumElements * elementSize). Normally
  4841. you wouldn't need to specify the second parameter, but it can be handy if you need
  4842. to allocate a size in bytes rather than in terms of the number of elements.
  4843. The data that is allocated will be freed when this object is deleted, or when you
  4844. call free() or any of the allocation methods.
  4845. */
  4846. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4847. {
  4848. ::free (data);
  4849. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4850. }
  4851. /** Allocates a specified amount of memory and clears it.
  4852. This does the same job as the malloc() method, but clears the memory that it allocates.
  4853. */
  4854. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4855. {
  4856. ::free (data);
  4857. data = static_cast <ElementType*> (::calloc (newNumElements, elementSize));
  4858. }
  4859. /** Allocates a specified amount of memory and optionally clears it.
  4860. This does the same job as either malloc() or calloc(), depending on the
  4861. initialiseToZero parameter.
  4862. */
  4863. void allocate (const size_t newNumElements, const bool initialiseToZero)
  4864. {
  4865. ::free (data);
  4866. if (initialiseToZero)
  4867. data = static_cast <ElementType*> (::calloc (newNumElements, sizeof (ElementType)));
  4868. else
  4869. data = static_cast <ElementType*> (::malloc (newNumElements * sizeof (ElementType)));
  4870. }
  4871. /** Re-allocates a specified amount of memory.
  4872. The semantics of this method are the same as malloc() and calloc(), but it
  4873. uses realloc() to keep as much of the existing data as possible.
  4874. */
  4875. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4876. {
  4877. if (data == nullptr)
  4878. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4879. else
  4880. data = static_cast <ElementType*> (::realloc (data, newNumElements * elementSize));
  4881. }
  4882. /** Frees any currently-allocated data.
  4883. This will free the data and reset this object to be a null pointer.
  4884. */
  4885. void free()
  4886. {
  4887. ::free (data);
  4888. data = nullptr;
  4889. }
  4890. /** Swaps this object's data with the data of another HeapBlock.
  4891. The two objects simply exchange their data pointers.
  4892. */
  4893. void swapWith (HeapBlock <ElementType>& other) noexcept
  4894. {
  4895. std::swap (data, other.data);
  4896. }
  4897. /** This fills the block with zeros, up to the number of elements specified.
  4898. Since the block has no way of knowing its own size, you must make sure that the number of
  4899. elements you specify doesn't exceed the allocated size.
  4900. */
  4901. void clear (size_t numElements) noexcept
  4902. {
  4903. zeromem (data, sizeof (ElementType) * numElements);
  4904. }
  4905. private:
  4906. ElementType* data;
  4907. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HeapBlock);
  4908. };
  4909. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  4910. /*** End of inlined file: juce_HeapBlock.h ***/
  4911. /**
  4912. Implements some basic array storage allocation functions.
  4913. This class isn't really for public use - it's used by the other
  4914. array classes, but might come in handy for some purposes.
  4915. It inherits from a critical section class to allow the arrays to use
  4916. the "empty base class optimisation" pattern to reduce their footprint.
  4917. @see Array, OwnedArray, ReferenceCountedArray
  4918. */
  4919. template <class ElementType, class TypeOfCriticalSectionToUse>
  4920. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  4921. {
  4922. public:
  4923. /** Creates an empty array. */
  4924. ArrayAllocationBase() noexcept
  4925. : numAllocated (0)
  4926. {
  4927. }
  4928. /** Destructor. */
  4929. ~ArrayAllocationBase()
  4930. {
  4931. }
  4932. /** Changes the amount of storage allocated.
  4933. This will retain any data currently held in the array, and either add or
  4934. remove extra space at the end.
  4935. @param numElements the number of elements that are needed
  4936. */
  4937. void setAllocatedSize (const int numElements)
  4938. {
  4939. if (numAllocated != numElements)
  4940. {
  4941. if (numElements > 0)
  4942. elements.realloc (numElements);
  4943. else
  4944. elements.free();
  4945. numAllocated = numElements;
  4946. }
  4947. }
  4948. /** Increases the amount of storage allocated if it is less than a given amount.
  4949. This will retain any data currently held in the array, but will add
  4950. extra space at the end to make sure there it's at least as big as the size
  4951. passed in. If it's already bigger, no action is taken.
  4952. @param minNumElements the minimum number of elements that are needed
  4953. */
  4954. void ensureAllocatedSize (const int minNumElements)
  4955. {
  4956. if (minNumElements > numAllocated)
  4957. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  4958. }
  4959. /** Minimises the amount of storage allocated so that it's no more than
  4960. the given number of elements.
  4961. */
  4962. void shrinkToNoMoreThan (const int maxNumElements)
  4963. {
  4964. if (maxNumElements < numAllocated)
  4965. setAllocatedSize (maxNumElements);
  4966. }
  4967. /** Swap the contents of two objects. */
  4968. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) noexcept
  4969. {
  4970. elements.swapWith (other.elements);
  4971. std::swap (numAllocated, other.numAllocated);
  4972. }
  4973. HeapBlock <ElementType> elements;
  4974. int numAllocated;
  4975. private:
  4976. JUCE_DECLARE_NON_COPYABLE (ArrayAllocationBase);
  4977. };
  4978. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4979. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  4980. /*** Start of inlined file: juce_ElementComparator.h ***/
  4981. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4982. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4983. /**
  4984. Sorts a range of elements in an array.
  4985. The comparator object that is passed-in must define a public method with the following
  4986. signature:
  4987. @code
  4988. int compareElements (ElementType first, ElementType second);
  4989. @endcode
  4990. ..and this method must return:
  4991. - a value of < 0 if the first comes before the second
  4992. - a value of 0 if the two objects are equivalent
  4993. - a value of > 0 if the second comes before the first
  4994. To improve performance, the compareElements() method can be declared as static or const.
  4995. @param comparator an object which defines a compareElements() method
  4996. @param array the array to sort
  4997. @param firstElement the index of the first element of the range to be sorted
  4998. @param lastElement the index of the last element in the range that needs
  4999. sorting (this is inclusive)
  5000. @param retainOrderOfEquivalentItems if true, the order of items that the
  5001. comparator deems the same will be maintained - this will be
  5002. a slower algorithm than if they are allowed to be moved around.
  5003. @see sortArrayRetainingOrder
  5004. */
  5005. template <class ElementType, class ElementComparator>
  5006. static void sortArray (ElementComparator& comparator,
  5007. ElementType* const array,
  5008. int firstElement,
  5009. int lastElement,
  5010. const bool retainOrderOfEquivalentItems)
  5011. {
  5012. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5013. // avoids getting warning messages about the parameter being unused
  5014. if (lastElement > firstElement)
  5015. {
  5016. if (retainOrderOfEquivalentItems)
  5017. {
  5018. for (int i = firstElement; i < lastElement; ++i)
  5019. {
  5020. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  5021. {
  5022. std::swap (array[i], array[i + 1]);
  5023. if (i > firstElement)
  5024. i -= 2;
  5025. }
  5026. }
  5027. }
  5028. else
  5029. {
  5030. int fromStack[30], toStack[30];
  5031. int stackIndex = 0;
  5032. for (;;)
  5033. {
  5034. const int size = (lastElement - firstElement) + 1;
  5035. if (size <= 8)
  5036. {
  5037. int j = lastElement;
  5038. int maxIndex;
  5039. while (j > firstElement)
  5040. {
  5041. maxIndex = firstElement;
  5042. for (int k = firstElement + 1; k <= j; ++k)
  5043. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  5044. maxIndex = k;
  5045. std::swap (array[j], array[maxIndex]);
  5046. --j;
  5047. }
  5048. }
  5049. else
  5050. {
  5051. const int mid = firstElement + (size >> 1);
  5052. std::swap (array[mid], array[firstElement]);
  5053. int i = firstElement;
  5054. int j = lastElement + 1;
  5055. for (;;)
  5056. {
  5057. while (++i <= lastElement
  5058. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  5059. {}
  5060. while (--j > firstElement
  5061. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  5062. {}
  5063. if (j < i)
  5064. break;
  5065. std::swap (array[i], array[j]);
  5066. }
  5067. std::swap (array[j], array[firstElement]);
  5068. if (j - 1 - firstElement >= lastElement - i)
  5069. {
  5070. if (firstElement + 1 < j)
  5071. {
  5072. fromStack [stackIndex] = firstElement;
  5073. toStack [stackIndex] = j - 1;
  5074. ++stackIndex;
  5075. }
  5076. if (i < lastElement)
  5077. {
  5078. firstElement = i;
  5079. continue;
  5080. }
  5081. }
  5082. else
  5083. {
  5084. if (i < lastElement)
  5085. {
  5086. fromStack [stackIndex] = i;
  5087. toStack [stackIndex] = lastElement;
  5088. ++stackIndex;
  5089. }
  5090. if (firstElement + 1 < j)
  5091. {
  5092. lastElement = j - 1;
  5093. continue;
  5094. }
  5095. }
  5096. }
  5097. if (--stackIndex < 0)
  5098. break;
  5099. jassert (stackIndex < numElementsInArray (fromStack));
  5100. firstElement = fromStack [stackIndex];
  5101. lastElement = toStack [stackIndex];
  5102. }
  5103. }
  5104. }
  5105. }
  5106. /**
  5107. Searches a sorted array of elements, looking for the index at which a specified value
  5108. should be inserted for it to be in the correct order.
  5109. The comparator object that is passed-in must define a public method with the following
  5110. signature:
  5111. @code
  5112. int compareElements (ElementType first, ElementType second);
  5113. @endcode
  5114. ..and this method must return:
  5115. - a value of < 0 if the first comes before the second
  5116. - a value of 0 if the two objects are equivalent
  5117. - a value of > 0 if the second comes before the first
  5118. To improve performance, the compareElements() method can be declared as static or const.
  5119. @param comparator an object which defines a compareElements() method
  5120. @param array the array to search
  5121. @param newElement the value that is going to be inserted
  5122. @param firstElement the index of the first element to search
  5123. @param lastElement the index of the last element in the range (this is non-inclusive)
  5124. */
  5125. template <class ElementType, class ElementComparator>
  5126. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  5127. ElementType* const array,
  5128. const ElementType newElement,
  5129. int firstElement,
  5130. int lastElement)
  5131. {
  5132. jassert (firstElement <= lastElement);
  5133. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5134. // avoids getting warning messages about the parameter being unused
  5135. while (firstElement < lastElement)
  5136. {
  5137. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  5138. {
  5139. ++firstElement;
  5140. break;
  5141. }
  5142. else
  5143. {
  5144. const int halfway = (firstElement + lastElement) >> 1;
  5145. if (halfway == firstElement)
  5146. {
  5147. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5148. ++firstElement;
  5149. break;
  5150. }
  5151. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5152. {
  5153. firstElement = halfway;
  5154. }
  5155. else
  5156. {
  5157. lastElement = halfway;
  5158. }
  5159. }
  5160. }
  5161. return firstElement;
  5162. }
  5163. /**
  5164. A simple ElementComparator class that can be used to sort an array of
  5165. objects that support the '<' operator.
  5166. This will work for primitive types and objects that implement operator<().
  5167. Example: @code
  5168. Array <int> myArray;
  5169. DefaultElementComparator<int> sorter;
  5170. myArray.sort (sorter);
  5171. @endcode
  5172. @see ElementComparator
  5173. */
  5174. template <class ElementType>
  5175. class DefaultElementComparator
  5176. {
  5177. private:
  5178. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5179. public:
  5180. static int compareElements (ParameterType first, ParameterType second)
  5181. {
  5182. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  5183. }
  5184. };
  5185. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5186. /*** End of inlined file: juce_ElementComparator.h ***/
  5187. /*** Start of inlined file: juce_CriticalSection.h ***/
  5188. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  5189. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  5190. /*** Start of inlined file: juce_ScopedLock.h ***/
  5191. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  5192. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  5193. /**
  5194. Automatically locks and unlocks a mutex object.
  5195. Use one of these as a local variable to provide RAII-based locking of a mutex.
  5196. The templated class could be a CriticalSection, SpinLock, or anything else that
  5197. provides enter() and exit() methods.
  5198. e.g. @code
  5199. CriticalSection myCriticalSection;
  5200. for (;;)
  5201. {
  5202. const GenericScopedLock<CriticalSection> myScopedLock (myCriticalSection);
  5203. // myCriticalSection is now locked
  5204. ...do some stuff...
  5205. // myCriticalSection gets unlocked here.
  5206. }
  5207. @endcode
  5208. @see GenericScopedUnlock, CriticalSection, SpinLock, ScopedLock, ScopedUnlock
  5209. */
  5210. template <class LockType>
  5211. class GenericScopedLock
  5212. {
  5213. public:
  5214. /** Creates a GenericScopedLock.
  5215. As soon as it is created, this will acquire the lock, and when the GenericScopedLock
  5216. object is deleted, the lock will be released.
  5217. Make sure this object is created and deleted by the same thread,
  5218. otherwise there are no guarantees what will happen! Best just to use it
  5219. as a local stack object, rather than creating one with the new() operator.
  5220. */
  5221. inline explicit GenericScopedLock (const LockType& lock) noexcept : lock_ (lock) { lock.enter(); }
  5222. /** Destructor.
  5223. The lock will be released when the destructor is called.
  5224. Make sure this object is created and deleted by the same thread, otherwise there are
  5225. no guarantees what will happen!
  5226. */
  5227. inline ~GenericScopedLock() noexcept { lock_.exit(); }
  5228. private:
  5229. const LockType& lock_;
  5230. JUCE_DECLARE_NON_COPYABLE (GenericScopedLock);
  5231. };
  5232. /**
  5233. Automatically unlocks and re-locks a mutex object.
  5234. This is the reverse of a GenericScopedLock object - instead of locking the mutex
  5235. for the lifetime of this object, it unlocks it.
  5236. Make sure you don't try to unlock mutexes that aren't actually locked!
  5237. e.g. @code
  5238. CriticalSection myCriticalSection;
  5239. for (;;)
  5240. {
  5241. const GenericScopedLock<CriticalSection> myScopedLock (myCriticalSection);
  5242. // myCriticalSection is now locked
  5243. ... do some stuff with it locked ..
  5244. while (xyz)
  5245. {
  5246. ... do some stuff with it locked ..
  5247. const GenericScopedUnlock<CriticalSection> unlocker (myCriticalSection);
  5248. // myCriticalSection is now unlocked for the remainder of this block,
  5249. // and re-locked at the end.
  5250. ...do some stuff with it unlocked ...
  5251. }
  5252. // myCriticalSection gets unlocked here.
  5253. }
  5254. @endcode
  5255. @see GenericScopedLock, CriticalSection, ScopedLock, ScopedUnlock
  5256. */
  5257. template <class LockType>
  5258. class GenericScopedUnlock
  5259. {
  5260. public:
  5261. /** Creates a GenericScopedUnlock.
  5262. As soon as it is created, this will unlock the CriticalSection, and
  5263. when the ScopedLock object is deleted, the CriticalSection will
  5264. be re-locked.
  5265. Make sure this object is created and deleted by the same thread,
  5266. otherwise there are no guarantees what will happen! Best just to use it
  5267. as a local stack object, rather than creating one with the new() operator.
  5268. */
  5269. inline explicit GenericScopedUnlock (const LockType& lock) noexcept : lock_ (lock) { lock.exit(); }
  5270. /** Destructor.
  5271. The CriticalSection will be unlocked when the destructor is called.
  5272. Make sure this object is created and deleted by the same thread,
  5273. otherwise there are no guarantees what will happen!
  5274. */
  5275. inline ~GenericScopedUnlock() noexcept { lock_.enter(); }
  5276. private:
  5277. const LockType& lock_;
  5278. JUCE_DECLARE_NON_COPYABLE (GenericScopedUnlock);
  5279. };
  5280. /**
  5281. Automatically locks and unlocks a mutex object.
  5282. Use one of these as a local variable to provide RAII-based locking of a mutex.
  5283. The templated class could be a CriticalSection, SpinLock, or anything else that
  5284. provides enter() and exit() methods.
  5285. e.g. @code
  5286. CriticalSection myCriticalSection;
  5287. for (;;)
  5288. {
  5289. const GenericScopedTryLock<CriticalSection> myScopedTryLock (myCriticalSection);
  5290. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  5291. // should test this with the isLocked() method before doing your thread-unsafe
  5292. // action..
  5293. if (myScopedTryLock.isLocked())
  5294. {
  5295. ...do some stuff...
  5296. }
  5297. else
  5298. {
  5299. ..our attempt at locking failed because another thread had already locked it..
  5300. }
  5301. // myCriticalSection gets unlocked here (if it was locked)
  5302. }
  5303. @endcode
  5304. @see CriticalSection::tryEnter, GenericScopedLock, GenericScopedUnlock
  5305. */
  5306. template <class LockType>
  5307. class GenericScopedTryLock
  5308. {
  5309. public:
  5310. /** Creates a GenericScopedTryLock.
  5311. As soon as it is created, this will attempt to acquire the lock, and when the
  5312. GenericScopedTryLock is deleted, the lock will be released (if the lock was
  5313. successfully acquired).
  5314. Make sure this object is created and deleted by the same thread,
  5315. otherwise there are no guarantees what will happen! Best just to use it
  5316. as a local stack object, rather than creating one with the new() operator.
  5317. */
  5318. inline explicit GenericScopedTryLock (const LockType& lock) noexcept
  5319. : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  5320. /** Destructor.
  5321. The mutex will be unlocked (if it had been successfully locked) when the
  5322. destructor is called.
  5323. Make sure this object is created and deleted by the same thread,
  5324. otherwise there are no guarantees what will happen!
  5325. */
  5326. inline ~GenericScopedTryLock() noexcept { if (lockWasSuccessful) lock_.exit(); }
  5327. /** Returns true if the mutex was successfully locked. */
  5328. bool isLocked() const noexcept { return lockWasSuccessful; }
  5329. private:
  5330. const LockType& lock_;
  5331. const bool lockWasSuccessful;
  5332. JUCE_DECLARE_NON_COPYABLE (GenericScopedTryLock);
  5333. };
  5334. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  5335. /*** End of inlined file: juce_ScopedLock.h ***/
  5336. /**
  5337. A mutex class.
  5338. A CriticalSection acts as a re-entrant mutex lock. The best way to lock and unlock
  5339. one of these is by using RAII in the form of a local ScopedLock object - have a look
  5340. through the codebase for many examples of how to do this.
  5341. @see ScopedLock, ScopedTryLock, ScopedUnlock, SpinLock, ReadWriteLock, Thread, InterProcessLock
  5342. */
  5343. class JUCE_API CriticalSection
  5344. {
  5345. public:
  5346. /** Creates a CriticalSection object. */
  5347. CriticalSection() noexcept;
  5348. /** Destructor.
  5349. If the critical section is deleted whilst locked, any subsequent behaviour
  5350. is unpredictable.
  5351. */
  5352. ~CriticalSection() noexcept;
  5353. /** Acquires the lock.
  5354. If the lock is already held by the caller thread, the method returns immediately.
  5355. If the lock is currently held by another thread, this will wait until it becomes free.
  5356. It's strongly recommended that you never call this method directly - instead use the
  5357. ScopedLock class to manage the locking using an RAII pattern instead.
  5358. @see exit, tryEnter, ScopedLock
  5359. */
  5360. void enter() const noexcept;
  5361. /** Attempts to lock this critical section without blocking.
  5362. This method behaves identically to CriticalSection::enter, except that the caller thread
  5363. does not wait if the lock is currently held by another thread but returns false immediately.
  5364. @returns false if the lock is currently held by another thread, true otherwise.
  5365. @see enter
  5366. */
  5367. bool tryEnter() const noexcept;
  5368. /** Releases the lock.
  5369. If the caller thread hasn't got the lock, this can have unpredictable results.
  5370. If the enter() method has been called multiple times by the thread, each
  5371. call must be matched by a call to exit() before other threads will be allowed
  5372. to take over the lock.
  5373. @see enter, ScopedLock
  5374. */
  5375. void exit() const noexcept;
  5376. /** Provides the type of scoped lock to use with a CriticalSection. */
  5377. typedef GenericScopedLock <CriticalSection> ScopedLockType;
  5378. /** Provides the type of scoped unlocker to use with a CriticalSection. */
  5379. typedef GenericScopedUnlock <CriticalSection> ScopedUnlockType;
  5380. /** Provides the type of scoped try-locker to use with a CriticalSection. */
  5381. typedef GenericScopedTryLock <CriticalSection> ScopedTryLockType;
  5382. private:
  5383. #if JUCE_WINDOWS
  5384. // To avoid including windows.h in the public JUCE headers, we'll just allocate a
  5385. // block of memory here that's big enough to be used internally as a windows critical
  5386. // section structure.
  5387. #if JUCE_64BIT
  5388. uint8 internal [44];
  5389. #else
  5390. uint8 internal [24];
  5391. #endif
  5392. #else
  5393. mutable pthread_mutex_t internal;
  5394. #endif
  5395. JUCE_DECLARE_NON_COPYABLE (CriticalSection);
  5396. };
  5397. /**
  5398. A class that can be used in place of a real CriticalSection object, but which
  5399. doesn't perform any locking.
  5400. This is currently used by some templated classes, and most compilers should
  5401. manage to optimise it out of existence.
  5402. @see CriticalSection, Array, OwnedArray, ReferenceCountedArray
  5403. */
  5404. class JUCE_API DummyCriticalSection
  5405. {
  5406. public:
  5407. inline DummyCriticalSection() noexcept {}
  5408. inline ~DummyCriticalSection() noexcept {}
  5409. inline void enter() const noexcept {}
  5410. inline bool tryEnter() const noexcept { return true; }
  5411. inline void exit() const noexcept {}
  5412. /** A dummy scoped-lock type to use with a dummy critical section. */
  5413. struct ScopedLockType
  5414. {
  5415. ScopedLockType (const DummyCriticalSection&) noexcept {}
  5416. };
  5417. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  5418. typedef ScopedLockType ScopedUnlockType;
  5419. private:
  5420. JUCE_DECLARE_NON_COPYABLE (DummyCriticalSection);
  5421. };
  5422. /**
  5423. Automatically locks and unlocks a CriticalSection object.
  5424. Use one of these as a local variable to provide RAII-based locking of a CriticalSection.
  5425. e.g. @code
  5426. CriticalSection myCriticalSection;
  5427. for (;;)
  5428. {
  5429. const ScopedLock myScopedLock (myCriticalSection);
  5430. // myCriticalSection is now locked
  5431. ...do some stuff...
  5432. // myCriticalSection gets unlocked here.
  5433. }
  5434. @endcode
  5435. @see CriticalSection, ScopedUnlock
  5436. */
  5437. typedef CriticalSection::ScopedLockType ScopedLock;
  5438. /**
  5439. Automatically unlocks and re-locks a CriticalSection object.
  5440. This is the reverse of a ScopedLock object - instead of locking the critical
  5441. section for the lifetime of this object, it unlocks it.
  5442. Make sure you don't try to unlock critical sections that aren't actually locked!
  5443. e.g. @code
  5444. CriticalSection myCriticalSection;
  5445. for (;;)
  5446. {
  5447. const ScopedLock myScopedLock (myCriticalSection);
  5448. // myCriticalSection is now locked
  5449. ... do some stuff with it locked ..
  5450. while (xyz)
  5451. {
  5452. ... do some stuff with it locked ..
  5453. const ScopedUnlock unlocker (myCriticalSection);
  5454. // myCriticalSection is now unlocked for the remainder of this block,
  5455. // and re-locked at the end.
  5456. ...do some stuff with it unlocked ...
  5457. }
  5458. // myCriticalSection gets unlocked here.
  5459. }
  5460. @endcode
  5461. @see CriticalSection, ScopedLock
  5462. */
  5463. typedef CriticalSection::ScopedUnlockType ScopedUnlock;
  5464. /**
  5465. Automatically tries to lock and unlock a CriticalSection object.
  5466. Use one of these as a local variable to control access to a CriticalSection.
  5467. e.g. @code
  5468. CriticalSection myCriticalSection;
  5469. for (;;)
  5470. {
  5471. const ScopedTryLock myScopedTryLock (myCriticalSection);
  5472. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  5473. // should test this with the isLocked() method before doing your thread-unsafe
  5474. // action..
  5475. if (myScopedTryLock.isLocked())
  5476. {
  5477. ...do some stuff...
  5478. }
  5479. else
  5480. {
  5481. ..our attempt at locking failed because another thread had already locked it..
  5482. }
  5483. // myCriticalSection gets unlocked here (if it was locked)
  5484. }
  5485. @endcode
  5486. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  5487. */
  5488. typedef CriticalSection::ScopedTryLockType ScopedTryLock;
  5489. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  5490. /*** End of inlined file: juce_CriticalSection.h ***/
  5491. /**
  5492. Holds a resizable array of primitive or copy-by-value objects.
  5493. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  5494. The Array class can be used to hold simple, non-polymorphic objects as well as primitive types - to
  5495. do so, the class must fulfil these requirements:
  5496. - it must have a copy constructor and assignment operator
  5497. - it must be able to be relocated in memory by a memcpy without this causing any problems - so
  5498. objects whose functionality relies on external pointers or references to themselves can be used.
  5499. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  5500. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  5501. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  5502. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  5503. specialised class StringArray, which provides more useful functions.
  5504. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5505. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5506. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  5507. */
  5508. template <typename ElementType,
  5509. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  5510. class Array
  5511. {
  5512. private:
  5513. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5514. public:
  5515. /** Creates an empty array. */
  5516. Array() noexcept
  5517. : numUsed (0)
  5518. {
  5519. }
  5520. /** Creates a copy of another array.
  5521. @param other the array to copy
  5522. */
  5523. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  5524. {
  5525. const ScopedLockType lock (other.getLock());
  5526. numUsed = other.numUsed;
  5527. data.setAllocatedSize (other.numUsed);
  5528. for (int i = 0; i < numUsed; ++i)
  5529. new (data.elements + i) ElementType (other.data.elements[i]);
  5530. }
  5531. /** Initalises from a null-terminated C array of values.
  5532. @param values the array to copy from
  5533. */
  5534. template <typename TypeToCreateFrom>
  5535. explicit Array (const TypeToCreateFrom* values)
  5536. : numUsed (0)
  5537. {
  5538. while (*values != TypeToCreateFrom())
  5539. add (*values++);
  5540. }
  5541. /** Initalises from a C array of values.
  5542. @param values the array to copy from
  5543. @param numValues the number of values in the array
  5544. */
  5545. template <typename TypeToCreateFrom>
  5546. Array (const TypeToCreateFrom* values, int numValues)
  5547. : numUsed (numValues)
  5548. {
  5549. data.setAllocatedSize (numValues);
  5550. for (int i = 0; i < numValues; ++i)
  5551. new (data.elements + i) ElementType (values[i]);
  5552. }
  5553. /** Destructor. */
  5554. ~Array()
  5555. {
  5556. for (int i = 0; i < numUsed; ++i)
  5557. data.elements[i].~ElementType();
  5558. }
  5559. /** Copies another array.
  5560. @param other the array to copy
  5561. */
  5562. Array& operator= (const Array& other)
  5563. {
  5564. if (this != &other)
  5565. {
  5566. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  5567. swapWithArray (otherCopy);
  5568. }
  5569. return *this;
  5570. }
  5571. /** Compares this array to another one.
  5572. Two arrays are considered equal if they both contain the same set of
  5573. elements, in the same order.
  5574. @param other the other array to compare with
  5575. */
  5576. template <class OtherArrayType>
  5577. bool operator== (const OtherArrayType& other) const
  5578. {
  5579. const ScopedLockType lock (getLock());
  5580. const typename OtherArrayType::ScopedLockType lock2 (other.getLock());
  5581. if (numUsed != other.numUsed)
  5582. return false;
  5583. for (int i = numUsed; --i >= 0;)
  5584. if (! (data.elements [i] == other.data.elements [i]))
  5585. return false;
  5586. return true;
  5587. }
  5588. /** Compares this array to another one.
  5589. Two arrays are considered equal if they both contain the same set of
  5590. elements, in the same order.
  5591. @param other the other array to compare with
  5592. */
  5593. template <class OtherArrayType>
  5594. bool operator!= (const OtherArrayType& other) const
  5595. {
  5596. return ! operator== (other);
  5597. }
  5598. /** Removes all elements from the array.
  5599. This will remove all the elements, and free any storage that the array is
  5600. using. To clear the array without freeing the storage, use the clearQuick()
  5601. method instead.
  5602. @see clearQuick
  5603. */
  5604. void clear()
  5605. {
  5606. const ScopedLockType lock (getLock());
  5607. for (int i = 0; i < numUsed; ++i)
  5608. data.elements[i].~ElementType();
  5609. data.setAllocatedSize (0);
  5610. numUsed = 0;
  5611. }
  5612. /** Removes all elements from the array without freeing the array's allocated storage.
  5613. @see clear
  5614. */
  5615. void clearQuick()
  5616. {
  5617. const ScopedLockType lock (getLock());
  5618. for (int i = 0; i < numUsed; ++i)
  5619. data.elements[i].~ElementType();
  5620. numUsed = 0;
  5621. }
  5622. /** Returns the current number of elements in the array.
  5623. */
  5624. inline int size() const noexcept
  5625. {
  5626. return numUsed;
  5627. }
  5628. /** Returns one of the elements in the array.
  5629. If the index passed in is beyond the range of valid elements, this
  5630. will return zero.
  5631. If you're certain that the index will always be a valid element, you
  5632. can call getUnchecked() instead, which is faster.
  5633. @param index the index of the element being requested (0 is the first element in the array)
  5634. @see getUnchecked, getFirst, getLast
  5635. */
  5636. const ElementType operator[] (const int index) const
  5637. {
  5638. const ScopedLockType lock (getLock());
  5639. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  5640. : ElementType();
  5641. }
  5642. /** Returns one of the elements in the array, without checking the index passed in.
  5643. Unlike the operator[] method, this will try to return an element without
  5644. checking that the index is within the bounds of the array, so should only
  5645. be used when you're confident that it will always be a valid index.
  5646. @param index the index of the element being requested (0 is the first element in the array)
  5647. @see operator[], getFirst, getLast
  5648. */
  5649. inline const ElementType getUnchecked (const int index) const
  5650. {
  5651. const ScopedLockType lock (getLock());
  5652. jassert (isPositiveAndBelow (index, numUsed));
  5653. return data.elements [index];
  5654. }
  5655. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  5656. This is like getUnchecked, but returns a direct reference to the element, so that
  5657. you can alter it directly. Obviously this can be dangerous, so only use it when
  5658. absolutely necessary.
  5659. @param index the index of the element being requested (0 is the first element in the array)
  5660. @see operator[], getFirst, getLast
  5661. */
  5662. inline ElementType& getReference (const int index) const noexcept
  5663. {
  5664. const ScopedLockType lock (getLock());
  5665. jassert (isPositiveAndBelow (index, numUsed));
  5666. return data.elements [index];
  5667. }
  5668. /** Returns the first element in the array, or 0 if the array is empty.
  5669. @see operator[], getUnchecked, getLast
  5670. */
  5671. inline ElementType getFirst() const
  5672. {
  5673. const ScopedLockType lock (getLock());
  5674. return (numUsed > 0) ? data.elements [0]
  5675. : ElementType();
  5676. }
  5677. /** Returns the last element in the array, or 0 if the array is empty.
  5678. @see operator[], getUnchecked, getFirst
  5679. */
  5680. inline ElementType getLast() const
  5681. {
  5682. const ScopedLockType lock (getLock());
  5683. return (numUsed > 0) ? data.elements [numUsed - 1]
  5684. : ElementType();
  5685. }
  5686. /** Returns a pointer to the actual array data.
  5687. This pointer will only be valid until the next time a non-const method
  5688. is called on the array.
  5689. */
  5690. inline ElementType* getRawDataPointer() noexcept
  5691. {
  5692. return data.elements;
  5693. }
  5694. /** Returns a pointer to the first element in the array.
  5695. This method is provided for compatibility with standard C++ iteration mechanisms.
  5696. */
  5697. inline ElementType* begin() const noexcept
  5698. {
  5699. return data.elements;
  5700. }
  5701. /** Returns a pointer to the element which follows the last element in the array.
  5702. This method is provided for compatibility with standard C++ iteration mechanisms.
  5703. */
  5704. inline ElementType* end() const noexcept
  5705. {
  5706. return data.elements + numUsed;
  5707. }
  5708. /** Finds the index of the first element which matches the value passed in.
  5709. This will search the array for the given object, and return the index
  5710. of its first occurrence. If the object isn't found, the method will return -1.
  5711. @param elementToLookFor the value or object to look for
  5712. @returns the index of the object, or -1 if it's not found
  5713. */
  5714. int indexOf (ParameterType elementToLookFor) const
  5715. {
  5716. const ScopedLockType lock (getLock());
  5717. const ElementType* e = data.elements.getData();
  5718. const ElementType* const end_ = e + numUsed;
  5719. for (; e != end_; ++e)
  5720. if (elementToLookFor == *e)
  5721. return static_cast <int> (e - data.elements.getData());
  5722. return -1;
  5723. }
  5724. /** Returns true if the array contains at least one occurrence of an object.
  5725. @param elementToLookFor the value or object to look for
  5726. @returns true if the item is found
  5727. */
  5728. bool contains (ParameterType elementToLookFor) const
  5729. {
  5730. const ScopedLockType lock (getLock());
  5731. const ElementType* e = data.elements.getData();
  5732. const ElementType* const end_ = e + numUsed;
  5733. for (; e != end_; ++e)
  5734. if (elementToLookFor == *e)
  5735. return true;
  5736. return false;
  5737. }
  5738. /** Appends a new element at the end of the array.
  5739. @param newElement the new object to add to the array
  5740. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  5741. */
  5742. void add (ParameterType newElement)
  5743. {
  5744. const ScopedLockType lock (getLock());
  5745. data.ensureAllocatedSize (numUsed + 1);
  5746. new (data.elements + numUsed++) ElementType (newElement);
  5747. }
  5748. /** Inserts a new element into the array at a given position.
  5749. If the index is less than 0 or greater than the size of the array, the
  5750. element will be added to the end of the array.
  5751. Otherwise, it will be inserted into the array, moving all the later elements
  5752. along to make room.
  5753. @param indexToInsertAt the index at which the new element should be
  5754. inserted (pass in -1 to add it to the end)
  5755. @param newElement the new object to add to the array
  5756. @see add, addSorted, addUsingDefaultSort, set
  5757. */
  5758. void insert (int indexToInsertAt, ParameterType newElement)
  5759. {
  5760. const ScopedLockType lock (getLock());
  5761. data.ensureAllocatedSize (numUsed + 1);
  5762. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5763. {
  5764. ElementType* const insertPos = data.elements + indexToInsertAt;
  5765. const int numberToMove = numUsed - indexToInsertAt;
  5766. if (numberToMove > 0)
  5767. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  5768. new (insertPos) ElementType (newElement);
  5769. ++numUsed;
  5770. }
  5771. else
  5772. {
  5773. new (data.elements + numUsed++) ElementType (newElement);
  5774. }
  5775. }
  5776. /** Inserts multiple copies of an element into the array at a given position.
  5777. If the index is less than 0 or greater than the size of the array, the
  5778. element will be added to the end of the array.
  5779. Otherwise, it will be inserted into the array, moving all the later elements
  5780. along to make room.
  5781. @param indexToInsertAt the index at which the new element should be inserted
  5782. @param newElement the new object to add to the array
  5783. @param numberOfTimesToInsertIt how many copies of the value to insert
  5784. @see insert, add, addSorted, set
  5785. */
  5786. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  5787. int numberOfTimesToInsertIt)
  5788. {
  5789. if (numberOfTimesToInsertIt > 0)
  5790. {
  5791. const ScopedLockType lock (getLock());
  5792. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  5793. ElementType* insertPos;
  5794. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5795. {
  5796. insertPos = data.elements + indexToInsertAt;
  5797. const int numberToMove = numUsed - indexToInsertAt;
  5798. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  5799. }
  5800. else
  5801. {
  5802. insertPos = data.elements + numUsed;
  5803. }
  5804. numUsed += numberOfTimesToInsertIt;
  5805. while (--numberOfTimesToInsertIt >= 0)
  5806. new (insertPos++) ElementType (newElement);
  5807. }
  5808. }
  5809. /** Inserts an array of values into this array at a given position.
  5810. If the index is less than 0 or greater than the size of the array, the
  5811. new elements will be added to the end of the array.
  5812. Otherwise, they will be inserted into the array, moving all the later elements
  5813. along to make room.
  5814. @param indexToInsertAt the index at which the first new element should be inserted
  5815. @param newElements the new values to add to the array
  5816. @param numberOfElements how many items are in the array
  5817. @see insert, add, addSorted, set
  5818. */
  5819. void insertArray (int indexToInsertAt,
  5820. const ElementType* newElements,
  5821. int numberOfElements)
  5822. {
  5823. if (numberOfElements > 0)
  5824. {
  5825. const ScopedLockType lock (getLock());
  5826. data.ensureAllocatedSize (numUsed + numberOfElements);
  5827. ElementType* insertPos;
  5828. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5829. {
  5830. insertPos = data.elements + indexToInsertAt;
  5831. const int numberToMove = numUsed - indexToInsertAt;
  5832. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  5833. }
  5834. else
  5835. {
  5836. insertPos = data.elements + numUsed;
  5837. }
  5838. numUsed += numberOfElements;
  5839. while (--numberOfElements >= 0)
  5840. new (insertPos++) ElementType (*newElements++);
  5841. }
  5842. }
  5843. /** Appends a new element at the end of the array as long as the array doesn't
  5844. already contain it.
  5845. If the array already contains an element that matches the one passed in, nothing
  5846. will be done.
  5847. @param newElement the new object to add to the array
  5848. */
  5849. void addIfNotAlreadyThere (ParameterType newElement)
  5850. {
  5851. const ScopedLockType lock (getLock());
  5852. if (! contains (newElement))
  5853. add (newElement);
  5854. }
  5855. /** Replaces an element with a new value.
  5856. If the index is less than zero, this method does nothing.
  5857. If the index is beyond the end of the array, the item is added to the end of the array.
  5858. @param indexToChange the index whose value you want to change
  5859. @param newValue the new value to set for this index.
  5860. @see add, insert
  5861. */
  5862. void set (const int indexToChange, ParameterType newValue)
  5863. {
  5864. jassert (indexToChange >= 0);
  5865. const ScopedLockType lock (getLock());
  5866. if (isPositiveAndBelow (indexToChange, numUsed))
  5867. {
  5868. data.elements [indexToChange] = newValue;
  5869. }
  5870. else if (indexToChange >= 0)
  5871. {
  5872. data.ensureAllocatedSize (numUsed + 1);
  5873. new (data.elements + numUsed++) ElementType (newValue);
  5874. }
  5875. }
  5876. /** Replaces an element with a new value without doing any bounds-checking.
  5877. This just sets a value directly in the array's internal storage, so you'd
  5878. better make sure it's in range!
  5879. @param indexToChange the index whose value you want to change
  5880. @param newValue the new value to set for this index.
  5881. @see set, getUnchecked
  5882. */
  5883. void setUnchecked (const int indexToChange, ParameterType newValue)
  5884. {
  5885. const ScopedLockType lock (getLock());
  5886. jassert (isPositiveAndBelow (indexToChange, numUsed));
  5887. data.elements [indexToChange] = newValue;
  5888. }
  5889. /** Adds elements from an array to the end of this array.
  5890. @param elementsToAdd the array of elements to add
  5891. @param numElementsToAdd how many elements are in this other array
  5892. @see add
  5893. */
  5894. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  5895. {
  5896. const ScopedLockType lock (getLock());
  5897. if (numElementsToAdd > 0)
  5898. {
  5899. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5900. while (--numElementsToAdd >= 0)
  5901. {
  5902. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  5903. ++numUsed;
  5904. }
  5905. }
  5906. }
  5907. /** This swaps the contents of this array with those of another array.
  5908. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5909. because it just swaps their internal pointers.
  5910. */
  5911. void swapWithArray (Array& otherArray) noexcept
  5912. {
  5913. const ScopedLockType lock1 (getLock());
  5914. const ScopedLockType lock2 (otherArray.getLock());
  5915. data.swapWith (otherArray.data);
  5916. swapVariables (numUsed, otherArray.numUsed);
  5917. }
  5918. /** Adds elements from another array to the end of this array.
  5919. @param arrayToAddFrom the array from which to copy the elements
  5920. @param startIndex the first element of the other array to start copying from
  5921. @param numElementsToAdd how many elements to add from the other array. If this
  5922. value is negative or greater than the number of available elements,
  5923. all available elements will be copied.
  5924. @see add
  5925. */
  5926. template <class OtherArrayType>
  5927. void addArray (const OtherArrayType& arrayToAddFrom,
  5928. int startIndex = 0,
  5929. int numElementsToAdd = -1)
  5930. {
  5931. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5932. {
  5933. const ScopedLockType lock2 (getLock());
  5934. if (startIndex < 0)
  5935. {
  5936. jassertfalse;
  5937. startIndex = 0;
  5938. }
  5939. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5940. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5941. while (--numElementsToAdd >= 0)
  5942. add (arrayToAddFrom.getUnchecked (startIndex++));
  5943. }
  5944. }
  5945. /** This will enlarge or shrink the array to the given number of elements, by adding
  5946. or removing items from its end.
  5947. If the array is smaller than the given target size, empty elements will be appended
  5948. until its size is as specified. If its size is larger than the target, items will be
  5949. removed from its end to shorten it.
  5950. */
  5951. void resize (const int targetNumItems)
  5952. {
  5953. jassert (targetNumItems >= 0);
  5954. const int numToAdd = targetNumItems - numUsed;
  5955. if (numToAdd > 0)
  5956. insertMultiple (numUsed, ElementType(), numToAdd);
  5957. else if (numToAdd < 0)
  5958. removeRange (targetNumItems, -numToAdd);
  5959. }
  5960. /** Inserts a new element into the array, assuming that the array is sorted.
  5961. This will use a comparator to find the position at which the new element
  5962. should go. If the array isn't sorted, the behaviour of this
  5963. method will be unpredictable.
  5964. @param comparator the comparator to use to compare the elements - see the sort()
  5965. method for details about the form this object should take
  5966. @param newElement the new element to insert to the array
  5967. @returns the index at which the new item was added
  5968. @see addUsingDefaultSort, add, sort
  5969. */
  5970. template <class ElementComparator>
  5971. int addSorted (ElementComparator& comparator, ParameterType newElement)
  5972. {
  5973. const ScopedLockType lock (getLock());
  5974. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed);
  5975. insert (index, newElement);
  5976. return index;
  5977. }
  5978. /** Inserts a new element into the array, assuming that the array is sorted.
  5979. This will use the DefaultElementComparator class for sorting, so your ElementType
  5980. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  5981. method will be unpredictable.
  5982. @param newElement the new element to insert to the array
  5983. @see addSorted, sort
  5984. */
  5985. void addUsingDefaultSort (ParameterType newElement)
  5986. {
  5987. DefaultElementComparator <ElementType> comparator;
  5988. addSorted (comparator, newElement);
  5989. }
  5990. /** Finds the index of an element in the array, assuming that the array is sorted.
  5991. This will use a comparator to do a binary-chop to find the index of the given
  5992. element, if it exists. If the array isn't sorted, the behaviour of this
  5993. method will be unpredictable.
  5994. @param comparator the comparator to use to compare the elements - see the sort()
  5995. method for details about the form this object should take
  5996. @param elementToLookFor the element to search for
  5997. @returns the index of the element, or -1 if it's not found
  5998. @see addSorted, sort
  5999. */
  6000. template <class ElementComparator>
  6001. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  6002. {
  6003. (void) comparator; // if you pass in an object with a static compareElements() method, this
  6004. // avoids getting warning messages about the parameter being unused
  6005. const ScopedLockType lock (getLock());
  6006. int start = 0;
  6007. int end_ = numUsed;
  6008. for (;;)
  6009. {
  6010. if (start >= end_)
  6011. {
  6012. return -1;
  6013. }
  6014. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  6015. {
  6016. return start;
  6017. }
  6018. else
  6019. {
  6020. const int halfway = (start + end_) >> 1;
  6021. if (halfway == start)
  6022. return -1;
  6023. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  6024. start = halfway;
  6025. else
  6026. end_ = halfway;
  6027. }
  6028. }
  6029. }
  6030. /** Removes an element from the array.
  6031. This will remove the element at a given index, and move back
  6032. all the subsequent elements to close the gap.
  6033. If the index passed in is out-of-range, nothing will happen.
  6034. @param indexToRemove the index of the element to remove
  6035. @returns the element that has been removed
  6036. @see removeValue, removeRange
  6037. */
  6038. ElementType remove (const int indexToRemove)
  6039. {
  6040. const ScopedLockType lock (getLock());
  6041. if (isPositiveAndBelow (indexToRemove, numUsed))
  6042. {
  6043. --numUsed;
  6044. ElementType* const e = data.elements + indexToRemove;
  6045. ElementType removed (*e);
  6046. e->~ElementType();
  6047. const int numberToShift = numUsed - indexToRemove;
  6048. if (numberToShift > 0)
  6049. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  6050. if ((numUsed << 1) < data.numAllocated)
  6051. minimiseStorageOverheads();
  6052. return removed;
  6053. }
  6054. else
  6055. {
  6056. return ElementType();
  6057. }
  6058. }
  6059. /** Removes an item from the array.
  6060. This will remove the first occurrence of the given element from the array.
  6061. If the item isn't found, no action is taken.
  6062. @param valueToRemove the object to try to remove
  6063. @see remove, removeRange
  6064. */
  6065. void removeValue (ParameterType valueToRemove)
  6066. {
  6067. const ScopedLockType lock (getLock());
  6068. ElementType* const e = data.elements;
  6069. for (int i = 0; i < numUsed; ++i)
  6070. {
  6071. if (valueToRemove == e[i])
  6072. {
  6073. remove (i);
  6074. break;
  6075. }
  6076. }
  6077. }
  6078. /** Removes a range of elements from the array.
  6079. This will remove a set of elements, starting from the given index,
  6080. and move subsequent elements down to close the gap.
  6081. If the range extends beyond the bounds of the array, it will
  6082. be safely clipped to the size of the array.
  6083. @param startIndex the index of the first element to remove
  6084. @param numberToRemove how many elements should be removed
  6085. @see remove, removeValue
  6086. */
  6087. void removeRange (int startIndex, int numberToRemove)
  6088. {
  6089. const ScopedLockType lock (getLock());
  6090. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  6091. startIndex = jlimit (0, numUsed, startIndex);
  6092. if (endIndex > startIndex)
  6093. {
  6094. ElementType* const e = data.elements + startIndex;
  6095. numberToRemove = endIndex - startIndex;
  6096. for (int i = 0; i < numberToRemove; ++i)
  6097. e[i].~ElementType();
  6098. const int numToShift = numUsed - endIndex;
  6099. if (numToShift > 0)
  6100. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  6101. numUsed -= numberToRemove;
  6102. if ((numUsed << 1) < data.numAllocated)
  6103. minimiseStorageOverheads();
  6104. }
  6105. }
  6106. /** Removes the last n elements from the array.
  6107. @param howManyToRemove how many elements to remove from the end of the array
  6108. @see remove, removeValue, removeRange
  6109. */
  6110. void removeLast (int howManyToRemove = 1)
  6111. {
  6112. const ScopedLockType lock (getLock());
  6113. if (howManyToRemove > numUsed)
  6114. howManyToRemove = numUsed;
  6115. for (int i = 1; i <= howManyToRemove; ++i)
  6116. data.elements [numUsed - i].~ElementType();
  6117. numUsed -= howManyToRemove;
  6118. if ((numUsed << 1) < data.numAllocated)
  6119. minimiseStorageOverheads();
  6120. }
  6121. /** Removes any elements which are also in another array.
  6122. @param otherArray the other array in which to look for elements to remove
  6123. @see removeValuesNotIn, remove, removeValue, removeRange
  6124. */
  6125. template <class OtherArrayType>
  6126. void removeValuesIn (const OtherArrayType& otherArray)
  6127. {
  6128. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  6129. const ScopedLockType lock2 (getLock());
  6130. if (this == &otherArray)
  6131. {
  6132. clear();
  6133. }
  6134. else
  6135. {
  6136. if (otherArray.size() > 0)
  6137. {
  6138. for (int i = numUsed; --i >= 0;)
  6139. if (otherArray.contains (data.elements [i]))
  6140. remove (i);
  6141. }
  6142. }
  6143. }
  6144. /** Removes any elements which are not found in another array.
  6145. Only elements which occur in this other array will be retained.
  6146. @param otherArray the array in which to look for elements NOT to remove
  6147. @see removeValuesIn, remove, removeValue, removeRange
  6148. */
  6149. template <class OtherArrayType>
  6150. void removeValuesNotIn (const OtherArrayType& otherArray)
  6151. {
  6152. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  6153. const ScopedLockType lock2 (getLock());
  6154. if (this != &otherArray)
  6155. {
  6156. if (otherArray.size() <= 0)
  6157. {
  6158. clear();
  6159. }
  6160. else
  6161. {
  6162. for (int i = numUsed; --i >= 0;)
  6163. if (! otherArray.contains (data.elements [i]))
  6164. remove (i);
  6165. }
  6166. }
  6167. }
  6168. /** Swaps over two elements in the array.
  6169. This swaps over the elements found at the two indexes passed in.
  6170. If either index is out-of-range, this method will do nothing.
  6171. @param index1 index of one of the elements to swap
  6172. @param index2 index of the other element to swap
  6173. */
  6174. void swap (const int index1,
  6175. const int index2)
  6176. {
  6177. const ScopedLockType lock (getLock());
  6178. if (isPositiveAndBelow (index1, numUsed)
  6179. && isPositiveAndBelow (index2, numUsed))
  6180. {
  6181. swapVariables (data.elements [index1],
  6182. data.elements [index2]);
  6183. }
  6184. }
  6185. /** Moves one of the values to a different position.
  6186. This will move the value to a specified index, shuffling along
  6187. any intervening elements as required.
  6188. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  6189. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  6190. @param currentIndex the index of the value to be moved. If this isn't a
  6191. valid index, then nothing will be done
  6192. @param newIndex the index at which you'd like this value to end up. If this
  6193. is less than zero, the value will be moved to the end
  6194. of the array
  6195. */
  6196. void move (const int currentIndex, int newIndex) noexcept
  6197. {
  6198. if (currentIndex != newIndex)
  6199. {
  6200. const ScopedLockType lock (getLock());
  6201. if (isPositiveAndBelow (currentIndex, numUsed))
  6202. {
  6203. if (! isPositiveAndBelow (newIndex, numUsed))
  6204. newIndex = numUsed - 1;
  6205. char tempCopy [sizeof (ElementType)];
  6206. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  6207. if (newIndex > currentIndex)
  6208. {
  6209. memmove (data.elements + currentIndex,
  6210. data.elements + currentIndex + 1,
  6211. (newIndex - currentIndex) * sizeof (ElementType));
  6212. }
  6213. else
  6214. {
  6215. memmove (data.elements + newIndex + 1,
  6216. data.elements + newIndex,
  6217. (currentIndex - newIndex) * sizeof (ElementType));
  6218. }
  6219. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  6220. }
  6221. }
  6222. }
  6223. /** Reduces the amount of storage being used by the array.
  6224. Arrays typically allocate slightly more storage than they need, and after
  6225. removing elements, they may have quite a lot of unused space allocated.
  6226. This method will reduce the amount of allocated storage to a minimum.
  6227. */
  6228. void minimiseStorageOverheads()
  6229. {
  6230. const ScopedLockType lock (getLock());
  6231. data.shrinkToNoMoreThan (numUsed);
  6232. }
  6233. /** Increases the array's internal storage to hold a minimum number of elements.
  6234. Calling this before adding a large known number of elements means that
  6235. the array won't have to keep dynamically resizing itself as the elements
  6236. are added, and it'll therefore be more efficient.
  6237. */
  6238. void ensureStorageAllocated (const int minNumElements)
  6239. {
  6240. const ScopedLockType lock (getLock());
  6241. data.ensureAllocatedSize (minNumElements);
  6242. }
  6243. /** Sorts the elements in the array.
  6244. This will use a comparator object to sort the elements into order. The object
  6245. passed must have a method of the form:
  6246. @code
  6247. int compareElements (ElementType first, ElementType second);
  6248. @endcode
  6249. ..and this method must return:
  6250. - a value of < 0 if the first comes before the second
  6251. - a value of 0 if the two objects are equivalent
  6252. - a value of > 0 if the second comes before the first
  6253. To improve performance, the compareElements() method can be declared as static or const.
  6254. @param comparator the comparator to use for comparing elements.
  6255. @param retainOrderOfEquivalentItems if this is true, then items
  6256. which the comparator says are equivalent will be
  6257. kept in the order in which they currently appear
  6258. in the array. This is slower to perform, but may
  6259. be important in some cases. If it's false, a faster
  6260. algorithm is used, but equivalent elements may be
  6261. rearranged.
  6262. @see addSorted, indexOfSorted, sortArray
  6263. */
  6264. template <class ElementComparator>
  6265. void sort (ElementComparator& comparator,
  6266. const bool retainOrderOfEquivalentItems = false) const
  6267. {
  6268. const ScopedLockType lock (getLock());
  6269. (void) comparator; // if you pass in an object with a static compareElements() method, this
  6270. // avoids getting warning messages about the parameter being unused
  6271. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  6272. }
  6273. /** Returns the CriticalSection that locks this array.
  6274. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  6275. an object of ScopedLockType as an RAII lock for it.
  6276. */
  6277. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  6278. /** Returns the type of scoped lock to use for locking this array */
  6279. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  6280. private:
  6281. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  6282. int numUsed;
  6283. };
  6284. #endif // __JUCE_ARRAY_JUCEHEADER__
  6285. /*** End of inlined file: juce_Array.h ***/
  6286. #endif
  6287. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6288. #endif
  6289. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6290. /*** Start of inlined file: juce_DynamicObject.h ***/
  6291. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6292. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6293. /*** Start of inlined file: juce_NamedValueSet.h ***/
  6294. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  6295. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  6296. /*** Start of inlined file: juce_Variant.h ***/
  6297. #ifndef __JUCE_VARIANT_JUCEHEADER__
  6298. #define __JUCE_VARIANT_JUCEHEADER__
  6299. /*** Start of inlined file: juce_Identifier.h ***/
  6300. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  6301. #define __JUCE_IDENTIFIER_JUCEHEADER__
  6302. class StringPool;
  6303. /**
  6304. Represents a string identifier, designed for accessing properties by name.
  6305. Identifier objects are very light and fast to copy, but slower to initialise
  6306. from a string, so it's much faster to keep a static identifier object to refer
  6307. to frequently-used names, rather than constructing them each time you need it.
  6308. @see NamedPropertySet, ValueTree
  6309. */
  6310. class JUCE_API Identifier
  6311. {
  6312. public:
  6313. /** Creates a null identifier. */
  6314. Identifier() noexcept;
  6315. /** Creates an identifier with a specified name.
  6316. Because this name may need to be used in contexts such as script variables or XML
  6317. tags, it must only contain ascii letters and digits, or the underscore character.
  6318. */
  6319. Identifier (const char* name);
  6320. /** Creates an identifier with a specified name.
  6321. Because this name may need to be used in contexts such as script variables or XML
  6322. tags, it must only contain ascii letters and digits, or the underscore character.
  6323. */
  6324. Identifier (const String& name);
  6325. /** Creates a copy of another identifier. */
  6326. Identifier (const Identifier& other) noexcept;
  6327. /** Creates a copy of another identifier. */
  6328. Identifier& operator= (const Identifier& other) noexcept;
  6329. /** Destructor */
  6330. ~Identifier();
  6331. /** Compares two identifiers. This is a very fast operation. */
  6332. inline bool operator== (const Identifier& other) const noexcept { return name == other.name; }
  6333. /** Compares two identifiers. This is a very fast operation. */
  6334. inline bool operator!= (const Identifier& other) const noexcept { return name != other.name; }
  6335. /** Returns this identifier as a string. */
  6336. String toString() const { return name; }
  6337. /** Returns this identifier's raw string pointer. */
  6338. operator const String::CharPointerType() const noexcept { return name; }
  6339. /** Checks a given string for characters that might not be valid in an Identifier.
  6340. Since Identifiers are used as a script variables and XML attributes, they should only contain
  6341. alphanumeric characters, underscores, or the '-' and ':' characters.
  6342. */
  6343. static bool isValidIdentifier (const String& possibleIdentifier) noexcept;
  6344. private:
  6345. String::CharPointerType name;
  6346. static StringPool& getPool();
  6347. };
  6348. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  6349. /*** End of inlined file: juce_Identifier.h ***/
  6350. /*** Start of inlined file: juce_OutputStream.h ***/
  6351. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6352. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6353. /*** Start of inlined file: juce_NewLine.h ***/
  6354. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  6355. #define __JUCE_NEWLINE_JUCEHEADER__
  6356. /** This class is used for represent a new-line character sequence.
  6357. To write a new-line to a stream, you can use the predefined 'newLine' variable, e.g.
  6358. @code
  6359. myOutputStream << "Hello World" << newLine << newLine;
  6360. @endcode
  6361. The exact character sequence that will be used for the new-line can be set and
  6362. retrieved with OutputStream::setNewLineString() and OutputStream::getNewLineString().
  6363. */
  6364. class JUCE_API NewLine
  6365. {
  6366. public:
  6367. /** Returns the default new-line sequence that the library uses.
  6368. @see OutputStream::setNewLineString()
  6369. */
  6370. static const char* getDefault() noexcept { return "\r\n"; }
  6371. /** Returns the default new-line sequence that the library uses.
  6372. @see getDefault()
  6373. */
  6374. operator String() const { return getDefault(); }
  6375. };
  6376. /** A predefined object representing a new-line, which can be written to a string or stream.
  6377. To write a new-line to a stream, you can use the predefined 'newLine' variable like this:
  6378. @code
  6379. myOutputStream << "Hello World" << newLine << newLine;
  6380. @endcode
  6381. */
  6382. extern NewLine newLine;
  6383. /** Writes a new-line sequence to a string.
  6384. You can use the predefined object 'newLine' to invoke this, e.g.
  6385. @code
  6386. myString << "Hello World" << newLine << newLine;
  6387. @endcode
  6388. */
  6389. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&);
  6390. #endif // __JUCE_NEWLINE_JUCEHEADER__
  6391. /*** End of inlined file: juce_NewLine.h ***/
  6392. class InputStream;
  6393. class MemoryBlock;
  6394. class File;
  6395. /**
  6396. The base class for streams that write data to some kind of destination.
  6397. Input and output streams are used throughout the library - subclasses can override
  6398. some or all of the virtual functions to implement their behaviour.
  6399. @see InputStream, MemoryOutputStream, FileOutputStream
  6400. */
  6401. class JUCE_API OutputStream
  6402. {
  6403. protected:
  6404. OutputStream();
  6405. public:
  6406. /** Destructor.
  6407. Some subclasses might want to do things like call flush() during their
  6408. destructors.
  6409. */
  6410. virtual ~OutputStream();
  6411. /** If the stream is using a buffer, this will ensure it gets written
  6412. out to the destination. */
  6413. virtual void flush() = 0;
  6414. /** Tries to move the stream's output position.
  6415. Not all streams will be able to seek to a new position - this will return
  6416. false if it fails to work.
  6417. @see getPosition
  6418. */
  6419. virtual bool setPosition (int64 newPosition) = 0;
  6420. /** Returns the stream's current position.
  6421. @see setPosition
  6422. */
  6423. virtual int64 getPosition() = 0;
  6424. /** Writes a block of data to the stream.
  6425. When creating a subclass of OutputStream, this is the only write method
  6426. that needs to be overloaded - the base class has methods for writing other
  6427. types of data which use this to do the work.
  6428. @returns false if the write operation fails for some reason
  6429. */
  6430. virtual bool write (const void* dataToWrite,
  6431. int howManyBytes) = 0;
  6432. /** Writes a single byte to the stream.
  6433. @see InputStream::readByte
  6434. */
  6435. virtual void writeByte (char byte);
  6436. /** Writes a boolean to the stream as a single byte.
  6437. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  6438. @see InputStream::readBool
  6439. */
  6440. virtual void writeBool (bool boolValue);
  6441. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6442. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6443. @see InputStream::readShort
  6444. */
  6445. virtual void writeShort (short value);
  6446. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6447. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6448. @see InputStream::readShortBigEndian
  6449. */
  6450. virtual void writeShortBigEndian (short value);
  6451. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6452. @see InputStream::readInt
  6453. */
  6454. virtual void writeInt (int value);
  6455. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6456. @see InputStream::readIntBigEndian
  6457. */
  6458. virtual void writeIntBigEndian (int value);
  6459. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6460. @see InputStream::readInt64
  6461. */
  6462. virtual void writeInt64 (int64 value);
  6463. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6464. @see InputStream::readInt64BigEndian
  6465. */
  6466. virtual void writeInt64BigEndian (int64 value);
  6467. /** Writes a 32-bit floating point value to the stream in a binary format.
  6468. The binary 32-bit encoding of the float is written as a little-endian int.
  6469. @see InputStream::readFloat
  6470. */
  6471. virtual void writeFloat (float value);
  6472. /** Writes a 32-bit floating point value to the stream in a binary format.
  6473. The binary 32-bit encoding of the float is written as a big-endian int.
  6474. @see InputStream::readFloatBigEndian
  6475. */
  6476. virtual void writeFloatBigEndian (float value);
  6477. /** Writes a 64-bit floating point value to the stream in a binary format.
  6478. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6479. @see InputStream::readDouble
  6480. */
  6481. virtual void writeDouble (double value);
  6482. /** Writes a 64-bit floating point value to the stream in a binary format.
  6483. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6484. @see InputStream::readDoubleBigEndian
  6485. */
  6486. virtual void writeDoubleBigEndian (double value);
  6487. /** Writes a byte to the output stream a given number of times. */
  6488. virtual void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  6489. /** Writes a condensed binary encoding of a 32-bit integer.
  6490. If you're storing a lot of integers which are unlikely to have very large values,
  6491. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6492. under 0xffff only 3 bytes, etc.
  6493. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6494. @see InputStream::readCompressedInt
  6495. */
  6496. virtual void writeCompressedInt (int value);
  6497. /** Stores a string in the stream in a binary format.
  6498. This isn't the method to use if you're trying to append text to the end of a
  6499. text-file! It's intended for storing a string so that it can be retrieved later
  6500. by InputStream::readString().
  6501. It writes the string to the stream as UTF8, including the null termination character.
  6502. For appending text to a file, instead use writeText, or operator<<
  6503. @see InputStream::readString, writeText, operator<<
  6504. */
  6505. virtual void writeString (const String& text);
  6506. /** Writes a string of text to the stream.
  6507. It can either write the text as UTF-8 or UTF-16, and can also add the UTF-16 byte-order-mark
  6508. bytes (0xff, 0xfe) to indicate the endianness (these should only be used at the start
  6509. of a file).
  6510. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6511. */
  6512. virtual void writeText (const String& text,
  6513. bool asUTF16,
  6514. bool writeUTF16ByteOrderMark);
  6515. /** Reads data from an input stream and writes it to this stream.
  6516. @param source the stream to read from
  6517. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6518. less than zero, it will keep reading until the input
  6519. is exhausted)
  6520. */
  6521. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  6522. /** Sets the string that will be written to the stream when the writeNewLine()
  6523. method is called.
  6524. By default this will be set the the value of NewLine::getDefault().
  6525. */
  6526. void setNewLineString (const String& newLineString);
  6527. /** Returns the current new-line string that was set by setNewLineString(). */
  6528. const String& getNewLineString() const noexcept { return newLineString; }
  6529. private:
  6530. String newLineString;
  6531. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OutputStream);
  6532. };
  6533. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6534. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  6535. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6536. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  6537. /** Writes a character to a stream. */
  6538. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  6539. /** Writes a null-terminated text string to a stream. */
  6540. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  6541. /** Writes a block of data from a MemoryBlock to a stream. */
  6542. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  6543. /** Writes the contents of a file to a stream. */
  6544. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  6545. /** Writes a new-line to a stream.
  6546. You can use the predefined symbol 'newLine' to invoke this, e.g.
  6547. @code
  6548. myOutputStream << "Hello World" << newLine << newLine;
  6549. @endcode
  6550. @see OutputStream::setNewLineString
  6551. */
  6552. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&);
  6553. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6554. /*** End of inlined file: juce_OutputStream.h ***/
  6555. /*** Start of inlined file: juce_InputStream.h ***/
  6556. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6557. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6558. class MemoryBlock;
  6559. /** The base class for streams that read data.
  6560. Input and output streams are used throughout the library - subclasses can override
  6561. some or all of the virtual functions to implement their behaviour.
  6562. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6563. */
  6564. class JUCE_API InputStream
  6565. {
  6566. public:
  6567. /** Destructor. */
  6568. virtual ~InputStream() {}
  6569. /** Returns the total number of bytes available for reading in this stream.
  6570. Note that this is the number of bytes available from the start of the
  6571. stream, not from the current position.
  6572. If the size of the stream isn't actually known, this may return -1.
  6573. */
  6574. virtual int64 getTotalLength() = 0;
  6575. /** Returns true if the stream has no more data to read. */
  6576. virtual bool isExhausted() = 0;
  6577. /** Reads a set of bytes from the stream into a memory buffer.
  6578. This is the only read method that subclasses actually need to implement, as the
  6579. InputStream base class implements the other read methods in terms of this one (although
  6580. it's often more efficient for subclasses to implement them directly).
  6581. @param destBuffer the destination buffer for the data
  6582. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6583. memory block passed in is big enough to contain this
  6584. many bytes.
  6585. @returns the actual number of bytes that were read, which may be less than
  6586. maxBytesToRead if the stream is exhausted before it gets that far
  6587. */
  6588. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  6589. /** Reads a byte from the stream.
  6590. If the stream is exhausted, this will return zero.
  6591. @see OutputStream::writeByte
  6592. */
  6593. virtual char readByte();
  6594. /** Reads a boolean from the stream.
  6595. The bool is encoded as a single byte - 1 for true, 0 for false.
  6596. If the stream is exhausted, this will return false.
  6597. @see OutputStream::writeBool
  6598. */
  6599. virtual bool readBool();
  6600. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6601. If the next two bytes read are byte1 and byte2, this returns
  6602. (byte1 | (byte2 << 8)).
  6603. If the stream is exhausted partway through reading the bytes, this will return zero.
  6604. @see OutputStream::writeShort, readShortBigEndian
  6605. */
  6606. virtual short readShort();
  6607. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6608. If the next two bytes read are byte1 and byte2, this returns
  6609. (byte2 | (byte1 << 8)).
  6610. If the stream is exhausted partway through reading the bytes, this will return zero.
  6611. @see OutputStream::writeShortBigEndian, readShort
  6612. */
  6613. virtual short readShortBigEndian();
  6614. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6615. If the next four bytes are byte1 to byte4, this returns
  6616. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6617. If the stream is exhausted partway through reading the bytes, this will return zero.
  6618. @see OutputStream::writeInt, readIntBigEndian
  6619. */
  6620. virtual int readInt();
  6621. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6622. If the next four bytes are byte1 to byte4, this returns
  6623. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6624. If the stream is exhausted partway through reading the bytes, this will return zero.
  6625. @see OutputStream::writeIntBigEndian, readInt
  6626. */
  6627. virtual int readIntBigEndian();
  6628. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6629. If the next eight bytes are byte1 to byte8, this returns
  6630. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6631. If the stream is exhausted partway through reading the bytes, this will return zero.
  6632. @see OutputStream::writeInt64, readInt64BigEndian
  6633. */
  6634. virtual int64 readInt64();
  6635. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6636. If the next eight bytes are byte1 to byte8, this returns
  6637. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6638. If the stream is exhausted partway through reading the bytes, this will return zero.
  6639. @see OutputStream::writeInt64BigEndian, readInt64
  6640. */
  6641. virtual int64 readInt64BigEndian();
  6642. /** Reads four bytes as a 32-bit floating point value.
  6643. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6644. If the stream is exhausted partway through reading the bytes, this will return zero.
  6645. @see OutputStream::writeFloat, readDouble
  6646. */
  6647. virtual float readFloat();
  6648. /** Reads four bytes as a 32-bit floating point value.
  6649. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6650. If the stream is exhausted partway through reading the bytes, this will return zero.
  6651. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6652. */
  6653. virtual float readFloatBigEndian();
  6654. /** Reads eight bytes as a 64-bit floating point value.
  6655. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6656. If the stream is exhausted partway through reading the bytes, this will return zero.
  6657. @see OutputStream::writeDouble, readFloat
  6658. */
  6659. virtual double readDouble();
  6660. /** Reads eight bytes as a 64-bit floating point value.
  6661. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6662. If the stream is exhausted partway through reading the bytes, this will return zero.
  6663. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6664. */
  6665. virtual double readDoubleBigEndian();
  6666. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6667. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6668. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6669. @see OutputStream::writeCompressedInt()
  6670. */
  6671. virtual int readCompressedInt();
  6672. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  6673. This will read up to the next "\n" or "\r\n" or end-of-stream.
  6674. After this call, the stream's position will be left pointing to the next character
  6675. following the line-feed, but the linefeeds aren't included in the string that
  6676. is returned.
  6677. */
  6678. virtual String readNextLine();
  6679. /** Reads a zero-terminated UTF8 string from the stream.
  6680. This will read characters from the stream until it hits a zero character or
  6681. end-of-stream.
  6682. @see OutputStream::writeString, readEntireStreamAsString
  6683. */
  6684. virtual String readString();
  6685. /** Tries to read the whole stream and turn it into a string.
  6686. This will read from the stream's current position until the end-of-stream, and
  6687. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6688. */
  6689. virtual String readEntireStreamAsString();
  6690. /** Reads from the stream and appends the data to a MemoryBlock.
  6691. @param destBlock the block to append the data onto
  6692. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6693. of bytes that will be read - if it's negative, data
  6694. will be read until the stream is exhausted.
  6695. @returns the number of bytes that were added to the memory block
  6696. */
  6697. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6698. int maxNumBytesToRead = -1);
  6699. /** Returns the offset of the next byte that will be read from the stream.
  6700. @see setPosition
  6701. */
  6702. virtual int64 getPosition() = 0;
  6703. /** Tries to move the current read position of the stream.
  6704. The position is an absolute number of bytes from the stream's start.
  6705. Some streams might not be able to do this, in which case they should do
  6706. nothing and return false. Others might be able to manage it by resetting
  6707. themselves and skipping to the correct position, although this is
  6708. obviously a bit slow.
  6709. @returns true if the stream manages to reposition itself correctly
  6710. @see getPosition
  6711. */
  6712. virtual bool setPosition (int64 newPosition) = 0;
  6713. /** Reads and discards a number of bytes from the stream.
  6714. Some input streams might implement this efficiently, but the base
  6715. class will just keep reading data until the requisite number of bytes
  6716. have been done.
  6717. */
  6718. virtual void skipNextBytes (int64 numBytesToSkip);
  6719. protected:
  6720. InputStream() noexcept {}
  6721. private:
  6722. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InputStream);
  6723. };
  6724. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6725. /*** End of inlined file: juce_InputStream.h ***/
  6726. #ifndef DOXYGEN
  6727. class ReferenceCountedObject;
  6728. class DynamicObject;
  6729. #endif
  6730. /**
  6731. A variant class, that can be used to hold a range of primitive values.
  6732. A var object can hold a range of simple primitive values, strings, or
  6733. any kind of ReferenceCountedObject. The var class is intended to act like
  6734. the kind of values used in dynamic scripting languages.
  6735. You can save/load var objects either in a small, proprietary binary format
  6736. using writeToStream()/readFromStream(), or as JSON by using the JSON class.
  6737. @see JSON, DynamicObject
  6738. */
  6739. class JUCE_API var
  6740. {
  6741. public:
  6742. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  6743. typedef Identifier identifier;
  6744. /** Creates a void variant. */
  6745. var() noexcept;
  6746. /** Destructor. */
  6747. ~var() noexcept;
  6748. /** A static var object that can be used where you need an empty variant object. */
  6749. static const var null;
  6750. var (const var& valueToCopy);
  6751. var (int value) noexcept;
  6752. var (int64 value) noexcept;
  6753. var (bool value) noexcept;
  6754. var (double value) noexcept;
  6755. var (const char* value);
  6756. var (const wchar_t* value);
  6757. var (const String& value);
  6758. var (const Array<var>& value);
  6759. var (ReferenceCountedObject* object);
  6760. var (MethodFunction method) noexcept;
  6761. const var& operator= (const var& valueToCopy);
  6762. const var& operator= (int value);
  6763. const var& operator= (int64 value);
  6764. const var& operator= (bool value);
  6765. const var& operator= (double value);
  6766. const var& operator= (const char* value);
  6767. const var& operator= (const wchar_t* value);
  6768. const var& operator= (const String& value);
  6769. const var& operator= (const Array<var>& value);
  6770. const var& operator= (ReferenceCountedObject* object);
  6771. const var& operator= (MethodFunction method);
  6772. void swapWith (var& other) noexcept;
  6773. operator int() const noexcept;
  6774. operator int64() const noexcept;
  6775. operator bool() const noexcept;
  6776. operator float() const noexcept;
  6777. operator double() const noexcept;
  6778. operator String() const;
  6779. String toString() const;
  6780. Array<var>* getArray() const noexcept;
  6781. ReferenceCountedObject* getObject() const noexcept;
  6782. DynamicObject* getDynamicObject() const noexcept;
  6783. bool isVoid() const noexcept;
  6784. bool isInt() const noexcept;
  6785. bool isInt64() const noexcept;
  6786. bool isBool() const noexcept;
  6787. bool isDouble() const noexcept;
  6788. bool isString() const noexcept;
  6789. bool isObject() const noexcept;
  6790. bool isArray() const noexcept;
  6791. bool isMethod() const noexcept;
  6792. /** Returns true if this var has the same value as the one supplied.
  6793. Note that this ignores the type, so a string var "123" and an integer var with the
  6794. value 123 are considered to be equal.
  6795. @see equalsWithSameType
  6796. */
  6797. bool equals (const var& other) const noexcept;
  6798. /** Returns true if this var has the same value and type as the one supplied.
  6799. This differs from equals() because e.g. "123" and 123 will be considered different.
  6800. @see equals
  6801. */
  6802. bool equalsWithSameType (const var& other) const noexcept;
  6803. /** If the var is an array, this returns the number of elements.
  6804. If the var isn't actually an array, this will return 0.
  6805. */
  6806. int size() const;
  6807. /** If the var is an array, this can be used to return one of its elements.
  6808. To call this method, you must make sure that the var is actually an array, and
  6809. that the index is a valid number. If these conditions aren't met, behaviour is
  6810. undefined.
  6811. For more control over the array's contents, you can call getArray() and manipulate
  6812. it directly as an Array\<var\>.
  6813. */
  6814. const var& operator[] (int arrayIndex) const;
  6815. /** If the var is an array, this can be used to return one of its elements.
  6816. To call this method, you must make sure that the var is actually an array, and
  6817. that the index is a valid number. If these conditions aren't met, behaviour is
  6818. undefined.
  6819. For more control over the array's contents, you can call getArray() and manipulate
  6820. it directly as an Array\<var\>.
  6821. */
  6822. var& operator[] (int arrayIndex);
  6823. /** Appends an element to the var, converting it to an array if it isn't already one.
  6824. If the var isn't an array, it will be converted to one, and if its value was non-void,
  6825. this value will be kept as the first element of the new array. The parameter value
  6826. will then be appended to it.
  6827. For more control over the array's contents, you can call getArray() and manipulate
  6828. it directly as an Array\<var\>.
  6829. */
  6830. void append (const var& valueToAppend);
  6831. /** Inserts an element to the var, converting it to an array if it isn't already one.
  6832. If the var isn't an array, it will be converted to one, and if its value was non-void,
  6833. this value will be kept as the first element of the new array. The parameter value
  6834. will then be inserted into it.
  6835. For more control over the array's contents, you can call getArray() and manipulate
  6836. it directly as an Array\<var\>.
  6837. */
  6838. void insert (int index, const var& value);
  6839. /** If the var is an array, this removes one of its elements.
  6840. If the index is out-of-range or the var isn't an array, nothing will be done.
  6841. For more control over the array's contents, you can call getArray() and manipulate
  6842. it directly as an Array\<var\>.
  6843. */
  6844. void remove (int index);
  6845. /** Treating the var as an array, this resizes it to contain the specified number of elements.
  6846. If the var isn't an array, it will be converted to one, and if its value was non-void,
  6847. this value will be kept as the first element of the new array before resizing.
  6848. For more control over the array's contents, you can call getArray() and manipulate
  6849. it directly as an Array\<var\>.
  6850. */
  6851. void resize (int numArrayElementsWanted);
  6852. /** If the var is an array, this searches it for the first occurrence of the specified value,
  6853. and returns its index.
  6854. If the var isn't an array, or if the value isn't found, this returns -1.
  6855. */
  6856. int indexOf (const var& value) const;
  6857. /** If this variant is an object, this returns one of its properties. */
  6858. var operator[] (const Identifier& propertyName) const;
  6859. /** If this variant is an object, this invokes one of its methods with no arguments. */
  6860. var call (const Identifier& method) const;
  6861. /** If this variant is an object, this invokes one of its methods with one argument. */
  6862. var call (const Identifier& method, const var& arg1) const;
  6863. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  6864. var call (const Identifier& method, const var& arg1, const var& arg2) const;
  6865. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  6866. var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  6867. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  6868. var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  6869. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  6870. var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  6871. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  6872. var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  6873. /** Writes a binary representation of this value to a stream.
  6874. The data can be read back later using readFromStream().
  6875. @see JSON
  6876. */
  6877. void writeToStream (OutputStream& output) const;
  6878. /** Reads back a stored binary representation of a value.
  6879. The data in the stream must have been written using writeToStream(), or this
  6880. will have unpredictable results.
  6881. @see JSON
  6882. */
  6883. static var readFromStream (InputStream& input);
  6884. private:
  6885. class VariantType; friend class VariantType;
  6886. class VariantType_Void; friend class VariantType_Void;
  6887. class VariantType_Int; friend class VariantType_Int;
  6888. class VariantType_Int64; friend class VariantType_Int64;
  6889. class VariantType_Double; friend class VariantType_Double;
  6890. class VariantType_Bool; friend class VariantType_Bool;
  6891. class VariantType_String; friend class VariantType_String;
  6892. class VariantType_Object; friend class VariantType_Object;
  6893. class VariantType_Array; friend class VariantType_Array;
  6894. class VariantType_Method; friend class VariantType_Method;
  6895. union ValueUnion
  6896. {
  6897. int intValue;
  6898. int64 int64Value;
  6899. bool boolValue;
  6900. double doubleValue;
  6901. char stringValue [sizeof (String)];
  6902. ReferenceCountedObject* objectValue;
  6903. Array<var>* arrayValue;
  6904. MethodFunction methodValue;
  6905. };
  6906. const VariantType* type;
  6907. ValueUnion value;
  6908. Array<var>* convertToArray();
  6909. friend class DynamicObject;
  6910. var invokeMethod (DynamicObject*, const var*, int) const;
  6911. };
  6912. /** Compares the values of two var objects, using the var::equals() comparison. */
  6913. bool operator== (const var& v1, const var& v2) noexcept;
  6914. /** Compares the values of two var objects, using the var::equals() comparison. */
  6915. bool operator!= (const var& v1, const var& v2) noexcept;
  6916. bool operator== (const var& v1, const String& v2);
  6917. bool operator!= (const var& v1, const String& v2);
  6918. bool operator== (const var& v1, const char* v2);
  6919. bool operator!= (const var& v1, const char* v2);
  6920. #endif // __JUCE_VARIANT_JUCEHEADER__
  6921. /*** End of inlined file: juce_Variant.h ***/
  6922. /*** Start of inlined file: juce_LinkedListPointer.h ***/
  6923. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  6924. #define __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  6925. /**
  6926. Helps to manipulate singly-linked lists of objects.
  6927. For objects that are designed to contain a pointer to the subsequent item in the
  6928. list, this class contains methods to deal with the list. To use it, the ObjectType
  6929. class that it points to must contain a LinkedListPointer called nextListItem, e.g.
  6930. @code
  6931. struct MyObject
  6932. {
  6933. int x, y, z;
  6934. // A linkable object must contain a member with this name and type, which must be
  6935. // accessible by the LinkedListPointer class. (This doesn't mean it has to be public -
  6936. // you could make your class a friend of a LinkedListPointer<MyObject> instead).
  6937. LinkedListPointer<MyObject> nextListItem;
  6938. };
  6939. LinkedListPointer<MyObject> myList;
  6940. myList.append (new MyObject());
  6941. myList.append (new MyObject());
  6942. int numItems = myList.size(); // returns 2
  6943. MyObject* lastInList = myList.getLast();
  6944. @endcode
  6945. */
  6946. template <class ObjectType>
  6947. class LinkedListPointer
  6948. {
  6949. public:
  6950. /** Creates a null pointer to an empty list. */
  6951. LinkedListPointer() noexcept
  6952. : item (nullptr)
  6953. {
  6954. }
  6955. /** Creates a pointer to a list whose head is the item provided. */
  6956. explicit LinkedListPointer (ObjectType* const headItem) noexcept
  6957. : item (headItem)
  6958. {
  6959. }
  6960. /** Sets this pointer to point to a new list. */
  6961. LinkedListPointer& operator= (ObjectType* const newItem) noexcept
  6962. {
  6963. item = newItem;
  6964. return *this;
  6965. }
  6966. /** Returns the item which this pointer points to. */
  6967. inline operator ObjectType*() const noexcept
  6968. {
  6969. return item;
  6970. }
  6971. /** Returns the item which this pointer points to. */
  6972. inline ObjectType* get() const noexcept
  6973. {
  6974. return item;
  6975. }
  6976. /** Returns the last item in the list which this pointer points to.
  6977. This will iterate the list and return the last item found. Obviously the speed
  6978. of this operation will be proportional to the size of the list. If the list is
  6979. empty the return value will be this object.
  6980. If you're planning on appending a number of items to your list, it's much more
  6981. efficient to use the Appender class than to repeatedly call getLast() to find the end.
  6982. */
  6983. LinkedListPointer& getLast() noexcept
  6984. {
  6985. LinkedListPointer* l = this;
  6986. while (l->item != nullptr)
  6987. l = &(l->item->nextListItem);
  6988. return *l;
  6989. }
  6990. /** Returns the number of items in the list.
  6991. Obviously with a simple linked list, getting the size involves iterating the list, so
  6992. this can be a lengthy operation - be careful when using this method in your code.
  6993. */
  6994. int size() const noexcept
  6995. {
  6996. int total = 0;
  6997. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  6998. ++total;
  6999. return total;
  7000. }
  7001. /** Returns the item at a given index in the list.
  7002. Since the only way to find an item is to iterate the list, this operation can obviously
  7003. be slow, depending on its size, so you should be careful when using this in algorithms.
  7004. */
  7005. LinkedListPointer& operator[] (int index) noexcept
  7006. {
  7007. LinkedListPointer* l = this;
  7008. while (--index >= 0 && l->item != nullptr)
  7009. l = &(l->item->nextListItem);
  7010. return *l;
  7011. }
  7012. /** Returns the item at a given index in the list.
  7013. Since the only way to find an item is to iterate the list, this operation can obviously
  7014. be slow, depending on its size, so you should be careful when using this in algorithms.
  7015. */
  7016. const LinkedListPointer& operator[] (int index) const noexcept
  7017. {
  7018. const LinkedListPointer* l = this;
  7019. while (--index >= 0 && l->item != nullptr)
  7020. l = &(l->item->nextListItem);
  7021. return *l;
  7022. }
  7023. /** Returns true if the list contains the given item. */
  7024. bool contains (const ObjectType* const itemToLookFor) const noexcept
  7025. {
  7026. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  7027. if (itemToLookFor == i)
  7028. return true;
  7029. return false;
  7030. }
  7031. /** Inserts an item into the list, placing it before the item that this pointer
  7032. currently points to.
  7033. */
  7034. void insertNext (ObjectType* const newItem)
  7035. {
  7036. jassert (newItem != nullptr);
  7037. jassert (newItem->nextListItem == nullptr);
  7038. newItem->nextListItem = item;
  7039. item = newItem;
  7040. }
  7041. /** Inserts an item at a numeric index in the list.
  7042. Obviously this will involve iterating the list to find the item at the given index,
  7043. so be careful about the impact this may have on execution time.
  7044. */
  7045. void insertAtIndex (int index, ObjectType* newItem)
  7046. {
  7047. jassert (newItem != nullptr);
  7048. LinkedListPointer* l = this;
  7049. while (index != 0 && l->item != nullptr)
  7050. {
  7051. l = &(l->item->nextListItem);
  7052. --index;
  7053. }
  7054. l->insertNext (newItem);
  7055. }
  7056. /** Replaces the object that this pointer points to, appending the rest of the list to
  7057. the new object, and returning the old one.
  7058. */
  7059. ObjectType* replaceNext (ObjectType* const newItem) noexcept
  7060. {
  7061. jassert (newItem != nullptr);
  7062. jassert (newItem->nextListItem == nullptr);
  7063. ObjectType* const oldItem = item;
  7064. item = newItem;
  7065. item->nextListItem = oldItem->nextListItem.item;
  7066. oldItem->nextListItem = (ObjectType*) 0;
  7067. return oldItem;
  7068. }
  7069. /** Adds an item to the end of the list.
  7070. This operation involves iterating the whole list, so can be slow - if you need to
  7071. append a number of items to your list, it's much more efficient to use the Appender
  7072. class than to repeatedly call append().
  7073. */
  7074. void append (ObjectType* const newItem)
  7075. {
  7076. getLast().item = newItem;
  7077. }
  7078. /** Creates copies of all the items in another list and adds them to this one.
  7079. This will use the ObjectType's copy constructor to try to create copies of each
  7080. item in the other list, and appends them to this list.
  7081. */
  7082. void addCopyOfList (const LinkedListPointer& other)
  7083. {
  7084. LinkedListPointer* insertPoint = this;
  7085. for (ObjectType* i = other.item; i != nullptr; i = i->nextListItem)
  7086. {
  7087. insertPoint->insertNext (new ObjectType (*i));
  7088. insertPoint = &(insertPoint->item->nextListItem);
  7089. }
  7090. }
  7091. /** Removes the head item from the list.
  7092. This won't delete the object that is removed, but returns it, so the caller can
  7093. delete it if necessary.
  7094. */
  7095. ObjectType* removeNext() noexcept
  7096. {
  7097. ObjectType* const oldItem = item;
  7098. if (oldItem != nullptr)
  7099. {
  7100. item = oldItem->nextListItem;
  7101. oldItem->nextListItem = (ObjectType*) 0;
  7102. }
  7103. return oldItem;
  7104. }
  7105. /** Removes a specific item from the list.
  7106. Note that this will not delete the item, it simply unlinks it from the list.
  7107. */
  7108. void remove (ObjectType* const itemToRemove)
  7109. {
  7110. LinkedListPointer* const l = findPointerTo (itemToRemove);
  7111. if (l != nullptr)
  7112. l->removeNext();
  7113. }
  7114. /** Iterates the list, calling the delete operator on all of its elements and
  7115. leaving this pointer empty.
  7116. */
  7117. void deleteAll()
  7118. {
  7119. while (item != nullptr)
  7120. {
  7121. ObjectType* const oldItem = item;
  7122. item = oldItem->nextListItem;
  7123. delete oldItem;
  7124. }
  7125. }
  7126. /** Finds a pointer to a given item.
  7127. If the item is found in the list, this returns the pointer that points to it. If
  7128. the item isn't found, this returns null.
  7129. */
  7130. LinkedListPointer* findPointerTo (ObjectType* const itemToLookFor) noexcept
  7131. {
  7132. LinkedListPointer* l = this;
  7133. while (l->item != nullptr)
  7134. {
  7135. if (l->item == itemToLookFor)
  7136. return l;
  7137. l = &(l->item->nextListItem);
  7138. }
  7139. return nullptr;
  7140. }
  7141. /** Copies the items in the list to an array.
  7142. The destArray must contain enough elements to hold the entire list - no checks are
  7143. made for this!
  7144. */
  7145. void copyToArray (ObjectType** destArray) const noexcept
  7146. {
  7147. jassert (destArray != nullptr);
  7148. for (ObjectType* i = item; i != nullptr; i = i->nextListItem)
  7149. *destArray++ = i;
  7150. }
  7151. /**
  7152. Allows efficient repeated insertions into a list.
  7153. You can create an Appender object which points to the last element in your
  7154. list, and then repeatedly call Appender::append() to add items to the end
  7155. of the list in O(1) time.
  7156. */
  7157. class Appender
  7158. {
  7159. public:
  7160. /** Creates an appender which will add items to the given list.
  7161. */
  7162. Appender (LinkedListPointer& endOfListPointer) noexcept
  7163. : endOfList (&endOfListPointer)
  7164. {
  7165. // This can only be used to add to the end of a list.
  7166. jassert (endOfListPointer.item == nullptr);
  7167. }
  7168. /** Appends an item to the list. */
  7169. void append (ObjectType* const newItem) noexcept
  7170. {
  7171. *endOfList = newItem;
  7172. endOfList = &(newItem->nextListItem);
  7173. }
  7174. private:
  7175. LinkedListPointer* endOfList;
  7176. JUCE_DECLARE_NON_COPYABLE (Appender);
  7177. };
  7178. private:
  7179. ObjectType* item;
  7180. JUCE_DECLARE_NON_COPYABLE (LinkedListPointer);
  7181. };
  7182. #endif // __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7183. /*** End of inlined file: juce_LinkedListPointer.h ***/
  7184. class XmlElement;
  7185. #ifndef DOXYGEN
  7186. class JSONFormatter;
  7187. #endif
  7188. /** Holds a set of named var objects.
  7189. This can be used as a basic structure to hold a set of var object, which can
  7190. be retrieved by using their identifier.
  7191. */
  7192. class JUCE_API NamedValueSet
  7193. {
  7194. public:
  7195. /** Creates an empty set. */
  7196. NamedValueSet() noexcept;
  7197. /** Creates a copy of another set. */
  7198. NamedValueSet (const NamedValueSet& other);
  7199. /** Replaces this set with a copy of another set. */
  7200. NamedValueSet& operator= (const NamedValueSet& other);
  7201. /** Destructor. */
  7202. ~NamedValueSet();
  7203. bool operator== (const NamedValueSet& other) const;
  7204. bool operator!= (const NamedValueSet& other) const;
  7205. /** Returns the total number of values that the set contains. */
  7206. int size() const noexcept;
  7207. /** Returns the value of a named item.
  7208. If the name isn't found, this will return a void variant.
  7209. @see getProperty
  7210. */
  7211. const var& operator[] (const Identifier& name) const;
  7212. /** Tries to return the named value, but if no such value is found, this will
  7213. instead return the supplied default value.
  7214. */
  7215. var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  7216. /** Changes or adds a named value.
  7217. @returns true if a value was changed or added; false if the
  7218. value was already set the the value passed-in.
  7219. */
  7220. bool set (const Identifier& name, const var& newValue);
  7221. /** Returns true if the set contains an item with the specified name. */
  7222. bool contains (const Identifier& name) const;
  7223. /** Removes a value from the set.
  7224. @returns true if a value was removed; false if there was no value
  7225. with the name that was given.
  7226. */
  7227. bool remove (const Identifier& name);
  7228. /** Returns the name of the value at a given index.
  7229. The index must be between 0 and size() - 1.
  7230. */
  7231. const Identifier getName (int index) const;
  7232. /** Returns the value of the item at a given index.
  7233. The index must be between 0 and size() - 1.
  7234. */
  7235. const var& getValueAt (int index) const;
  7236. /** Removes all values. */
  7237. void clear();
  7238. /** Returns a pointer to the var that holds a named value, or null if there is
  7239. no value with this name.
  7240. Do not use this method unless you really need access to the internal var object
  7241. for some reason - for normal reading and writing always prefer operator[]() and set().
  7242. */
  7243. var* getVarPointer (const Identifier& name) const noexcept;
  7244. /** Sets properties to the values of all of an XML element's attributes. */
  7245. void setFromXmlAttributes (const XmlElement& xml);
  7246. /** Sets attributes in an XML element corresponding to each of this object's
  7247. properties.
  7248. */
  7249. void copyToXmlAttributes (XmlElement& xml) const;
  7250. private:
  7251. class NamedValue
  7252. {
  7253. public:
  7254. NamedValue() noexcept;
  7255. NamedValue (const NamedValue&);
  7256. NamedValue (const Identifier& name, const var& value);
  7257. NamedValue& operator= (const NamedValue&);
  7258. bool operator== (const NamedValue& other) const noexcept;
  7259. LinkedListPointer<NamedValue> nextListItem;
  7260. Identifier name;
  7261. var value;
  7262. private:
  7263. JUCE_LEAK_DETECTOR (NamedValue);
  7264. };
  7265. friend class LinkedListPointer<NamedValue>;
  7266. LinkedListPointer<NamedValue> values;
  7267. friend class JSONFormatter;
  7268. };
  7269. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  7270. /*** End of inlined file: juce_NamedValueSet.h ***/
  7271. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  7272. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7273. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7274. /**
  7275. Adds reference-counting to an object.
  7276. To add reference-counting to a class, derive it from this class, and
  7277. use the ReferenceCountedObjectPtr class to point to it.
  7278. e.g. @code
  7279. class MyClass : public ReferenceCountedObject
  7280. {
  7281. void foo();
  7282. // This is a neat way of declaring a typedef for a pointer class,
  7283. // rather than typing out the full templated name each time..
  7284. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7285. };
  7286. MyClass::Ptr p = new MyClass();
  7287. MyClass::Ptr p2 = p;
  7288. p = nullptr;
  7289. p2->foo();
  7290. @endcode
  7291. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7292. careful not to delete the object manually.
  7293. This class uses an Atomic<int> value to hold the reference count, so that it
  7294. the pointers can be passed between threads safely. For a faster but non-thread-safe
  7295. version, use SingleThreadedReferenceCountedObject instead.
  7296. @see ReferenceCountedObjectPtr, ReferenceCountedArray, SingleThreadedReferenceCountedObject
  7297. */
  7298. class JUCE_API ReferenceCountedObject
  7299. {
  7300. public:
  7301. /** Increments the object's reference count.
  7302. This is done automatically by the smart pointer, but is public just
  7303. in case it's needed for nefarious purposes.
  7304. */
  7305. inline void incReferenceCount() noexcept
  7306. {
  7307. ++refCount;
  7308. }
  7309. /** Decreases the object's reference count.
  7310. If the count gets to zero, the object will be deleted.
  7311. */
  7312. inline void decReferenceCount() noexcept
  7313. {
  7314. jassert (getReferenceCount() > 0);
  7315. if (--refCount == 0)
  7316. delete this;
  7317. }
  7318. /** Returns the object's current reference count. */
  7319. inline int getReferenceCount() const noexcept { return refCount.get(); }
  7320. protected:
  7321. /** Creates the reference-counted object (with an initial ref count of zero). */
  7322. ReferenceCountedObject()
  7323. {
  7324. }
  7325. /** Destructor. */
  7326. virtual ~ReferenceCountedObject()
  7327. {
  7328. // it's dangerous to delete an object that's still referenced by something else!
  7329. jassert (getReferenceCount() == 0);
  7330. }
  7331. private:
  7332. Atomic <int> refCount;
  7333. };
  7334. /**
  7335. Adds reference-counting to an object.
  7336. This is efectively a version of the ReferenceCountedObject class, but which
  7337. uses a non-atomic counter, and so is not thread-safe (but which will be more
  7338. efficient).
  7339. For more details on how to use it, see the ReferenceCountedObject class notes.
  7340. @see ReferenceCountedObject, ReferenceCountedObjectPtr, ReferenceCountedArray
  7341. */
  7342. class JUCE_API SingleThreadedReferenceCountedObject
  7343. {
  7344. public:
  7345. /** Increments the object's reference count.
  7346. This is done automatically by the smart pointer, but is public just
  7347. in case it's needed for nefarious purposes.
  7348. */
  7349. inline void incReferenceCount() noexcept
  7350. {
  7351. ++refCount;
  7352. }
  7353. /** Decreases the object's reference count.
  7354. If the count gets to zero, the object will be deleted.
  7355. */
  7356. inline void decReferenceCount() noexcept
  7357. {
  7358. jassert (getReferenceCount() > 0);
  7359. if (--refCount == 0)
  7360. delete this;
  7361. }
  7362. /** Returns the object's current reference count. */
  7363. inline int getReferenceCount() const noexcept { return refCount; }
  7364. protected:
  7365. /** Creates the reference-counted object (with an initial ref count of zero). */
  7366. SingleThreadedReferenceCountedObject() : refCount (0) {}
  7367. /** Destructor. */
  7368. virtual ~SingleThreadedReferenceCountedObject()
  7369. {
  7370. // it's dangerous to delete an object that's still referenced by something else!
  7371. jassert (getReferenceCount() == 0);
  7372. }
  7373. private:
  7374. int refCount;
  7375. };
  7376. /**
  7377. A smart-pointer class which points to a reference-counted object.
  7378. The template parameter specifies the class of the object you want to point to - the easiest
  7379. way to make a class reference-countable is to simply make it inherit from ReferenceCountedObject,
  7380. but if you need to, you could roll your own reference-countable class by implementing a pair of
  7381. mathods called incReferenceCount() and decReferenceCount().
  7382. When using this class, you'll probably want to create a typedef to abbreviate the full
  7383. templated name - e.g.
  7384. @code typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;@endcode
  7385. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7386. */
  7387. template <class ReferenceCountedObjectClass>
  7388. class ReferenceCountedObjectPtr
  7389. {
  7390. public:
  7391. /** The class being referenced by this pointer. */
  7392. typedef ReferenceCountedObjectClass ReferencedType;
  7393. /** Creates a pointer to a null object. */
  7394. inline ReferenceCountedObjectPtr() noexcept
  7395. : referencedObject (nullptr)
  7396. {
  7397. }
  7398. /** Creates a pointer to an object.
  7399. This will increment the object's reference-count if it is non-null.
  7400. */
  7401. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) noexcept
  7402. : referencedObject (refCountedObject)
  7403. {
  7404. if (refCountedObject != nullptr)
  7405. refCountedObject->incReferenceCount();
  7406. }
  7407. /** Copies another pointer.
  7408. This will increment the object's reference-count (if it is non-null).
  7409. */
  7410. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) noexcept
  7411. : referencedObject (other.referencedObject)
  7412. {
  7413. if (referencedObject != nullptr)
  7414. referencedObject->incReferenceCount();
  7415. }
  7416. /** Changes this pointer to point at a different object.
  7417. The reference count of the old object is decremented, and it might be
  7418. deleted if it hits zero. The new object's count is incremented.
  7419. */
  7420. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7421. {
  7422. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7423. if (newObject != referencedObject)
  7424. {
  7425. if (newObject != nullptr)
  7426. newObject->incReferenceCount();
  7427. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7428. referencedObject = newObject;
  7429. if (oldObject != nullptr)
  7430. oldObject->decReferenceCount();
  7431. }
  7432. return *this;
  7433. }
  7434. /** Changes this pointer to point at a different object.
  7435. The reference count of the old object is decremented, and it might be
  7436. deleted if it hits zero. The new object's count is incremented.
  7437. */
  7438. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7439. {
  7440. if (referencedObject != newObject)
  7441. {
  7442. if (newObject != nullptr)
  7443. newObject->incReferenceCount();
  7444. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7445. referencedObject = newObject;
  7446. if (oldObject != nullptr)
  7447. oldObject->decReferenceCount();
  7448. }
  7449. return *this;
  7450. }
  7451. /** Destructor.
  7452. This will decrement the object's reference-count, and may delete it if it
  7453. gets to zero.
  7454. */
  7455. inline ~ReferenceCountedObjectPtr()
  7456. {
  7457. if (referencedObject != nullptr)
  7458. referencedObject->decReferenceCount();
  7459. }
  7460. /** Returns the object that this pointer references.
  7461. The pointer returned may be zero, of course.
  7462. */
  7463. inline operator ReferenceCountedObjectClass*() const noexcept
  7464. {
  7465. return referencedObject;
  7466. }
  7467. // the -> operator is called on the referenced object
  7468. inline ReferenceCountedObjectClass* operator->() const noexcept
  7469. {
  7470. return referencedObject;
  7471. }
  7472. /** Returns the object that this pointer references.
  7473. The pointer returned may be zero, of course.
  7474. */
  7475. inline ReferenceCountedObjectClass* getObject() const noexcept
  7476. {
  7477. return referencedObject;
  7478. }
  7479. private:
  7480. ReferenceCountedObjectClass* referencedObject;
  7481. };
  7482. /** Compares two ReferenceCountedObjectPointers. */
  7483. template <class ReferenceCountedObjectClass>
  7484. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectClass* const object2) noexcept
  7485. {
  7486. return object1.getObject() == object2;
  7487. }
  7488. /** Compares two ReferenceCountedObjectPointers. */
  7489. template <class ReferenceCountedObjectClass>
  7490. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7491. {
  7492. return object1.getObject() == object2.getObject();
  7493. }
  7494. /** Compares two ReferenceCountedObjectPointers. */
  7495. template <class ReferenceCountedObjectClass>
  7496. bool operator== (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7497. {
  7498. return object1 == object2.getObject();
  7499. }
  7500. /** Compares two ReferenceCountedObjectPointers. */
  7501. template <class ReferenceCountedObjectClass>
  7502. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectClass* object2) noexcept
  7503. {
  7504. return object1.getObject() != object2;
  7505. }
  7506. /** Compares two ReferenceCountedObjectPointers. */
  7507. template <class ReferenceCountedObjectClass>
  7508. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7509. {
  7510. return object1.getObject() != object2.getObject();
  7511. }
  7512. /** Compares two ReferenceCountedObjectPointers. */
  7513. template <class ReferenceCountedObjectClass>
  7514. bool operator!= (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) noexcept
  7515. {
  7516. return object1 != object2.getObject();
  7517. }
  7518. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7519. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  7520. /**
  7521. Represents a dynamically implemented object.
  7522. This class is primarily intended for wrapping scripting language objects,
  7523. but could be used for other purposes.
  7524. An instance of a DynamicObject can be used to store named properties, and
  7525. by subclassing hasMethod() and invokeMethod(), you can give your object
  7526. methods.
  7527. */
  7528. class JUCE_API DynamicObject : public ReferenceCountedObject
  7529. {
  7530. public:
  7531. DynamicObject();
  7532. /** Destructor. */
  7533. virtual ~DynamicObject();
  7534. /** Returns true if the object has a property with this name.
  7535. Note that if the property is actually a method, this will return false.
  7536. */
  7537. virtual bool hasProperty (const Identifier& propertyName) const;
  7538. /** Returns a named property.
  7539. This returns a void if no such property exists.
  7540. */
  7541. virtual var getProperty (const Identifier& propertyName) const;
  7542. /** Sets a named property. */
  7543. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  7544. /** Removes a named property. */
  7545. virtual void removeProperty (const Identifier& propertyName);
  7546. /** Checks whether this object has the specified method.
  7547. The default implementation of this just checks whether there's a property
  7548. with this name that's actually a method, but this can be overridden for
  7549. building objects with dynamic invocation.
  7550. */
  7551. virtual bool hasMethod (const Identifier& methodName) const;
  7552. /** Invokes a named method on this object.
  7553. The default implementation looks up the named property, and if it's a method
  7554. call, then it invokes it.
  7555. This method is virtual to allow more dynamic invocation to used for objects
  7556. where the methods may not already be set as properies.
  7557. */
  7558. virtual var invokeMethod (const Identifier& methodName,
  7559. const var* parameters,
  7560. int numParameters);
  7561. /** Sets up a method.
  7562. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  7563. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  7564. the code easier to read,
  7565. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  7566. @code
  7567. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  7568. @endcode
  7569. */
  7570. void setMethod (const Identifier& methodName,
  7571. var::MethodFunction methodFunction);
  7572. /** Removes all properties and methods from the object. */
  7573. void clear();
  7574. /** Returns the NamedValueSet that holds the object's properties. */
  7575. NamedValueSet& getProperties() noexcept { return properties; }
  7576. private:
  7577. NamedValueSet properties;
  7578. JUCE_LEAK_DETECTOR (DynamicObject);
  7579. };
  7580. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  7581. /*** End of inlined file: juce_DynamicObject.h ***/
  7582. #endif
  7583. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  7584. #endif
  7585. #ifndef __JUCE_HASHMAP_JUCEHEADER__
  7586. /*** Start of inlined file: juce_HashMap.h ***/
  7587. #ifndef __JUCE_HASHMAP_JUCEHEADER__
  7588. #define __JUCE_HASHMAP_JUCEHEADER__
  7589. /*** Start of inlined file: juce_OwnedArray.h ***/
  7590. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7591. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  7592. /** An array designed for holding objects.
  7593. This holds a list of pointers to objects, and will automatically
  7594. delete the objects when they are removed from the array, or when the
  7595. array is itself deleted.
  7596. Declare it in the form: OwnedArray<MyObjectClass>
  7597. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  7598. After adding objects, they are 'owned' by the array and will be deleted when
  7599. removed or replaced.
  7600. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7601. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7602. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  7603. */
  7604. template <class ObjectClass,
  7605. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7606. class OwnedArray
  7607. {
  7608. public:
  7609. /** Creates an empty array. */
  7610. OwnedArray() noexcept
  7611. : numUsed (0)
  7612. {
  7613. }
  7614. /** Deletes the array and also deletes any objects inside it.
  7615. To get rid of the array without deleting its objects, use its
  7616. clear (false) method before deleting it.
  7617. */
  7618. ~OwnedArray()
  7619. {
  7620. clear (true);
  7621. }
  7622. /** Clears the array, optionally deleting the objects inside it first. */
  7623. void clear (const bool deleteObjects = true)
  7624. {
  7625. const ScopedLockType lock (getLock());
  7626. if (deleteObjects)
  7627. {
  7628. while (numUsed > 0)
  7629. delete data.elements [--numUsed];
  7630. }
  7631. data.setAllocatedSize (0);
  7632. numUsed = 0;
  7633. }
  7634. /** Returns the number of items currently in the array.
  7635. @see operator[]
  7636. */
  7637. inline int size() const noexcept
  7638. {
  7639. return numUsed;
  7640. }
  7641. /** Returns a pointer to the object at this index in the array.
  7642. If the index is out-of-range, this will return a null pointer, (and
  7643. it could be null anyway, because it's ok for the array to hold null
  7644. pointers as well as objects).
  7645. @see getUnchecked
  7646. */
  7647. inline ObjectClass* operator[] (const int index) const noexcept
  7648. {
  7649. const ScopedLockType lock (getLock());
  7650. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  7651. : static_cast <ObjectClass*> (nullptr);
  7652. }
  7653. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7654. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7655. it can be used when you're sure the index if always going to be legal.
  7656. */
  7657. inline ObjectClass* getUnchecked (const int index) const noexcept
  7658. {
  7659. const ScopedLockType lock (getLock());
  7660. jassert (isPositiveAndBelow (index, numUsed));
  7661. return data.elements [index];
  7662. }
  7663. /** Returns a pointer to the first object in the array.
  7664. This will return a null pointer if the array's empty.
  7665. @see getLast
  7666. */
  7667. inline ObjectClass* getFirst() const noexcept
  7668. {
  7669. const ScopedLockType lock (getLock());
  7670. return numUsed > 0 ? data.elements [0]
  7671. : static_cast <ObjectClass*> (nullptr);
  7672. }
  7673. /** Returns a pointer to the last object in the array.
  7674. This will return a null pointer if the array's empty.
  7675. @see getFirst
  7676. */
  7677. inline ObjectClass* getLast() const noexcept
  7678. {
  7679. const ScopedLockType lock (getLock());
  7680. return numUsed > 0 ? data.elements [numUsed - 1]
  7681. : static_cast <ObjectClass*> (nullptr);
  7682. }
  7683. /** Returns a pointer to the actual array data.
  7684. This pointer will only be valid until the next time a non-const method
  7685. is called on the array.
  7686. */
  7687. inline ObjectClass** getRawDataPointer() noexcept
  7688. {
  7689. return data.elements;
  7690. }
  7691. /** Returns a pointer to the first element in the array.
  7692. This method is provided for compatibility with standard C++ iteration mechanisms.
  7693. */
  7694. inline ObjectClass** begin() const noexcept
  7695. {
  7696. return data.elements;
  7697. }
  7698. /** Returns a pointer to the element which follows the last element in the array.
  7699. This method is provided for compatibility with standard C++ iteration mechanisms.
  7700. */
  7701. inline ObjectClass** end() const noexcept
  7702. {
  7703. return data.elements + numUsed;
  7704. }
  7705. /** Finds the index of an object which might be in the array.
  7706. @param objectToLookFor the object to look for
  7707. @returns the index at which the object was found, or -1 if it's not found
  7708. */
  7709. int indexOf (const ObjectClass* const objectToLookFor) const noexcept
  7710. {
  7711. const ScopedLockType lock (getLock());
  7712. ObjectClass* const* e = data.elements.getData();
  7713. ObjectClass* const* const end_ = e + numUsed;
  7714. for (; e != end_; ++e)
  7715. if (objectToLookFor == *e)
  7716. return static_cast <int> (e - data.elements.getData());
  7717. return -1;
  7718. }
  7719. /** Returns true if the array contains a specified object.
  7720. @param objectToLookFor the object to look for
  7721. @returns true if the object is in the array
  7722. */
  7723. bool contains (const ObjectClass* const objectToLookFor) const noexcept
  7724. {
  7725. const ScopedLockType lock (getLock());
  7726. ObjectClass* const* e = data.elements.getData();
  7727. ObjectClass* const* const end_ = e + numUsed;
  7728. for (; e != end_; ++e)
  7729. if (objectToLookFor == *e)
  7730. return true;
  7731. return false;
  7732. }
  7733. /** Appends a new object to the end of the array.
  7734. Note that the this object will be deleted by the OwnedArray when it
  7735. is removed, so be careful not to delete it somewhere else.
  7736. Also be careful not to add the same object to the array more than once,
  7737. as this will obviously cause deletion of dangling pointers.
  7738. @param newObject the new object to add to the array
  7739. @see set, insert, addIfNotAlreadyThere, addSorted
  7740. */
  7741. void add (const ObjectClass* const newObject) noexcept
  7742. {
  7743. const ScopedLockType lock (getLock());
  7744. data.ensureAllocatedSize (numUsed + 1);
  7745. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7746. }
  7747. /** Inserts a new object into the array at the given index.
  7748. Note that the this object will be deleted by the OwnedArray when it
  7749. is removed, so be careful not to delete it somewhere else.
  7750. If the index is less than 0 or greater than the size of the array, the
  7751. element will be added to the end of the array.
  7752. Otherwise, it will be inserted into the array, moving all the later elements
  7753. along to make room.
  7754. Be careful not to add the same object to the array more than once,
  7755. as this will obviously cause deletion of dangling pointers.
  7756. @param indexToInsertAt the index at which the new element should be inserted
  7757. @param newObject the new object to add to the array
  7758. @see add, addSorted, addIfNotAlreadyThere, set
  7759. */
  7760. void insert (int indexToInsertAt,
  7761. const ObjectClass* const newObject) noexcept
  7762. {
  7763. if (indexToInsertAt >= 0)
  7764. {
  7765. const ScopedLockType lock (getLock());
  7766. if (indexToInsertAt > numUsed)
  7767. indexToInsertAt = numUsed;
  7768. data.ensureAllocatedSize (numUsed + 1);
  7769. ObjectClass** const e = data.elements + indexToInsertAt;
  7770. const int numToMove = numUsed - indexToInsertAt;
  7771. if (numToMove > 0)
  7772. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7773. *e = const_cast <ObjectClass*> (newObject);
  7774. ++numUsed;
  7775. }
  7776. else
  7777. {
  7778. add (newObject);
  7779. }
  7780. }
  7781. /** Appends a new object at the end of the array as long as the array doesn't
  7782. already contain it.
  7783. If the array already contains a matching object, nothing will be done.
  7784. @param newObject the new object to add to the array
  7785. */
  7786. void addIfNotAlreadyThere (const ObjectClass* const newObject) noexcept
  7787. {
  7788. const ScopedLockType lock (getLock());
  7789. if (! contains (newObject))
  7790. add (newObject);
  7791. }
  7792. /** Replaces an object in the array with a different one.
  7793. If the index is less than zero, this method does nothing.
  7794. If the index is beyond the end of the array, the new object is added to the end of the array.
  7795. Be careful not to add the same object to the array more than once,
  7796. as this will obviously cause deletion of dangling pointers.
  7797. @param indexToChange the index whose value you want to change
  7798. @param newObject the new value to set for this index.
  7799. @param deleteOldElement whether to delete the object that's being replaced with the new one
  7800. @see add, insert, remove
  7801. */
  7802. void set (const int indexToChange,
  7803. const ObjectClass* const newObject,
  7804. const bool deleteOldElement = true)
  7805. {
  7806. if (indexToChange >= 0)
  7807. {
  7808. ObjectClass* toDelete = nullptr;
  7809. {
  7810. const ScopedLockType lock (getLock());
  7811. if (indexToChange < numUsed)
  7812. {
  7813. if (deleteOldElement)
  7814. {
  7815. toDelete = data.elements [indexToChange];
  7816. if (toDelete == newObject)
  7817. toDelete = nullptr;
  7818. }
  7819. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  7820. }
  7821. else
  7822. {
  7823. data.ensureAllocatedSize (numUsed + 1);
  7824. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7825. }
  7826. }
  7827. delete toDelete; // don't want to use a ScopedPointer here because if the
  7828. // object has a private destructor, both OwnedArray and
  7829. // ScopedPointer would need to be friend classes..
  7830. }
  7831. else
  7832. {
  7833. jassertfalse; // you're trying to set an object at a negative index, which doesn't have
  7834. // any effect - but since the object is not being added, it may be leaking..
  7835. }
  7836. }
  7837. /** Adds elements from another array to the end of this array.
  7838. @param arrayToAddFrom the array from which to copy the elements
  7839. @param startIndex the first element of the other array to start copying from
  7840. @param numElementsToAdd how many elements to add from the other array. If this
  7841. value is negative or greater than the number of available elements,
  7842. all available elements will be copied.
  7843. @see add
  7844. */
  7845. template <class OtherArrayType>
  7846. void addArray (const OtherArrayType& arrayToAddFrom,
  7847. int startIndex = 0,
  7848. int numElementsToAdd = -1)
  7849. {
  7850. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7851. const ScopedLockType lock2 (getLock());
  7852. if (startIndex < 0)
  7853. {
  7854. jassertfalse;
  7855. startIndex = 0;
  7856. }
  7857. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7858. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7859. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7860. while (--numElementsToAdd >= 0)
  7861. {
  7862. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  7863. ++numUsed;
  7864. }
  7865. }
  7866. /** Adds copies of the elements in another array to the end of this array.
  7867. The other array must be either an OwnedArray of a compatible type of object, or an Array
  7868. containing pointers to the same kind of object. The objects involved must provide
  7869. a copy constructor, and this will be used to create new copies of each element, and
  7870. add them to this array.
  7871. @param arrayToAddFrom the array from which to copy the elements
  7872. @param startIndex the first element of the other array to start copying from
  7873. @param numElementsToAdd how many elements to add from the other array. If this
  7874. value is negative or greater than the number of available elements,
  7875. all available elements will be copied.
  7876. @see add
  7877. */
  7878. template <class OtherArrayType>
  7879. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  7880. int startIndex = 0,
  7881. int numElementsToAdd = -1)
  7882. {
  7883. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7884. const ScopedLockType lock2 (getLock());
  7885. if (startIndex < 0)
  7886. {
  7887. jassertfalse;
  7888. startIndex = 0;
  7889. }
  7890. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7891. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7892. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7893. while (--numElementsToAdd >= 0)
  7894. {
  7895. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  7896. ++numUsed;
  7897. }
  7898. }
  7899. /** Inserts a new object into the array assuming that the array is sorted.
  7900. This will use a comparator to find the position at which the new object
  7901. should go. If the array isn't sorted, the behaviour of this
  7902. method will be unpredictable.
  7903. @param comparator the comparator to use to compare the elements - see the sort method
  7904. for details about this object's structure
  7905. @param newObject the new object to insert to the array
  7906. @returns the index at which the new object was added
  7907. @see add, sort, indexOfSorted
  7908. */
  7909. template <class ElementComparator>
  7910. int addSorted (ElementComparator& comparator, ObjectClass* const newObject) noexcept
  7911. {
  7912. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7913. // avoids getting warning messages about the parameter being unused
  7914. const ScopedLockType lock (getLock());
  7915. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  7916. insert (index, newObject);
  7917. return index;
  7918. }
  7919. /** Finds the index of an object in the array, assuming that the array is sorted.
  7920. This will use a comparator to do a binary-chop to find the index of the given
  7921. element, if it exists. If the array isn't sorted, the behaviour of this
  7922. method will be unpredictable.
  7923. @param comparator the comparator to use to compare the elements - see the sort()
  7924. method for details about the form this object should take
  7925. @param objectToLookFor the object to search for
  7926. @returns the index of the element, or -1 if it's not found
  7927. @see addSorted, sort
  7928. */
  7929. template <class ElementComparator>
  7930. int indexOfSorted (ElementComparator& comparator,
  7931. const ObjectClass* const objectToLookFor) const noexcept
  7932. {
  7933. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7934. // avoids getting warning messages about the parameter being unused
  7935. const ScopedLockType lock (getLock());
  7936. int start = 0;
  7937. int end_ = numUsed;
  7938. for (;;)
  7939. {
  7940. if (start >= end_)
  7941. {
  7942. return -1;
  7943. }
  7944. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  7945. {
  7946. return start;
  7947. }
  7948. else
  7949. {
  7950. const int halfway = (start + end_) >> 1;
  7951. if (halfway == start)
  7952. return -1;
  7953. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  7954. start = halfway;
  7955. else
  7956. end_ = halfway;
  7957. }
  7958. }
  7959. }
  7960. /** Removes an object from the array.
  7961. This will remove the object at a given index (optionally also
  7962. deleting it) and move back all the subsequent objects to close the gap.
  7963. If the index passed in is out-of-range, nothing will happen.
  7964. @param indexToRemove the index of the element to remove
  7965. @param deleteObject whether to delete the object that is removed
  7966. @see removeObject, removeRange
  7967. */
  7968. void remove (const int indexToRemove,
  7969. const bool deleteObject = true)
  7970. {
  7971. ObjectClass* toDelete = nullptr;
  7972. {
  7973. const ScopedLockType lock (getLock());
  7974. if (isPositiveAndBelow (indexToRemove, numUsed))
  7975. {
  7976. ObjectClass** const e = data.elements + indexToRemove;
  7977. if (deleteObject)
  7978. toDelete = *e;
  7979. --numUsed;
  7980. const int numToShift = numUsed - indexToRemove;
  7981. if (numToShift > 0)
  7982. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  7983. }
  7984. }
  7985. delete toDelete; // don't want to use a ScopedPointer here because if the
  7986. // object has a private destructor, both OwnedArray and
  7987. // ScopedPointer would need to be friend classes..
  7988. if ((numUsed << 1) < data.numAllocated)
  7989. minimiseStorageOverheads();
  7990. }
  7991. /** Removes and returns an object from the array without deleting it.
  7992. This will remove the object at a given index and return it, moving back all
  7993. the subsequent objects to close the gap. If the index passed in is out-of-range,
  7994. nothing will happen.
  7995. @param indexToRemove the index of the element to remove
  7996. @see remove, removeObject, removeRange
  7997. */
  7998. ObjectClass* removeAndReturn (const int indexToRemove)
  7999. {
  8000. ObjectClass* removedItem = nullptr;
  8001. const ScopedLockType lock (getLock());
  8002. if (isPositiveAndBelow (indexToRemove, numUsed))
  8003. {
  8004. ObjectClass** const e = data.elements + indexToRemove;
  8005. removedItem = *e;
  8006. --numUsed;
  8007. const int numToShift = numUsed - indexToRemove;
  8008. if (numToShift > 0)
  8009. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  8010. if ((numUsed << 1) < data.numAllocated)
  8011. minimiseStorageOverheads();
  8012. }
  8013. return removedItem;
  8014. }
  8015. /** Removes a specified object from the array.
  8016. If the item isn't found, no action is taken.
  8017. @param objectToRemove the object to try to remove
  8018. @param deleteObject whether to delete the object (if it's found)
  8019. @see remove, removeRange
  8020. */
  8021. void removeObject (const ObjectClass* const objectToRemove,
  8022. const bool deleteObject = true)
  8023. {
  8024. const ScopedLockType lock (getLock());
  8025. ObjectClass** const e = data.elements.getData();
  8026. for (int i = 0; i < numUsed; ++i)
  8027. {
  8028. if (objectToRemove == e[i])
  8029. {
  8030. remove (i, deleteObject);
  8031. break;
  8032. }
  8033. }
  8034. }
  8035. /** Removes a range of objects from the array.
  8036. This will remove a set of objects, starting from the given index,
  8037. and move any subsequent elements down to close the gap.
  8038. If the range extends beyond the bounds of the array, it will
  8039. be safely clipped to the size of the array.
  8040. @param startIndex the index of the first object to remove
  8041. @param numberToRemove how many objects should be removed
  8042. @param deleteObjects whether to delete the objects that get removed
  8043. @see remove, removeObject
  8044. */
  8045. void removeRange (int startIndex,
  8046. const int numberToRemove,
  8047. const bool deleteObjects = true)
  8048. {
  8049. const ScopedLockType lock (getLock());
  8050. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  8051. startIndex = jlimit (0, numUsed, startIndex);
  8052. if (endIndex > startIndex)
  8053. {
  8054. if (deleteObjects)
  8055. {
  8056. for (int i = startIndex; i < endIndex; ++i)
  8057. {
  8058. delete data.elements [i];
  8059. data.elements [i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8060. }
  8061. }
  8062. const int rangeSize = endIndex - startIndex;
  8063. ObjectClass** e = data.elements + startIndex;
  8064. int numToShift = numUsed - endIndex;
  8065. numUsed -= rangeSize;
  8066. while (--numToShift >= 0)
  8067. {
  8068. *e = e [rangeSize];
  8069. ++e;
  8070. }
  8071. if ((numUsed << 1) < data.numAllocated)
  8072. minimiseStorageOverheads();
  8073. }
  8074. }
  8075. /** Removes the last n objects from the array.
  8076. @param howManyToRemove how many objects to remove from the end of the array
  8077. @param deleteObjects whether to also delete the objects that are removed
  8078. @see remove, removeObject, removeRange
  8079. */
  8080. void removeLast (int howManyToRemove = 1,
  8081. const bool deleteObjects = true)
  8082. {
  8083. const ScopedLockType lock (getLock());
  8084. if (howManyToRemove >= numUsed)
  8085. clear (deleteObjects);
  8086. else
  8087. removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects);
  8088. }
  8089. /** Swaps a pair of objects in the array.
  8090. If either of the indexes passed in is out-of-range, nothing will happen,
  8091. otherwise the two objects at these positions will be exchanged.
  8092. */
  8093. void swap (const int index1,
  8094. const int index2) noexcept
  8095. {
  8096. const ScopedLockType lock (getLock());
  8097. if (isPositiveAndBelow (index1, numUsed)
  8098. && isPositiveAndBelow (index2, numUsed))
  8099. {
  8100. swapVariables (data.elements [index1],
  8101. data.elements [index2]);
  8102. }
  8103. }
  8104. /** Moves one of the objects to a different position.
  8105. This will move the object to a specified index, shuffling along
  8106. any intervening elements as required.
  8107. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8108. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8109. @param currentIndex the index of the object to be moved. If this isn't a
  8110. valid index, then nothing will be done
  8111. @param newIndex the index at which you'd like this object to end up. If this
  8112. is less than zero, it will be moved to the end of the array
  8113. */
  8114. void move (const int currentIndex,
  8115. int newIndex) noexcept
  8116. {
  8117. if (currentIndex != newIndex)
  8118. {
  8119. const ScopedLockType lock (getLock());
  8120. if (isPositiveAndBelow (currentIndex, numUsed))
  8121. {
  8122. if (! isPositiveAndBelow (newIndex, numUsed))
  8123. newIndex = numUsed - 1;
  8124. ObjectClass* const value = data.elements [currentIndex];
  8125. if (newIndex > currentIndex)
  8126. {
  8127. memmove (data.elements + currentIndex,
  8128. data.elements + currentIndex + 1,
  8129. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8130. }
  8131. else
  8132. {
  8133. memmove (data.elements + newIndex + 1,
  8134. data.elements + newIndex,
  8135. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8136. }
  8137. data.elements [newIndex] = value;
  8138. }
  8139. }
  8140. }
  8141. /** This swaps the contents of this array with those of another array.
  8142. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  8143. because it just swaps their internal pointers.
  8144. */
  8145. void swapWithArray (OwnedArray& otherArray) noexcept
  8146. {
  8147. const ScopedLockType lock1 (getLock());
  8148. const ScopedLockType lock2 (otherArray.getLock());
  8149. data.swapWith (otherArray.data);
  8150. swapVariables (numUsed, otherArray.numUsed);
  8151. }
  8152. /** Reduces the amount of storage being used by the array.
  8153. Arrays typically allocate slightly more storage than they need, and after
  8154. removing elements, they may have quite a lot of unused space allocated.
  8155. This method will reduce the amount of allocated storage to a minimum.
  8156. */
  8157. void minimiseStorageOverheads() noexcept
  8158. {
  8159. const ScopedLockType lock (getLock());
  8160. data.shrinkToNoMoreThan (numUsed);
  8161. }
  8162. /** Increases the array's internal storage to hold a minimum number of elements.
  8163. Calling this before adding a large known number of elements means that
  8164. the array won't have to keep dynamically resizing itself as the elements
  8165. are added, and it'll therefore be more efficient.
  8166. */
  8167. void ensureStorageAllocated (const int minNumElements) noexcept
  8168. {
  8169. const ScopedLockType lock (getLock());
  8170. data.ensureAllocatedSize (minNumElements);
  8171. }
  8172. /** Sorts the elements in the array.
  8173. This will use a comparator object to sort the elements into order. The object
  8174. passed must have a method of the form:
  8175. @code
  8176. int compareElements (ElementType first, ElementType second);
  8177. @endcode
  8178. ..and this method must return:
  8179. - a value of < 0 if the first comes before the second
  8180. - a value of 0 if the two objects are equivalent
  8181. - a value of > 0 if the second comes before the first
  8182. To improve performance, the compareElements() method can be declared as static or const.
  8183. @param comparator the comparator to use for comparing elements.
  8184. @param retainOrderOfEquivalentItems if this is true, then items
  8185. which the comparator says are equivalent will be
  8186. kept in the order in which they currently appear
  8187. in the array. This is slower to perform, but may
  8188. be important in some cases. If it's false, a faster
  8189. algorithm is used, but equivalent elements may be
  8190. rearranged.
  8191. @see sortArray, indexOfSorted
  8192. */
  8193. template <class ElementComparator>
  8194. void sort (ElementComparator& comparator,
  8195. const bool retainOrderOfEquivalentItems = false) const noexcept
  8196. {
  8197. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8198. // avoids getting warning messages about the parameter being unused
  8199. const ScopedLockType lock (getLock());
  8200. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  8201. }
  8202. /** Returns the CriticalSection that locks this array.
  8203. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8204. an object of ScopedLockType as an RAII lock for it.
  8205. */
  8206. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  8207. /** Returns the type of scoped lock to use for locking this array */
  8208. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8209. private:
  8210. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  8211. int numUsed;
  8212. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OwnedArray);
  8213. };
  8214. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  8215. /*** End of inlined file: juce_OwnedArray.h ***/
  8216. /*** Start of inlined file: juce_ScopedPointer.h ***/
  8217. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8218. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8219. /**
  8220. This class holds a pointer which is automatically deleted when this object goes
  8221. out of scope.
  8222. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  8223. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  8224. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  8225. created objects.
  8226. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  8227. to an object. If you use the assignment operator to assign a different object to a
  8228. ScopedPointer, the old one will be automatically deleted.
  8229. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  8230. object to which it points during its lifetime. This means that making a copy of a const
  8231. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  8232. old one.
  8233. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  8234. can use the release() method.
  8235. */
  8236. template <class ObjectType>
  8237. class ScopedPointer
  8238. {
  8239. public:
  8240. /** Creates a ScopedPointer containing a null pointer. */
  8241. inline ScopedPointer() noexcept : object (nullptr)
  8242. {
  8243. }
  8244. /** Creates a ScopedPointer that owns the specified object. */
  8245. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) noexcept
  8246. : object (objectToTakePossessionOf)
  8247. {
  8248. }
  8249. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  8250. Because a pointer can only belong to one ScopedPointer, this transfers
  8251. the pointer from the other object to this one, and the other object is reset to
  8252. be a null pointer.
  8253. */
  8254. ScopedPointer (ScopedPointer& objectToTransferFrom) noexcept
  8255. : object (objectToTransferFrom.object)
  8256. {
  8257. objectToTransferFrom.object = nullptr;
  8258. }
  8259. /** Destructor.
  8260. This will delete the object that this ScopedPointer currently refers to.
  8261. */
  8262. inline ~ScopedPointer() { delete object; }
  8263. /** Changes this ScopedPointer to point to a new object.
  8264. Because a pointer can only belong to one ScopedPointer, this transfers
  8265. the pointer from the other object to this one, and the other object is reset to
  8266. be a null pointer.
  8267. If this ScopedPointer already points to an object, that object
  8268. will first be deleted.
  8269. */
  8270. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  8271. {
  8272. if (this != objectToTransferFrom.getAddress())
  8273. {
  8274. // Two ScopedPointers should never be able to refer to the same object - if
  8275. // this happens, you must have done something dodgy!
  8276. jassert (object == nullptr || object != objectToTransferFrom.object);
  8277. ObjectType* const oldObject = object;
  8278. object = objectToTransferFrom.object;
  8279. objectToTransferFrom.object = nullptr;
  8280. delete oldObject;
  8281. }
  8282. return *this;
  8283. }
  8284. /** Changes this ScopedPointer to point to a new object.
  8285. If this ScopedPointer already points to an object, that object
  8286. will first be deleted.
  8287. The pointer that you pass is may be null.
  8288. */
  8289. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  8290. {
  8291. if (object != newObjectToTakePossessionOf)
  8292. {
  8293. ObjectType* const oldObject = object;
  8294. object = newObjectToTakePossessionOf;
  8295. delete oldObject;
  8296. }
  8297. return *this;
  8298. }
  8299. /** Returns the object that this ScopedPointer refers to. */
  8300. inline operator ObjectType*() const noexcept { return object; }
  8301. /** Returns the object that this ScopedPointer refers to. */
  8302. inline ObjectType& operator*() const noexcept { return *object; }
  8303. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  8304. inline ObjectType* operator->() const noexcept { return object; }
  8305. /** Removes the current object from this ScopedPointer without deleting it.
  8306. This will return the current object, and set the ScopedPointer to a null pointer.
  8307. */
  8308. ObjectType* release() noexcept { ObjectType* const o = object; object = nullptr; return o; }
  8309. /** Swaps this object with that of another ScopedPointer.
  8310. The two objects simply exchange their pointers.
  8311. */
  8312. void swapWith (ScopedPointer <ObjectType>& other) noexcept
  8313. {
  8314. // Two ScopedPointers should never be able to refer to the same object - if
  8315. // this happens, you must have done something dodgy!
  8316. jassert (object != other.object);
  8317. std::swap (object, other.object);
  8318. }
  8319. private:
  8320. ObjectType* object;
  8321. // (Required as an alternative to the overloaded & operator).
  8322. const ScopedPointer* getAddress() const noexcept { return this; }
  8323. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  8324. /* This is private to stop people accidentally copying a const ScopedPointer (the compiler
  8325. would let you do so by implicitly casting the source to its raw object pointer).
  8326. A side effect of this is that you may hit a puzzling compiler error when you write something
  8327. like this:
  8328. ScopedPointer<MyClass> m = new MyClass(); // Compile error: copy constructor is private.
  8329. Even though the compiler would normally ignore the assignment here, it can't do so when the
  8330. copy constructor is private. It's very easy to fis though - just write it like this:
  8331. ScopedPointer<MyClass> m (new MyClass()); // Compiles OK
  8332. It's good practice to always use the latter form when writing your object declarations anyway,
  8333. rather than writing them as assignments and assuming (or hoping) that the compiler will be
  8334. smart enough to replace your construction + assignment with a single constructor.
  8335. */
  8336. ScopedPointer (const ScopedPointer&);
  8337. #endif
  8338. };
  8339. /** Compares a ScopedPointer with another pointer.
  8340. This can be handy for checking whether this is a null pointer.
  8341. */
  8342. template <class ObjectType>
  8343. bool operator== (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  8344. {
  8345. return static_cast <ObjectType*> (pointer1) == pointer2;
  8346. }
  8347. /** Compares a ScopedPointer with another pointer.
  8348. This can be handy for checking whether this is a null pointer.
  8349. */
  8350. template <class ObjectType>
  8351. bool operator!= (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  8352. {
  8353. return static_cast <ObjectType*> (pointer1) != pointer2;
  8354. }
  8355. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8356. /*** End of inlined file: juce_ScopedPointer.h ***/
  8357. /**
  8358. A simple class to generate hash functions for some primitive types, intended for
  8359. use with the HashMap class.
  8360. @see HashMap
  8361. */
  8362. class DefaultHashFunctions
  8363. {
  8364. public:
  8365. /** Generates a simple hash from an integer. */
  8366. static int generateHash (const int key, const int upperLimit) noexcept { return std::abs (key) % upperLimit; }
  8367. /** Generates a simple hash from a string. */
  8368. static int generateHash (const String& key, const int upperLimit) noexcept { return (int) (((uint32) key.hashCode()) % upperLimit); }
  8369. /** Generates a simple hash from a variant. */
  8370. static int generateHash (const var& key, const int upperLimit) noexcept { return generateHash (key.toString(), upperLimit); }
  8371. };
  8372. /**
  8373. Holds a set of mappings between some key/value pairs.
  8374. The types of the key and value objects are set as template parameters.
  8375. You can also specify a class to supply a hash function that converts a key value
  8376. into an hashed integer. This class must have the form:
  8377. @code
  8378. struct MyHashGenerator
  8379. {
  8380. static int generateHash (MyKeyType key, int upperLimit)
  8381. {
  8382. // The function must return a value 0 <= x < upperLimit
  8383. return someFunctionOfMyKeyType (key) % upperLimit;
  8384. }
  8385. };
  8386. @endcode
  8387. Like the Array class, the key and value types are expected to be copy-by-value types, so
  8388. if you define them to be pointer types, this class won't delete the objects that they
  8389. point to.
  8390. If you don't supply a class for the HashFunctionToUse template parameter, the
  8391. default one provides some simple mappings for strings and ints.
  8392. @code
  8393. HashMap<int, String> hash;
  8394. hash.set (1, "item1");
  8395. hash.set (2, "item2");
  8396. DBG (hash [1]); // prints "item1"
  8397. DBG (hash [2]); // prints "item2"
  8398. // This iterates the map, printing all of its key -> value pairs..
  8399. for (HashMap<int, String>::Iterator i (hash); i.next();)
  8400. DBG (i.getKey() << " -> " << i.getValue());
  8401. @endcode
  8402. @see CriticalSection, DefaultHashFunctions, NamedValueSet, SortedSet
  8403. */
  8404. template <typename KeyType,
  8405. typename ValueType,
  8406. class HashFunctionToUse = DefaultHashFunctions,
  8407. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8408. class HashMap
  8409. {
  8410. private:
  8411. typedef PARAMETER_TYPE (KeyType) KeyTypeParameter;
  8412. typedef PARAMETER_TYPE (ValueType) ValueTypeParameter;
  8413. public:
  8414. /** Creates an empty hash-map.
  8415. The numberOfSlots parameter specifies the number of hash entries the map will use. This
  8416. will be the "upperLimit" parameter that is passed to your generateHash() function. The number
  8417. of hash slots will grow automatically if necessary, or it can be remapped manually using remapTable().
  8418. */
  8419. explicit HashMap (const int numberOfSlots = defaultHashTableSize)
  8420. : totalNumItems (0)
  8421. {
  8422. slots.insertMultiple (0, nullptr, numberOfSlots);
  8423. }
  8424. /** Destructor. */
  8425. ~HashMap()
  8426. {
  8427. clear();
  8428. }
  8429. /** Removes all values from the map.
  8430. Note that this will clear the content, but won't affect the number of slots (see
  8431. remapTable and getNumSlots).
  8432. */
  8433. void clear()
  8434. {
  8435. const ScopedLockType sl (getLock());
  8436. for (int i = slots.size(); --i >= 0;)
  8437. {
  8438. HashEntry* h = slots.getUnchecked(i);
  8439. while (h != nullptr)
  8440. {
  8441. const ScopedPointer<HashEntry> deleter (h);
  8442. h = h->nextEntry;
  8443. }
  8444. slots.set (i, nullptr);
  8445. }
  8446. totalNumItems = 0;
  8447. }
  8448. /** Returns the current number of items in the map. */
  8449. inline int size() const noexcept
  8450. {
  8451. return totalNumItems;
  8452. }
  8453. /** Returns the value corresponding to a given key.
  8454. If the map doesn't contain the key, a default instance of the value type is returned.
  8455. @param keyToLookFor the key of the item being requested
  8456. */
  8457. inline const ValueType operator[] (KeyTypeParameter keyToLookFor) const
  8458. {
  8459. const ScopedLockType sl (getLock());
  8460. for (const HashEntry* entry = slots.getUnchecked (generateHashFor (keyToLookFor)); entry != nullptr; entry = entry->nextEntry)
  8461. if (entry->key == keyToLookFor)
  8462. return entry->value;
  8463. return ValueType();
  8464. }
  8465. /** Returns true if the map contains an item with the specied key. */
  8466. bool contains (KeyTypeParameter keyToLookFor) const
  8467. {
  8468. const ScopedLockType sl (getLock());
  8469. for (const HashEntry* entry = slots.getUnchecked (generateHashFor (keyToLookFor)); entry != nullptr; entry = entry->nextEntry)
  8470. if (entry->key == keyToLookFor)
  8471. return true;
  8472. return false;
  8473. }
  8474. /** Returns true if the hash contains at least one occurrence of a given value. */
  8475. bool containsValue (ValueTypeParameter valueToLookFor) const
  8476. {
  8477. const ScopedLockType sl (getLock());
  8478. for (int i = getNumSlots(); --i >= 0;)
  8479. for (const HashEntry* entry = slots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  8480. if (entry->value == valueToLookFor)
  8481. return true;
  8482. return false;
  8483. }
  8484. /** Adds or replaces an element in the hash-map.
  8485. If there's already an item with the given key, this will replace its value. Otherwise, a new item
  8486. will be added to the map.
  8487. */
  8488. void set (KeyTypeParameter newKey, ValueTypeParameter newValue)
  8489. {
  8490. const ScopedLockType sl (getLock());
  8491. const int hashIndex = generateHashFor (newKey);
  8492. HashEntry* const firstEntry = slots.getUnchecked (hashIndex);
  8493. for (HashEntry* entry = firstEntry; entry != nullptr; entry = entry->nextEntry)
  8494. {
  8495. if (entry->key == newKey)
  8496. {
  8497. entry->value = newValue;
  8498. return;
  8499. }
  8500. }
  8501. slots.set (hashIndex, new HashEntry (newKey, newValue, firstEntry));
  8502. ++totalNumItems;
  8503. if (totalNumItems > (getNumSlots() * 3) / 2)
  8504. remapTable (getNumSlots() * 2);
  8505. }
  8506. /** Removes an item with the given key. */
  8507. void remove (KeyTypeParameter keyToRemove)
  8508. {
  8509. const ScopedLockType sl (getLock());
  8510. const int hashIndex = generateHashFor (keyToRemove);
  8511. HashEntry* entry = slots.getUnchecked (hashIndex);
  8512. HashEntry* previous = nullptr;
  8513. while (entry != nullptr)
  8514. {
  8515. if (entry->key == keyToRemove)
  8516. {
  8517. const ScopedPointer<HashEntry> deleter (entry);
  8518. entry = entry->nextEntry;
  8519. if (previous != nullptr)
  8520. previous->nextEntry = entry;
  8521. else
  8522. slots.set (hashIndex, entry);
  8523. --totalNumItems;
  8524. }
  8525. else
  8526. {
  8527. previous = entry;
  8528. entry = entry->nextEntry;
  8529. }
  8530. }
  8531. }
  8532. /** Removes all items with the given value. */
  8533. void removeValue (ValueTypeParameter valueToRemove)
  8534. {
  8535. const ScopedLockType sl (getLock());
  8536. for (int i = getNumSlots(); --i >= 0;)
  8537. {
  8538. HashEntry* entry = slots.getUnchecked(i);
  8539. HashEntry* previous = nullptr;
  8540. while (entry != nullptr)
  8541. {
  8542. if (entry->value == valueToRemove)
  8543. {
  8544. const ScopedPointer<HashEntry> deleter (entry);
  8545. entry = entry->nextEntry;
  8546. if (previous != nullptr)
  8547. previous->nextEntry = entry;
  8548. else
  8549. slots.set (i, entry);
  8550. --totalNumItems;
  8551. }
  8552. else
  8553. {
  8554. previous = entry;
  8555. entry = entry->nextEntry;
  8556. }
  8557. }
  8558. }
  8559. }
  8560. /** Remaps the hash-map to use a different number of slots for its hash function.
  8561. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  8562. @see getNumSlots()
  8563. */
  8564. void remapTable (int newNumberOfSlots)
  8565. {
  8566. HashMap newTable (newNumberOfSlots);
  8567. for (int i = getNumSlots(); --i >= 0;)
  8568. for (const HashEntry* entry = slots.getUnchecked(i); entry != nullptr; entry = entry->nextEntry)
  8569. newTable.set (entry->key, entry->value);
  8570. swapWith (newTable);
  8571. }
  8572. /** Returns the number of slots which are available for hashing.
  8573. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  8574. @see getNumSlots()
  8575. */
  8576. inline int getNumSlots() const noexcept
  8577. {
  8578. return slots.size();
  8579. }
  8580. /** Efficiently swaps the contents of two hash-maps. */
  8581. void swapWith (HashMap& otherHashMap) noexcept
  8582. {
  8583. const ScopedLockType lock1 (getLock());
  8584. const ScopedLockType lock2 (otherHashMap.getLock());
  8585. slots.swapWithArray (otherHashMap.slots);
  8586. std::swap (totalNumItems, otherHashMap.totalNumItems);
  8587. }
  8588. /** Returns the CriticalSection that locks this structure.
  8589. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8590. an object of ScopedLockType as an RAII lock for it.
  8591. */
  8592. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return lock; }
  8593. /** Returns the type of scoped lock to use for locking this array */
  8594. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8595. private:
  8596. class HashEntry
  8597. {
  8598. public:
  8599. HashEntry (KeyTypeParameter key_, ValueTypeParameter value_, HashEntry* const nextEntry_)
  8600. : key (key_), value (value_), nextEntry (nextEntry_)
  8601. {}
  8602. const KeyType key;
  8603. ValueType value;
  8604. HashEntry* nextEntry;
  8605. JUCE_DECLARE_NON_COPYABLE (HashEntry);
  8606. };
  8607. public:
  8608. /** Iterates over the items in a HashMap.
  8609. To use it, repeatedly call next() until it returns false, e.g.
  8610. @code
  8611. HashMap <String, String> myMap;
  8612. HashMap<String, String>::Iterator i (myMap);
  8613. while (i.next())
  8614. {
  8615. DBG (i.getKey() << " -> " << i.getValue());
  8616. }
  8617. @endcode
  8618. The order in which items are iterated bears no resemblence to the order in which
  8619. they were originally added!
  8620. Obviously as soon as you call any non-const methods on the original hash-map, any
  8621. iterators that were created beforehand will cease to be valid, and should not be used.
  8622. @see HashMap
  8623. */
  8624. class Iterator
  8625. {
  8626. public:
  8627. Iterator (const HashMap& hashMapToIterate)
  8628. : hashMap (hashMapToIterate), entry (0), index (0)
  8629. {}
  8630. /** Moves to the next item, if one is available.
  8631. When this returns true, you can get the item's key and value using getKey() and
  8632. getValue(). If it returns false, the iteration has finished and you should stop.
  8633. */
  8634. bool next()
  8635. {
  8636. if (entry != nullptr)
  8637. entry = entry->nextEntry;
  8638. while (entry == nullptr)
  8639. {
  8640. if (index >= hashMap.getNumSlots())
  8641. return false;
  8642. entry = hashMap.slots.getUnchecked (index++);
  8643. }
  8644. return true;
  8645. }
  8646. /** Returns the current item's key.
  8647. This should only be called when a call to next() has just returned true.
  8648. */
  8649. const KeyType getKey() const
  8650. {
  8651. return entry != nullptr ? entry->key : KeyType();
  8652. }
  8653. /** Returns the current item's value.
  8654. This should only be called when a call to next() has just returned true.
  8655. */
  8656. const ValueType getValue() const
  8657. {
  8658. return entry != nullptr ? entry->value : ValueType();
  8659. }
  8660. private:
  8661. const HashMap& hashMap;
  8662. HashEntry* entry;
  8663. int index;
  8664. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Iterator);
  8665. };
  8666. private:
  8667. enum { defaultHashTableSize = 101 };
  8668. friend class Iterator;
  8669. Array <HashEntry*> slots;
  8670. int totalNumItems;
  8671. TypeOfCriticalSectionToUse lock;
  8672. int generateHashFor (KeyTypeParameter key) const
  8673. {
  8674. const int hash = HashFunctionToUse::generateHash (key, getNumSlots());
  8675. jassert (isPositiveAndBelow (hash, getNumSlots())); // your hash function is generating out-of-range numbers!
  8676. return hash;
  8677. }
  8678. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HashMap);
  8679. };
  8680. #endif // __JUCE_HASHMAP_JUCEHEADER__
  8681. /*** End of inlined file: juce_HashMap.h ***/
  8682. #endif
  8683. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  8684. #endif
  8685. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  8686. #endif
  8687. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  8688. #endif
  8689. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8690. /*** Start of inlined file: juce_PropertySet.h ***/
  8691. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8692. #define __JUCE_PROPERTYSET_JUCEHEADER__
  8693. /*** Start of inlined file: juce_StringPairArray.h ***/
  8694. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8695. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8696. /*** Start of inlined file: juce_StringArray.h ***/
  8697. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  8698. #define __JUCE_STRINGARRAY_JUCEHEADER__
  8699. /**
  8700. A special array for holding a list of strings.
  8701. @see String, StringPairArray
  8702. */
  8703. class JUCE_API StringArray
  8704. {
  8705. public:
  8706. /** Creates an empty string array */
  8707. StringArray() noexcept;
  8708. /** Creates a copy of another string array */
  8709. StringArray (const StringArray& other);
  8710. /** Creates an array containing a single string. */
  8711. explicit StringArray (const String& firstValue);
  8712. /** Creates a copy of an array of string literals.
  8713. @param strings an array of strings to add. Null pointers in the array will be
  8714. treated as empty strings
  8715. @param numberOfStrings how many items there are in the array
  8716. */
  8717. StringArray (const char* const* strings, int numberOfStrings);
  8718. /** Creates a copy of a null-terminated array of string literals.
  8719. Each item from the array passed-in is added, until it encounters a null pointer,
  8720. at which point it stops.
  8721. */
  8722. explicit StringArray (const char* const* strings);
  8723. /** Creates a copy of a null-terminated array of string literals.
  8724. Each item from the array passed-in is added, until it encounters a null pointer,
  8725. at which point it stops.
  8726. */
  8727. explicit StringArray (const wchar_t* const* strings);
  8728. /** Creates a copy of an array of string literals.
  8729. @param strings an array of strings to add. Null pointers in the array will be
  8730. treated as empty strings
  8731. @param numberOfStrings how many items there are in the array
  8732. */
  8733. StringArray (const wchar_t* const* strings, int numberOfStrings);
  8734. /** Destructor. */
  8735. ~StringArray();
  8736. /** Copies the contents of another string array into this one */
  8737. StringArray& operator= (const StringArray& other);
  8738. /** Compares two arrays.
  8739. Comparisons are case-sensitive.
  8740. @returns true only if the other array contains exactly the same strings in the same order
  8741. */
  8742. bool operator== (const StringArray& other) const noexcept;
  8743. /** Compares two arrays.
  8744. Comparisons are case-sensitive.
  8745. @returns false if the other array contains exactly the same strings in the same order
  8746. */
  8747. bool operator!= (const StringArray& other) const noexcept;
  8748. /** Returns the number of strings in the array */
  8749. inline int size() const noexcept { return strings.size(); };
  8750. /** Returns one of the strings from the array.
  8751. If the index is out-of-range, an empty string is returned.
  8752. Obviously the reference returned shouldn't be stored for later use, as the
  8753. string it refers to may disappear when the array changes.
  8754. */
  8755. const String& operator[] (int index) const noexcept;
  8756. /** Returns a reference to one of the strings in the array.
  8757. This lets you modify a string in-place in the array, but you must be sure that
  8758. the index is in-range.
  8759. */
  8760. String& getReference (int index) noexcept;
  8761. /** Searches for a string in the array.
  8762. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8763. @returns true if the string is found inside the array
  8764. */
  8765. bool contains (const String& stringToLookFor,
  8766. bool ignoreCase = false) const;
  8767. /** Searches for a string in the array.
  8768. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8769. @param stringToLookFor the string to try to find
  8770. @param ignoreCase whether the comparison should be case-insensitive
  8771. @param startIndex the first index to start searching from
  8772. @returns the index of the first occurrence of the string in this array,
  8773. or -1 if it isn't found.
  8774. */
  8775. int indexOf (const String& stringToLookFor,
  8776. bool ignoreCase = false,
  8777. int startIndex = 0) const;
  8778. /** Appends a string at the end of the array. */
  8779. void add (const String& stringToAdd);
  8780. /** Inserts a string into the array.
  8781. This will insert a string into the array at the given index, moving
  8782. up the other elements to make room for it.
  8783. If the index is less than zero or greater than the size of the array,
  8784. the new string will be added to the end of the array.
  8785. */
  8786. void insert (int index, const String& stringToAdd);
  8787. /** Adds a string to the array as long as it's not already in there.
  8788. The search can optionally be case-insensitive.
  8789. */
  8790. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  8791. /** Replaces one of the strings in the array with another one.
  8792. If the index is higher than the array's size, the new string will be
  8793. added to the end of the array; if it's less than zero nothing happens.
  8794. */
  8795. void set (int index, const String& newString);
  8796. /** Appends some strings from another array to the end of this one.
  8797. @param other the array to add
  8798. @param startIndex the first element of the other array to add
  8799. @param numElementsToAdd the maximum number of elements to add (if this is
  8800. less than zero, they are all added)
  8801. */
  8802. void addArray (const StringArray& other,
  8803. int startIndex = 0,
  8804. int numElementsToAdd = -1);
  8805. /** Breaks up a string into tokens and adds them to this array.
  8806. This will tokenise the given string using whitespace characters as the
  8807. token delimiters, and will add these tokens to the end of the array.
  8808. @returns the number of tokens added
  8809. */
  8810. int addTokens (const String& stringToTokenise,
  8811. bool preserveQuotedStrings);
  8812. /** Breaks up a string into tokens and adds them to this array.
  8813. This will tokenise the given string (using the string passed in to define the
  8814. token delimiters), and will add these tokens to the end of the array.
  8815. @param stringToTokenise the string to tokenise
  8816. @param breakCharacters a string of characters, any of which will be considered
  8817. to be a token delimiter.
  8818. @param quoteCharacters if this string isn't empty, it defines a set of characters
  8819. which are treated as quotes. Any text occurring
  8820. between quotes is not broken up into tokens.
  8821. @returns the number of tokens added
  8822. */
  8823. int addTokens (const String& stringToTokenise,
  8824. const String& breakCharacters,
  8825. const String& quoteCharacters);
  8826. /** Breaks up a string into lines and adds them to this array.
  8827. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  8828. to the array. Line-break characters are omitted from the strings that are added to
  8829. the array.
  8830. */
  8831. int addLines (const String& stringToBreakUp);
  8832. /** Removes all elements from the array. */
  8833. void clear();
  8834. /** Removes a string from the array.
  8835. If the index is out-of-range, no action will be taken.
  8836. */
  8837. void remove (int index);
  8838. /** Finds a string in the array and removes it.
  8839. This will remove the first occurrence of the given string from the array. The
  8840. comparison may be case-insensitive depending on the ignoreCase parameter.
  8841. */
  8842. void removeString (const String& stringToRemove,
  8843. bool ignoreCase = false);
  8844. /** Removes a range of elements from the array.
  8845. This will remove a set of elements, starting from the given index,
  8846. and move subsequent elements down to close the gap.
  8847. If the range extends beyond the bounds of the array, it will
  8848. be safely clipped to the size of the array.
  8849. @param startIndex the index of the first element to remove
  8850. @param numberToRemove how many elements should be removed
  8851. */
  8852. void removeRange (int startIndex, int numberToRemove);
  8853. /** Removes any duplicated elements from the array.
  8854. If any string appears in the array more than once, only the first occurrence of
  8855. it will be retained.
  8856. @param ignoreCase whether to use a case-insensitive comparison
  8857. */
  8858. void removeDuplicates (bool ignoreCase);
  8859. /** Removes empty strings from the array.
  8860. @param removeWhitespaceStrings if true, strings that only contain whitespace
  8861. characters will also be removed
  8862. */
  8863. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  8864. /** Moves one of the strings to a different position.
  8865. This will move the string to a specified index, shuffling along
  8866. any intervening elements as required.
  8867. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8868. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8869. @param currentIndex the index of the value to be moved. If this isn't a
  8870. valid index, then nothing will be done
  8871. @param newIndex the index at which you'd like this value to end up. If this
  8872. is less than zero, the value will be moved to the end
  8873. of the array
  8874. */
  8875. void move (int currentIndex, int newIndex) noexcept;
  8876. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  8877. void trim();
  8878. /** Adds numbers to the strings in the array, to make each string unique.
  8879. This will add numbers to the ends of groups of similar strings.
  8880. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  8881. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  8882. @param appendNumberToFirstInstance whether the first of a group of similar strings
  8883. also has a number appended to it.
  8884. @param preNumberString when adding a number, this string is added before the number.
  8885. If you pass 0, a default string will be used, which adds
  8886. brackets around the number.
  8887. @param postNumberString this string is appended after any numbers that are added.
  8888. If you pass 0, a default string will be used, which adds
  8889. brackets around the number.
  8890. */
  8891. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  8892. bool appendNumberToFirstInstance,
  8893. CharPointer_UTF8 preNumberString = CharPointer_UTF8 (nullptr),
  8894. CharPointer_UTF8 postNumberString = CharPointer_UTF8 (nullptr));
  8895. /** Joins the strings in the array together into one string.
  8896. This will join a range of elements from the array into a string, separating
  8897. them with a given string.
  8898. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  8899. @param separatorString the string to insert between all the strings
  8900. @param startIndex the first element to join
  8901. @param numberOfElements how many elements to join together. If this is less
  8902. than zero, all available elements will be used.
  8903. */
  8904. String joinIntoString (const String& separatorString,
  8905. int startIndex = 0,
  8906. int numberOfElements = -1) const;
  8907. /** Sorts the array into alphabetical order.
  8908. @param ignoreCase if true, the comparisons used will be case-sensitive.
  8909. */
  8910. void sort (bool ignoreCase);
  8911. /** Reduces the amount of storage being used by the array.
  8912. Arrays typically allocate slightly more storage than they need, and after
  8913. removing elements, they may have quite a lot of unused space allocated.
  8914. This method will reduce the amount of allocated storage to a minimum.
  8915. */
  8916. void minimiseStorageOverheads();
  8917. private:
  8918. Array <String> strings;
  8919. JUCE_LEAK_DETECTOR (StringArray);
  8920. };
  8921. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  8922. /*** End of inlined file: juce_StringArray.h ***/
  8923. /**
  8924. A container for holding a set of strings which are keyed by another string.
  8925. @see StringArray
  8926. */
  8927. class JUCE_API StringPairArray
  8928. {
  8929. public:
  8930. /** Creates an empty array */
  8931. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  8932. /** Creates a copy of another array */
  8933. StringPairArray (const StringPairArray& other);
  8934. /** Destructor. */
  8935. ~StringPairArray();
  8936. /** Copies the contents of another string array into this one */
  8937. StringPairArray& operator= (const StringPairArray& other);
  8938. /** Compares two arrays.
  8939. Comparisons are case-sensitive.
  8940. @returns true only if the other array contains exactly the same strings with the same keys
  8941. */
  8942. bool operator== (const StringPairArray& other) const;
  8943. /** Compares two arrays.
  8944. Comparisons are case-sensitive.
  8945. @returns false if the other array contains exactly the same strings with the same keys
  8946. */
  8947. bool operator!= (const StringPairArray& other) const;
  8948. /** Finds the value corresponding to a key string.
  8949. If no such key is found, this will just return an empty string. To check whether
  8950. a given key actually exists (because it might actually be paired with an empty string), use
  8951. the getAllKeys() method to obtain a list.
  8952. Obviously the reference returned shouldn't be stored for later use, as the
  8953. string it refers to may disappear when the array changes.
  8954. @see getValue
  8955. */
  8956. const String& operator[] (const String& key) const;
  8957. /** Finds the value corresponding to a key string.
  8958. If no such key is found, this will just return the value provided as a default.
  8959. @see operator[]
  8960. */
  8961. String getValue (const String& key, const String& defaultReturnValue) const;
  8962. /** Returns a list of all keys in the array. */
  8963. const StringArray& getAllKeys() const noexcept { return keys; }
  8964. /** Returns a list of all values in the array. */
  8965. const StringArray& getAllValues() const noexcept { return values; }
  8966. /** Returns the number of strings in the array */
  8967. inline int size() const noexcept { return keys.size(); };
  8968. /** Adds or amends a key/value pair.
  8969. If a value already exists with this key, its value will be overwritten,
  8970. otherwise the key/value pair will be added to the array.
  8971. */
  8972. void set (const String& key, const String& value);
  8973. /** Adds the items from another array to this one.
  8974. This is equivalent to using set() to add each of the pairs from the other array.
  8975. */
  8976. void addArray (const StringPairArray& other);
  8977. /** Removes all elements from the array. */
  8978. void clear();
  8979. /** Removes a string from the array based on its key.
  8980. If the key isn't found, nothing will happen.
  8981. */
  8982. void remove (const String& key);
  8983. /** Removes a string from the array based on its index.
  8984. If the index is out-of-range, no action will be taken.
  8985. */
  8986. void remove (int index);
  8987. /** Indicates whether to use a case-insensitive search when looking up a key string.
  8988. */
  8989. void setIgnoresCase (bool shouldIgnoreCase);
  8990. /** Returns a descriptive string containing the items.
  8991. This is handy for dumping the contents of an array.
  8992. */
  8993. String getDescription() const;
  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. StringArray keys, values;
  9002. bool ignoreCase;
  9003. JUCE_LEAK_DETECTOR (StringPairArray);
  9004. };
  9005. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  9006. /*** End of inlined file: juce_StringPairArray.h ***/
  9007. /*** Start of inlined file: juce_XmlElement.h ***/
  9008. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  9009. #define __JUCE_XMLELEMENT_JUCEHEADER__
  9010. /*** Start of inlined file: juce_File.h ***/
  9011. #ifndef __JUCE_FILE_JUCEHEADER__
  9012. #define __JUCE_FILE_JUCEHEADER__
  9013. /*** Start of inlined file: juce_Time.h ***/
  9014. #ifndef __JUCE_TIME_JUCEHEADER__
  9015. #define __JUCE_TIME_JUCEHEADER__
  9016. /*** Start of inlined file: juce_RelativeTime.h ***/
  9017. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  9018. #define __JUCE_RELATIVETIME_JUCEHEADER__
  9019. /** A relative measure of time.
  9020. The time is stored as a number of seconds, at double-precision floating
  9021. point accuracy, and may be positive or negative.
  9022. If you need an absolute time, (i.e. a date + time), see the Time class.
  9023. */
  9024. class JUCE_API RelativeTime
  9025. {
  9026. public:
  9027. /** Creates a RelativeTime.
  9028. @param seconds the number of seconds, which may be +ve or -ve.
  9029. @see milliseconds, minutes, hours, days, weeks
  9030. */
  9031. explicit RelativeTime (double seconds = 0.0) noexcept;
  9032. /** Copies another relative time. */
  9033. RelativeTime (const RelativeTime& other) noexcept;
  9034. /** Copies another relative time. */
  9035. RelativeTime& operator= (const RelativeTime& other) noexcept;
  9036. /** Destructor. */
  9037. ~RelativeTime() noexcept;
  9038. /** Creates a new RelativeTime object representing a number of milliseconds.
  9039. @see minutes, hours, days, weeks
  9040. */
  9041. static const RelativeTime milliseconds (int milliseconds) noexcept;
  9042. /** Creates a new RelativeTime object representing a number of milliseconds.
  9043. @see minutes, hours, days, weeks
  9044. */
  9045. static const RelativeTime milliseconds (int64 milliseconds) noexcept;
  9046. /** Creates a new RelativeTime object representing a number of minutes.
  9047. @see milliseconds, hours, days, weeks
  9048. */
  9049. static const RelativeTime minutes (double numberOfMinutes) noexcept;
  9050. /** Creates a new RelativeTime object representing a number of hours.
  9051. @see milliseconds, minutes, days, weeks
  9052. */
  9053. static const RelativeTime hours (double numberOfHours) noexcept;
  9054. /** Creates a new RelativeTime object representing a number of days.
  9055. @see milliseconds, minutes, hours, weeks
  9056. */
  9057. static const RelativeTime days (double numberOfDays) noexcept;
  9058. /** Creates a new RelativeTime object representing a number of weeks.
  9059. @see milliseconds, minutes, hours, days
  9060. */
  9061. static const RelativeTime weeks (double numberOfWeeks) noexcept;
  9062. /** Returns the number of milliseconds this time represents.
  9063. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  9064. */
  9065. int64 inMilliseconds() const noexcept;
  9066. /** Returns the number of seconds this time represents.
  9067. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  9068. */
  9069. double inSeconds() const noexcept { return seconds; }
  9070. /** Returns the number of minutes this time represents.
  9071. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  9072. */
  9073. double inMinutes() const noexcept;
  9074. /** Returns the number of hours this time represents.
  9075. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  9076. */
  9077. double inHours() const noexcept;
  9078. /** Returns the number of days this time represents.
  9079. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  9080. */
  9081. double inDays() const noexcept;
  9082. /** Returns the number of weeks this time represents.
  9083. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  9084. */
  9085. double inWeeks() const noexcept;
  9086. /** Returns a readable textual description of the time.
  9087. The exact format of the string returned will depend on
  9088. the magnitude of the time - e.g.
  9089. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  9090. so that only the two most significant units are printed.
  9091. The returnValueForZeroTime value is the result that is returned if the
  9092. length is zero. Depending on your application you might want to use this
  9093. to return something more relevant like "empty" or "0 secs", etc.
  9094. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  9095. */
  9096. String getDescription (const String& returnValueForZeroTime = "0") const;
  9097. /** Adds another RelativeTime to this one. */
  9098. const RelativeTime& operator+= (const RelativeTime& timeToAdd) noexcept;
  9099. /** Subtracts another RelativeTime from this one. */
  9100. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) noexcept;
  9101. /** Adds a number of seconds to this time. */
  9102. const RelativeTime& operator+= (double secondsToAdd) noexcept;
  9103. /** Subtracts a number of seconds from this time. */
  9104. const RelativeTime& operator-= (double secondsToSubtract) noexcept;
  9105. private:
  9106. double seconds;
  9107. };
  9108. /** Compares two RelativeTimes. */
  9109. bool operator== (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9110. /** Compares two RelativeTimes. */
  9111. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9112. /** Compares two RelativeTimes. */
  9113. bool operator> (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9114. /** Compares two RelativeTimes. */
  9115. bool operator< (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9116. /** Compares two RelativeTimes. */
  9117. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9118. /** Compares two RelativeTimes. */
  9119. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9120. /** Adds two RelativeTimes together. */
  9121. RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9122. /** Subtracts two RelativeTimes. */
  9123. RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) noexcept;
  9124. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  9125. /*** End of inlined file: juce_RelativeTime.h ***/
  9126. /**
  9127. Holds an absolute date and time.
  9128. Internally, the time is stored at millisecond precision.
  9129. @see RelativeTime
  9130. */
  9131. class JUCE_API Time
  9132. {
  9133. public:
  9134. /** Creates a Time object.
  9135. This default constructor creates a time of 1st January 1970, (which is
  9136. represented internally as 0ms).
  9137. To create a time object representing the current time, use getCurrentTime().
  9138. @see getCurrentTime
  9139. */
  9140. Time() noexcept;
  9141. /** Creates a time based on a number of milliseconds.
  9142. The internal millisecond count is set to 0 (1st January 1970). To create a
  9143. time object set to the current time, use getCurrentTime().
  9144. @param millisecondsSinceEpoch the number of milliseconds since the unix
  9145. 'epoch' (midnight Jan 1st 1970).
  9146. @see getCurrentTime, currentTimeMillis
  9147. */
  9148. explicit Time (int64 millisecondsSinceEpoch) noexcept;
  9149. /** Creates a time from a set of date components.
  9150. The timezone is assumed to be whatever the system is using as its locale.
  9151. @param year the year, in 4-digit format, e.g. 2004
  9152. @param month the month, in the range 0 to 11
  9153. @param day the day of the month, in the range 1 to 31
  9154. @param hours hours in 24-hour clock format, 0 to 23
  9155. @param minutes minutes 0 to 59
  9156. @param seconds seconds 0 to 59
  9157. @param milliseconds milliseconds 0 to 999
  9158. @param useLocalTime if true, encode using the current machine's local time; if
  9159. false, it will always work in GMT.
  9160. */
  9161. Time (int year,
  9162. int month,
  9163. int day,
  9164. int hours,
  9165. int minutes,
  9166. int seconds = 0,
  9167. int milliseconds = 0,
  9168. bool useLocalTime = true) noexcept;
  9169. /** Creates a copy of another Time object. */
  9170. Time (const Time& other) noexcept;
  9171. /** Destructor. */
  9172. ~Time() noexcept;
  9173. /** Copies this time from another one. */
  9174. Time& operator= (const Time& other) noexcept;
  9175. /** Returns a Time object that is set to the current system time.
  9176. @see currentTimeMillis
  9177. */
  9178. static Time JUCE_CALLTYPE getCurrentTime() noexcept;
  9179. /** Returns the time as a number of milliseconds.
  9180. @returns the number of milliseconds this Time object represents, since
  9181. midnight jan 1st 1970.
  9182. @see getMilliseconds
  9183. */
  9184. int64 toMilliseconds() const noexcept { return millisSinceEpoch; }
  9185. /** Returns the year.
  9186. A 4-digit format is used, e.g. 2004.
  9187. */
  9188. int getYear() const noexcept;
  9189. /** Returns the number of the month.
  9190. The value returned is in the range 0 to 11.
  9191. @see getMonthName
  9192. */
  9193. int getMonth() const noexcept;
  9194. /** Returns the name of the month.
  9195. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  9196. it'll return the long form, e.g. "January"
  9197. @see getMonth
  9198. */
  9199. String getMonthName (bool threeLetterVersion) const;
  9200. /** Returns the day of the month.
  9201. The value returned is in the range 1 to 31.
  9202. */
  9203. int getDayOfMonth() const noexcept;
  9204. /** Returns the number of the day of the week.
  9205. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  9206. */
  9207. int getDayOfWeek() const noexcept;
  9208. /** Returns the name of the weekday.
  9209. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  9210. false, it'll return the full version, e.g. "Tuesday".
  9211. */
  9212. String getWeekdayName (bool threeLetterVersion) const;
  9213. /** Returns the number of hours since midnight.
  9214. This is in 24-hour clock format, in the range 0 to 23.
  9215. @see getHoursInAmPmFormat, isAfternoon
  9216. */
  9217. int getHours() const noexcept;
  9218. /** Returns true if the time is in the afternoon.
  9219. So it returns true for "PM", false for "AM".
  9220. @see getHoursInAmPmFormat, getHours
  9221. */
  9222. bool isAfternoon() const noexcept;
  9223. /** Returns the hours in 12-hour clock format.
  9224. This will return a value 1 to 12 - use isAfternoon() to find out
  9225. whether this is in the afternoon or morning.
  9226. @see getHours, isAfternoon
  9227. */
  9228. int getHoursInAmPmFormat() const noexcept;
  9229. /** Returns the number of minutes, 0 to 59. */
  9230. int getMinutes() const noexcept;
  9231. /** Returns the number of seconds, 0 to 59. */
  9232. int getSeconds() const noexcept;
  9233. /** Returns the number of milliseconds, 0 to 999.
  9234. Unlike toMilliseconds(), this just returns the position within the
  9235. current second rather than the total number since the epoch.
  9236. @see toMilliseconds
  9237. */
  9238. int getMilliseconds() const noexcept;
  9239. /** Returns true if the local timezone uses a daylight saving correction. */
  9240. bool isDaylightSavingTime() const noexcept;
  9241. /** Returns a 3-character string to indicate the local timezone. */
  9242. String getTimeZone() const noexcept;
  9243. /** Quick way of getting a string version of a date and time.
  9244. For a more powerful way of formatting the date and time, see the formatted() method.
  9245. @param includeDate whether to include the date in the string
  9246. @param includeTime whether to include the time in the string
  9247. @param includeSeconds if the time is being included, this provides an option not to include
  9248. the seconds in it
  9249. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  9250. hour notation.
  9251. @see formatted
  9252. */
  9253. String toString (bool includeDate,
  9254. bool includeTime,
  9255. bool includeSeconds = true,
  9256. bool use24HourClock = false) const noexcept;
  9257. /** Converts this date/time to a string with a user-defined format.
  9258. This uses the C strftime() function to format this time as a string. To save you
  9259. looking it up, these are the escape codes that strftime uses (other codes might
  9260. work on some platforms and not others, but these are the common ones):
  9261. %a is replaced by the locale's abbreviated weekday name.
  9262. %A is replaced by the locale's full weekday name.
  9263. %b is replaced by the locale's abbreviated month name.
  9264. %B is replaced by the locale's full month name.
  9265. %c is replaced by the locale's appropriate date and time representation.
  9266. %d is replaced by the day of the month as a decimal number [01,31].
  9267. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  9268. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  9269. %j is replaced by the day of the year as a decimal number [001,366].
  9270. %m is replaced by the month as a decimal number [01,12].
  9271. %M is replaced by the minute as a decimal number [00,59].
  9272. %p is replaced by the locale's equivalent of either a.m. or p.m.
  9273. %S is replaced by the second as a decimal number [00,61].
  9274. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  9275. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  9276. %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.
  9277. %x is replaced by the locale's appropriate date representation.
  9278. %X is replaced by the locale's appropriate time representation.
  9279. %y is replaced by the year without century as a decimal number [00,99].
  9280. %Y is replaced by the year with century as a decimal number.
  9281. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  9282. %% is replaced by %.
  9283. @see toString
  9284. */
  9285. String formatted (const String& format) const;
  9286. /** Adds a RelativeTime to this time. */
  9287. Time& operator+= (const RelativeTime& delta);
  9288. /** Subtracts a RelativeTime from this time. */
  9289. Time& operator-= (const RelativeTime& delta);
  9290. /** Tries to set the computer's clock.
  9291. @returns true if this succeeds, although depending on the system, the
  9292. application might not have sufficient privileges to do this.
  9293. */
  9294. bool setSystemTimeToThisTime() const;
  9295. /** Returns the name of a day of the week.
  9296. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  9297. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  9298. false, it'll return the full version, e.g. "Tuesday".
  9299. */
  9300. static String getWeekdayName (int dayNumber,
  9301. bool threeLetterVersion);
  9302. /** Returns the name of one of the months.
  9303. @param monthNumber the month, 0 to 11
  9304. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  9305. it'll return the long form, e.g. "January"
  9306. */
  9307. static String getMonthName (int monthNumber,
  9308. bool threeLetterVersion);
  9309. // Static methods for getting system timers directly..
  9310. /** Returns the current system time.
  9311. Returns the number of milliseconds since midnight jan 1st 1970.
  9312. Should be accurate to within a few millisecs, depending on platform,
  9313. hardware, etc.
  9314. */
  9315. static int64 currentTimeMillis() noexcept;
  9316. /** Returns the number of millisecs since a fixed event (usually system startup).
  9317. This returns a monotonically increasing value which it unaffected by changes to the
  9318. system clock. It should be accurate to within a few millisecs, depending on platform,
  9319. hardware, etc.
  9320. Being a 32-bit return value, it will of course wrap back to 0 after 2^32 seconds of
  9321. uptime, so be careful to take that into account. If you need a 64-bit time, you can
  9322. use currentTimeMillis() instead.
  9323. @see getApproximateMillisecondCounter
  9324. */
  9325. static uint32 getMillisecondCounter() noexcept;
  9326. /** Returns the number of millisecs since a fixed event (usually system startup).
  9327. This has the same function as getMillisecondCounter(), but returns a more accurate
  9328. value, using a higher-resolution timer if one is available.
  9329. @see getMillisecondCounter
  9330. */
  9331. static double getMillisecondCounterHiRes() noexcept;
  9332. /** Waits until the getMillisecondCounter() reaches a given value.
  9333. This will make the thread sleep as efficiently as it can while it's waiting.
  9334. */
  9335. static void waitForMillisecondCounter (uint32 targetTime) noexcept;
  9336. /** Less-accurate but faster version of getMillisecondCounter().
  9337. This will return the last value that getMillisecondCounter() returned, so doesn't
  9338. need to make a system call, but is less accurate - it shouldn't be more than
  9339. 100ms away from the correct time, though, so is still accurate enough for a
  9340. lot of purposes.
  9341. @see getMillisecondCounter
  9342. */
  9343. static uint32 getApproximateMillisecondCounter() noexcept;
  9344. // High-resolution timers..
  9345. /** Returns the current high-resolution counter's tick-count.
  9346. This is a similar idea to getMillisecondCounter(), but with a higher
  9347. resolution.
  9348. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  9349. secondsToHighResolutionTicks
  9350. */
  9351. static int64 getHighResolutionTicks() noexcept;
  9352. /** Returns the resolution of the high-resolution counter in ticks per second.
  9353. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  9354. secondsToHighResolutionTicks
  9355. */
  9356. static int64 getHighResolutionTicksPerSecond() noexcept;
  9357. /** Converts a number of high-resolution ticks into seconds.
  9358. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  9359. secondsToHighResolutionTicks
  9360. */
  9361. static double highResolutionTicksToSeconds (int64 ticks) noexcept;
  9362. /** Converts a number seconds into high-resolution ticks.
  9363. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  9364. highResolutionTicksToSeconds
  9365. */
  9366. static int64 secondsToHighResolutionTicks (double seconds) noexcept;
  9367. private:
  9368. int64 millisSinceEpoch;
  9369. };
  9370. /** Adds a RelativeTime to a Time. */
  9371. JUCE_API Time operator+ (const Time& time, const RelativeTime& delta);
  9372. /** Adds a RelativeTime to a Time. */
  9373. JUCE_API Time operator+ (const RelativeTime& delta, const Time& time);
  9374. /** Subtracts a RelativeTime from a Time. */
  9375. JUCE_API Time operator- (const Time& time, const RelativeTime& delta);
  9376. /** Returns the relative time difference between two times. */
  9377. JUCE_API const RelativeTime operator- (const Time& time1, const Time& time2);
  9378. /** Compares two Time objects. */
  9379. JUCE_API bool operator== (const Time& time1, const Time& time2);
  9380. /** Compares two Time objects. */
  9381. JUCE_API bool operator!= (const Time& time1, const Time& time2);
  9382. /** Compares two Time objects. */
  9383. JUCE_API bool operator< (const Time& time1, const Time& time2);
  9384. /** Compares two Time objects. */
  9385. JUCE_API bool operator<= (const Time& time1, const Time& time2);
  9386. /** Compares two Time objects. */
  9387. JUCE_API bool operator> (const Time& time1, const Time& time2);
  9388. /** Compares two Time objects. */
  9389. JUCE_API bool operator>= (const Time& time1, const Time& time2);
  9390. #endif // __JUCE_TIME_JUCEHEADER__
  9391. /*** End of inlined file: juce_Time.h ***/
  9392. /*** Start of inlined file: juce_MemoryBlock.h ***/
  9393. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  9394. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  9395. /**
  9396. A class to hold a resizable block of raw data.
  9397. */
  9398. class JUCE_API MemoryBlock
  9399. {
  9400. public:
  9401. /** Create an uninitialised block with 0 size. */
  9402. MemoryBlock() noexcept;
  9403. /** Creates a memory block with a given initial size.
  9404. @param initialSize the size of block to create
  9405. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  9406. */
  9407. MemoryBlock (const size_t initialSize,
  9408. bool initialiseToZero = false);
  9409. /** Creates a copy of another memory block. */
  9410. MemoryBlock (const MemoryBlock& other);
  9411. /** Creates a memory block using a copy of a block of data.
  9412. @param dataToInitialiseFrom some data to copy into this block
  9413. @param sizeInBytes how much space to use
  9414. */
  9415. MemoryBlock (const void* dataToInitialiseFrom, size_t sizeInBytes);
  9416. /** Destructor. */
  9417. ~MemoryBlock() noexcept;
  9418. /** Copies another memory block onto this one.
  9419. This block will be resized and copied to exactly match the other one.
  9420. */
  9421. MemoryBlock& operator= (const MemoryBlock& other);
  9422. /** Compares two memory blocks.
  9423. @returns true only if the two blocks are the same size and have identical contents.
  9424. */
  9425. bool operator== (const MemoryBlock& other) const noexcept;
  9426. /** Compares two memory blocks.
  9427. @returns true if the two blocks are different sizes or have different contents.
  9428. */
  9429. bool operator!= (const MemoryBlock& other) const noexcept;
  9430. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  9431. */
  9432. bool matches (const void* data, size_t dataSize) const noexcept;
  9433. /** Returns a void pointer to the data.
  9434. Note that the pointer returned will probably become invalid when the
  9435. block is resized.
  9436. */
  9437. void* getData() const noexcept { return data; }
  9438. /** Returns a byte from the memory block.
  9439. This returns a reference, so you can also use it to set a byte.
  9440. */
  9441. template <typename Type>
  9442. char& operator[] (const Type offset) const noexcept { return data [offset]; }
  9443. /** Returns the block's current allocated size, in bytes. */
  9444. size_t getSize() const noexcept { return size; }
  9445. /** Resizes the memory block.
  9446. This will try to keep as much of the block's current content as it can,
  9447. and can optionally be made to clear any new space that gets allocated at
  9448. the end of the block.
  9449. @param newSize the new desired size for the block
  9450. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  9451. whether to clear the new section or just leave it
  9452. uninitialised
  9453. @see ensureSize
  9454. */
  9455. void setSize (const size_t newSize,
  9456. bool initialiseNewSpaceToZero = false);
  9457. /** Increases the block's size only if it's smaller than a given size.
  9458. @param minimumSize if the block is already bigger than this size, no action
  9459. will be taken; otherwise it will be increased to this size
  9460. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  9461. whether to clear the new section or just leave it
  9462. uninitialised
  9463. @see setSize
  9464. */
  9465. void ensureSize (const size_t minimumSize,
  9466. bool initialiseNewSpaceToZero = false);
  9467. /** Fills the entire memory block with a repeated byte value.
  9468. This is handy for clearing a block of memory to zero.
  9469. */
  9470. void fillWith (uint8 valueToUse) noexcept;
  9471. /** Adds another block of data to the end of this one.
  9472. This block's size will be increased accordingly.
  9473. */
  9474. void append (const void* data, size_t numBytes);
  9475. /** Exchanges the contents of this and another memory block.
  9476. No actual copying is required for this, so it's very fast.
  9477. */
  9478. void swapWith (MemoryBlock& other) noexcept;
  9479. /** Copies data into this MemoryBlock from a memory address.
  9480. @param srcData the memory location of the data to copy into this block
  9481. @param destinationOffset the offset in this block at which the data being copied should begin
  9482. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  9483. it will be clipped so not to do anything nasty)
  9484. */
  9485. void copyFrom (const void* srcData,
  9486. int destinationOffset,
  9487. size_t numBytes) noexcept;
  9488. /** Copies data from this MemoryBlock to a memory address.
  9489. @param destData the memory location to write to
  9490. @param sourceOffset the offset within this block from which the copied data will be read
  9491. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  9492. zeros will be used for that portion of the data)
  9493. */
  9494. void copyTo (void* destData,
  9495. int sourceOffset,
  9496. size_t numBytes) const noexcept;
  9497. /** Chops out a section of the block.
  9498. This will remove a section of the memory block and close the gap around it,
  9499. shifting any subsequent data downwards and reducing the size of the block.
  9500. If the range specified goes beyond the size of the block, it will be clipped.
  9501. */
  9502. void removeSection (size_t startByte, size_t numBytesToRemove);
  9503. /** Attempts to parse the contents of the block as a zero-terminated UTF8 string. */
  9504. String toString() const;
  9505. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  9506. The block will be resized to the number of valid bytes read from the string.
  9507. Non-hex characters in the string will be ignored.
  9508. @see String::toHexString()
  9509. */
  9510. void loadFromHexString (const String& sourceHexString);
  9511. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  9512. void setBitRange (size_t bitRangeStart,
  9513. size_t numBits,
  9514. int binaryNumberToApply) noexcept;
  9515. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  9516. int getBitRange (size_t bitRangeStart,
  9517. size_t numBitsToRead) const noexcept;
  9518. /** Returns a string of characters that represent the binary contents of this block.
  9519. Uses a 64-bit encoding system to allow binary data to be turned into a string
  9520. of simple non-extended characters, e.g. for storage in XML.
  9521. @see fromBase64Encoding
  9522. */
  9523. String toBase64Encoding() const;
  9524. /** Takes a string of encoded characters and turns it into binary data.
  9525. The string passed in must have been created by to64BitEncoding(), and this
  9526. block will be resized to recreate the original data block.
  9527. @see toBase64Encoding
  9528. */
  9529. bool fromBase64Encoding (const String& encodedString);
  9530. private:
  9531. HeapBlock <char> data;
  9532. size_t size;
  9533. static const char* const encodingTable;
  9534. JUCE_LEAK_DETECTOR (MemoryBlock);
  9535. };
  9536. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  9537. /*** End of inlined file: juce_MemoryBlock.h ***/
  9538. /*** Start of inlined file: juce_Result.h ***/
  9539. #ifndef __JUCE_RESULT_JUCEHEADER__
  9540. #define __JUCE_RESULT_JUCEHEADER__
  9541. /**
  9542. Represents the 'success' or 'failure' of an operation, and holds an associated
  9543. error message to describe the error when there's a failure.
  9544. E.g.
  9545. @code
  9546. Result myOperation()
  9547. {
  9548. if (doSomeKindOfFoobar())
  9549. return Result::ok();
  9550. else
  9551. return Result::fail ("foobar didn't work!");
  9552. }
  9553. const Result result (myOperation());
  9554. if (result.wasOk())
  9555. {
  9556. ...it's all good...
  9557. }
  9558. else
  9559. {
  9560. warnUserAboutFailure ("The foobar operation failed! Error message was: "
  9561. + result.getErrorMessage());
  9562. }
  9563. @endcode
  9564. */
  9565. class Result
  9566. {
  9567. public:
  9568. /** Creates and returns a 'successful' result. */
  9569. static Result ok() noexcept;
  9570. /** Creates a 'failure' result.
  9571. If you pass a blank error message in here, a default "Unknown Error" message
  9572. will be used instead.
  9573. */
  9574. static Result fail (const String& errorMessage) noexcept;
  9575. /** Returns true if this result indicates a success. */
  9576. bool wasOk() const noexcept;
  9577. /** Returns true if this result indicates a failure.
  9578. You can use getErrorMessage() to retrieve the error message associated
  9579. with the failure.
  9580. */
  9581. bool failed() const noexcept;
  9582. /** Returns true if this result indicates a success.
  9583. This is equivalent to calling wasOk().
  9584. */
  9585. operator bool() const noexcept;
  9586. /** Returns true if this result indicates a failure.
  9587. This is equivalent to calling failed().
  9588. */
  9589. bool operator!() const noexcept;
  9590. /** Returns the error message that was set when this result was created.
  9591. For a successful result, this will be an empty string;
  9592. */
  9593. const String& getErrorMessage() const noexcept;
  9594. Result (const Result& other);
  9595. Result& operator= (const Result& other);
  9596. bool operator== (const Result& other) const noexcept;
  9597. bool operator!= (const Result& other) const noexcept;
  9598. private:
  9599. String errorMessage;
  9600. explicit Result (const String& errorMessage) noexcept;
  9601. // These casts are private to prevent people trying to use the Result object in numeric contexts
  9602. operator int() const;
  9603. operator void*() const;
  9604. };
  9605. #endif // __JUCE_RESULT_JUCEHEADER__
  9606. /*** End of inlined file: juce_Result.h ***/
  9607. class FileInputStream;
  9608. class FileOutputStream;
  9609. /**
  9610. Represents a local file or directory.
  9611. This class encapsulates the absolute pathname of a file or directory, and
  9612. has methods for finding out about the file and changing its properties.
  9613. To read or write to the file, there are methods for returning an input or
  9614. output stream.
  9615. @see FileInputStream, FileOutputStream
  9616. */
  9617. class JUCE_API File
  9618. {
  9619. public:
  9620. /** Creates an (invalid) file object.
  9621. The file is initially set to an empty path, so getFullPath() will return
  9622. an empty string, and comparing the file to File::nonexistent will return
  9623. true.
  9624. You can use its operator= method to point it at a proper file.
  9625. */
  9626. File() {}
  9627. /** Creates a file from an absolute path.
  9628. If the path supplied is a relative path, it is taken to be relative
  9629. to the current working directory (see File::getCurrentWorkingDirectory()),
  9630. but this isn't a recommended way of creating a file, because you
  9631. never know what the CWD is going to be.
  9632. On the Mac/Linux, the path can include "~" notation for referring to
  9633. user home directories.
  9634. */
  9635. File (const String& path);
  9636. /** Creates a copy of another file object. */
  9637. File (const File& other);
  9638. /** Destructor. */
  9639. ~File() {}
  9640. /** Sets the file based on an absolute pathname.
  9641. If the path supplied is a relative path, it is taken to be relative
  9642. to the current working directory (see File::getCurrentWorkingDirectory()),
  9643. but this isn't a recommended way of creating a file, because you
  9644. never know what the CWD is going to be.
  9645. On the Mac/Linux, the path can include "~" notation for referring to
  9646. user home directories.
  9647. */
  9648. File& operator= (const String& newFilePath);
  9649. /** Copies from another file object. */
  9650. File& operator= (const File& otherFile);
  9651. /** This static constant is used for referring to an 'invalid' file. */
  9652. static const File nonexistent;
  9653. /** Checks whether the file actually exists.
  9654. @returns true if the file exists, either as a file or a directory.
  9655. @see existsAsFile, isDirectory
  9656. */
  9657. bool exists() const;
  9658. /** Checks whether the file exists and is a file rather than a directory.
  9659. @returns true only if this is a real file, false if it's a directory
  9660. or doesn't exist
  9661. @see exists, isDirectory
  9662. */
  9663. bool existsAsFile() const;
  9664. /** Checks whether the file is a directory that exists.
  9665. @returns true only if the file is a directory which actually exists, so
  9666. false if it's a file or doesn't exist at all
  9667. @see exists, existsAsFile
  9668. */
  9669. bool isDirectory() const;
  9670. /** Returns the size of the file in bytes.
  9671. @returns the number of bytes in the file, or 0 if it doesn't exist.
  9672. */
  9673. int64 getSize() const;
  9674. /** Utility function to convert a file size in bytes to a neat string description.
  9675. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  9676. 2000000 would produce "2 MB", etc.
  9677. */
  9678. static String descriptionOfSizeInBytes (int64 bytes);
  9679. /** Returns the complete, absolute path of this file.
  9680. This includes the filename and all its parent folders. On Windows it'll
  9681. also include the drive letter prefix; on Mac or Linux it'll be a complete
  9682. path starting from the root folder.
  9683. If you just want the file's name, you should use getFileName() or
  9684. getFileNameWithoutExtension().
  9685. @see getFileName, getRelativePathFrom
  9686. */
  9687. const String& getFullPathName() const noexcept { return fullPath; }
  9688. /** Returns the last section of the pathname.
  9689. Returns just the final part of the path - e.g. if the whole path
  9690. is "/moose/fish/foo.txt" this will return "foo.txt".
  9691. For a directory, it returns the final part of the path - e.g. for the
  9692. directory "/moose/fish" it'll return "fish".
  9693. If the filename begins with a dot, it'll return the whole filename, e.g. for
  9694. "/moose/.fish", it'll return ".fish"
  9695. @see getFullPathName, getFileNameWithoutExtension
  9696. */
  9697. String getFileName() const;
  9698. /** Creates a relative path that refers to a file relatively to a given directory.
  9699. e.g. File ("/moose/foo.txt").getRelativePathFrom (File ("/moose/fish/haddock"))
  9700. would return "../../foo.txt".
  9701. If it's not possible to navigate from one file to the other, an absolute
  9702. path is returned. If the paths are invalid, an empty string may also be
  9703. returned.
  9704. @param directoryToBeRelativeTo the directory which the resultant string will
  9705. be relative to. If this is actually a file rather than
  9706. a directory, its parent directory will be used instead.
  9707. If it doesn't exist, it's assumed to be a directory.
  9708. @see getChildFile, isAbsolutePath
  9709. */
  9710. String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  9711. /** Returns the file's extension.
  9712. Returns the file extension of this file, also including the dot.
  9713. e.g. "/moose/fish/foo.txt" would return ".txt"
  9714. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  9715. */
  9716. String getFileExtension() const;
  9717. /** Checks whether the file has a given extension.
  9718. @param extensionToTest the extension to look for - it doesn't matter whether or
  9719. not this string has a dot at the start, so ".wav" and "wav"
  9720. will have the same effect. The comparison used is
  9721. case-insensitve. To compare with multiple extensions, this
  9722. parameter can contain multiple strings, separated by semi-colons -
  9723. so, for example: hasFileExtension (".jpeg;png;gif") would return
  9724. true if the file has any of those three extensions.
  9725. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  9726. */
  9727. bool hasFileExtension (const String& extensionToTest) const;
  9728. /** Returns a version of this file with a different file extension.
  9729. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  9730. @param newExtension the new extension, either with or without a dot at the start (this
  9731. doesn't make any difference). To get remove a file's extension altogether,
  9732. pass an empty string into this function.
  9733. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  9734. */
  9735. File withFileExtension (const String& newExtension) const;
  9736. /** Returns the last part of the filename, without its file extension.
  9737. e.g. for "/moose/fish/foo.txt" this will return "foo".
  9738. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  9739. */
  9740. String getFileNameWithoutExtension() const;
  9741. /** Returns a 32-bit hash-code that identifies this file.
  9742. This is based on the filename. Obviously it's possible, although unlikely, that
  9743. two files will have the same hash-code.
  9744. */
  9745. int hashCode() const;
  9746. /** Returns a 64-bit hash-code that identifies this file.
  9747. This is based on the filename. Obviously it's possible, although unlikely, that
  9748. two files will have the same hash-code.
  9749. */
  9750. int64 hashCode64() const;
  9751. /** Returns a file based on a relative path.
  9752. This will find a child file or directory of the current object.
  9753. e.g.
  9754. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  9755. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  9756. If the string is actually an absolute path, it will be treated as such, e.g.
  9757. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  9758. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  9759. */
  9760. File getChildFile (String relativePath) const;
  9761. /** Returns a file which is in the same directory as this one.
  9762. This is equivalent to getParentDirectory().getChildFile (name).
  9763. @see getChildFile, getParentDirectory
  9764. */
  9765. File getSiblingFile (const String& siblingFileName) const;
  9766. /** Returns the directory that contains this file or directory.
  9767. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  9768. */
  9769. File getParentDirectory() const;
  9770. /** Checks whether a file is somewhere inside a directory.
  9771. Returns true if this file is somewhere inside a subdirectory of the directory
  9772. that is passed in. Neither file actually has to exist, because the function
  9773. just checks the paths for similarities.
  9774. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  9775. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  9776. */
  9777. bool isAChildOf (const File& potentialParentDirectory) const;
  9778. /** Chooses a filename relative to this one that doesn't already exist.
  9779. If this file is a directory, this will return a child file of this
  9780. directory that doesn't exist, by adding numbers to a prefix and suffix until
  9781. it finds one that isn't already there.
  9782. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  9783. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  9784. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  9785. @param prefix the string to use for the filename before the number
  9786. @param suffix the string to add to the filename after the number
  9787. @param putNumbersInBrackets if true, this will create filenames in the
  9788. format "prefix(number)suffix", if false, it will leave the
  9789. brackets out.
  9790. */
  9791. File getNonexistentChildFile (const String& prefix,
  9792. const String& suffix,
  9793. bool putNumbersInBrackets = true) const;
  9794. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  9795. If this file doesn't exist, this will just return itself, otherwise it
  9796. will return an appropriate sibling that doesn't exist, e.g. if a file
  9797. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  9798. @param putNumbersInBrackets whether to add brackets around the numbers that
  9799. get appended to the new filename.
  9800. */
  9801. File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  9802. /** Compares the pathnames for two files. */
  9803. bool operator== (const File& otherFile) const;
  9804. /** Compares the pathnames for two files. */
  9805. bool operator!= (const File& otherFile) const;
  9806. /** Compares the pathnames for two files. */
  9807. bool operator< (const File& otherFile) const;
  9808. /** Compares the pathnames for two files. */
  9809. bool operator> (const File& otherFile) const;
  9810. /** Checks whether a file can be created or written to.
  9811. @returns true if it's possible to create and write to this file. If the file
  9812. doesn't already exist, this will check its parent directory to
  9813. see if writing is allowed.
  9814. @see setReadOnly
  9815. */
  9816. bool hasWriteAccess() const;
  9817. /** Changes the write-permission of a file or directory.
  9818. @param shouldBeReadOnly whether to add or remove write-permission
  9819. @param applyRecursively if the file is a directory and this is true, it will
  9820. recurse through all the subfolders changing the permissions
  9821. of all files
  9822. @returns true if it manages to change the file's permissions.
  9823. @see hasWriteAccess
  9824. */
  9825. bool setReadOnly (bool shouldBeReadOnly,
  9826. bool applyRecursively = false) const;
  9827. /** Returns true if this file is a hidden or system file.
  9828. The criteria for deciding whether a file is hidden are platform-dependent.
  9829. */
  9830. bool isHidden() const;
  9831. /** If this file is a link, this returns the file that it points to.
  9832. If this file isn't actually link, it'll just return itself.
  9833. */
  9834. File getLinkedTarget() const;
  9835. /** Returns the last modification time of this file.
  9836. @returns the time, or an invalid time if the file doesn't exist.
  9837. @see setLastModificationTime, getLastAccessTime, getCreationTime
  9838. */
  9839. Time getLastModificationTime() const;
  9840. /** Returns the last time this file was accessed.
  9841. @returns the time, or an invalid time if the file doesn't exist.
  9842. @see setLastAccessTime, getLastModificationTime, getCreationTime
  9843. */
  9844. Time getLastAccessTime() const;
  9845. /** Returns the time that this file was created.
  9846. @returns the time, or an invalid time if the file doesn't exist.
  9847. @see getLastModificationTime, getLastAccessTime
  9848. */
  9849. Time getCreationTime() const;
  9850. /** Changes the modification time for this file.
  9851. @param newTime the time to apply to the file
  9852. @returns true if it manages to change the file's time.
  9853. @see getLastModificationTime, setLastAccessTime, setCreationTime
  9854. */
  9855. bool setLastModificationTime (const Time& newTime) const;
  9856. /** Changes the last-access time for this file.
  9857. @param newTime the time to apply to the file
  9858. @returns true if it manages to change the file's time.
  9859. @see getLastAccessTime, setLastModificationTime, setCreationTime
  9860. */
  9861. bool setLastAccessTime (const Time& newTime) const;
  9862. /** Changes the creation date for this file.
  9863. @param newTime the time to apply to the file
  9864. @returns true if it manages to change the file's time.
  9865. @see getCreationTime, setLastModificationTime, setLastAccessTime
  9866. */
  9867. bool setCreationTime (const Time& newTime) const;
  9868. /** If possible, this will try to create a version string for the given file.
  9869. The OS may be able to look at the file and give a version for it - e.g. with
  9870. executables, bundles, dlls, etc. If no version is available, this will
  9871. return an empty string.
  9872. */
  9873. String getVersion() const;
  9874. /** Creates an empty file if it doesn't already exist.
  9875. If the file that this object refers to doesn't exist, this will create a file
  9876. of zero size.
  9877. If it already exists or is a directory, this method will do nothing.
  9878. @returns true if the file has been created (or if it already existed).
  9879. @see createDirectory
  9880. */
  9881. Result create() const;
  9882. /** Creates a new directory for this filename.
  9883. This will try to create the file as a directory, and fill also create
  9884. any parent directories it needs in order to complete the operation.
  9885. @returns a result to indicate whether the directory was created successfully, or
  9886. an error message if it failed.
  9887. @see create
  9888. */
  9889. Result createDirectory() const;
  9890. /** Deletes a file.
  9891. If this file is actually a directory, it may not be deleted correctly if it
  9892. contains files. See deleteRecursively() as a better way of deleting directories.
  9893. @returns true if the file has been successfully deleted (or if it didn't exist to
  9894. begin with).
  9895. @see deleteRecursively
  9896. */
  9897. bool deleteFile() const;
  9898. /** Deletes a file or directory and all its subdirectories.
  9899. If this file is a directory, this will try to delete it and all its subfolders. If
  9900. it's just a file, it will just try to delete the file.
  9901. @returns true if the file and all its subfolders have been successfully deleted
  9902. (or if it didn't exist to begin with).
  9903. @see deleteFile
  9904. */
  9905. bool deleteRecursively() const;
  9906. /** Moves this file or folder to the trash.
  9907. @returns true if the operation succeeded. It could fail if the trash is full, or
  9908. if the file is write-protected, so you should check the return value
  9909. and act appropriately.
  9910. */
  9911. bool moveToTrash() const;
  9912. /** Moves or renames a file.
  9913. Tries to move a file to a different location.
  9914. If the target file already exists, this will attempt to delete it first, and
  9915. will fail if this can't be done.
  9916. Note that the destination file isn't the directory to put it in, it's the actual
  9917. filename that you want the new file to have.
  9918. @returns true if the operation succeeds
  9919. */
  9920. bool moveFileTo (const File& targetLocation) const;
  9921. /** Copies a file.
  9922. Tries to copy a file to a different location.
  9923. If the target file already exists, this will attempt to delete it first, and
  9924. will fail if this can't be done.
  9925. @returns true if the operation succeeds
  9926. */
  9927. bool copyFileTo (const File& targetLocation) const;
  9928. /** Copies a directory.
  9929. Tries to copy an entire directory, recursively.
  9930. If this file isn't a directory or if any target files can't be created, this
  9931. will return false.
  9932. @param newDirectory the directory that this one should be copied to. Note that this
  9933. is the name of the actual directory to create, not the directory
  9934. into which the new one should be placed, so there must be enough
  9935. write privileges to create it if it doesn't exist. Any files inside
  9936. it will be overwritten by similarly named ones that are copied.
  9937. */
  9938. bool copyDirectoryTo (const File& newDirectory) const;
  9939. /** Used in file searching, to specify whether to return files, directories, or both.
  9940. */
  9941. enum TypesOfFileToFind
  9942. {
  9943. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  9944. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  9945. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  9946. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  9947. };
  9948. /** Searches inside a directory for files matching a wildcard pattern.
  9949. Assuming that this file is a directory, this method will search it
  9950. for either files or subdirectories whose names match a filename pattern.
  9951. @param results an array to which File objects will be added for the
  9952. files that the search comes up with
  9953. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9954. return files, directories, or both. If the ignoreHiddenFiles flag
  9955. is also added to this value, hidden files won't be returned
  9956. @param searchRecursively if true, all subdirectories will be recursed into to do
  9957. an exhaustive search
  9958. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9959. @returns the number of results that have been found
  9960. @see getNumberOfChildFiles, DirectoryIterator
  9961. */
  9962. int findChildFiles (Array<File>& results,
  9963. int whatToLookFor,
  9964. bool searchRecursively,
  9965. const String& wildCardPattern = "*") const;
  9966. /** Searches inside a directory and counts how many files match a wildcard pattern.
  9967. Assuming that this file is a directory, this method will search it
  9968. for either files or subdirectories whose names match a filename pattern,
  9969. and will return the number of matches found.
  9970. This isn't a recursive call, and will only search this directory, not
  9971. its children.
  9972. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9973. count files, directories, or both. If the ignoreHiddenFiles flag
  9974. is also added to this value, hidden files won't be counted
  9975. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9976. @returns the number of matches found
  9977. @see findChildFiles, DirectoryIterator
  9978. */
  9979. int getNumberOfChildFiles (int whatToLookFor,
  9980. const String& wildCardPattern = "*") const;
  9981. /** Returns true if this file is a directory that contains one or more subdirectories.
  9982. @see isDirectory, findChildFiles
  9983. */
  9984. bool containsSubDirectories() const;
  9985. /** Creates a stream to read from this file.
  9986. @returns a stream that will read from this file (initially positioned at the
  9987. start of the file), or 0 if the file can't be opened for some reason
  9988. @see createOutputStream, loadFileAsData
  9989. */
  9990. FileInputStream* createInputStream() const;
  9991. /** Creates a stream to write to this file.
  9992. If the file exists, the stream that is returned will be positioned ready for
  9993. writing at the end of the file, so you might want to use deleteFile() first
  9994. to write to an empty file.
  9995. @returns a stream that will write to this file (initially positioned at the
  9996. end of the file), or 0 if the file can't be opened for some reason
  9997. @see createInputStream, appendData, appendText
  9998. */
  9999. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  10000. /** Loads a file's contents into memory as a block of binary data.
  10001. Of course, trying to load a very large file into memory will blow up, so
  10002. it's better to check first.
  10003. @param result the data block to which the file's contents should be appended - note
  10004. that if the memory block might already contain some data, you
  10005. might want to clear it first
  10006. @returns true if the file could all be read into memory
  10007. */
  10008. bool loadFileAsData (MemoryBlock& result) const;
  10009. /** Reads a file into memory as a string.
  10010. Attempts to load the entire file as a zero-terminated string.
  10011. This makes use of InputStream::readEntireStreamAsString, which should
  10012. automatically cope with unicode/acsii file formats.
  10013. */
  10014. String loadFileAsString() const;
  10015. /** Appends a block of binary data to the end of the file.
  10016. This will try to write the given buffer to the end of the file.
  10017. @returns false if it can't write to the file for some reason
  10018. */
  10019. bool appendData (const void* dataToAppend,
  10020. int numberOfBytes) const;
  10021. /** Replaces this file's contents with a given block of data.
  10022. This will delete the file and replace it with the given data.
  10023. A nice feature of this method is that it's safe - instead of deleting
  10024. the file first and then re-writing it, it creates a new temporary file,
  10025. writes the data to that, and then moves the new file to replace the existing
  10026. file. This means that if the power gets pulled out or something crashes,
  10027. you're a lot less likely to end up with a corrupted or unfinished file..
  10028. Returns true if the operation succeeds, or false if it fails.
  10029. @see appendText
  10030. */
  10031. bool replaceWithData (const void* dataToWrite,
  10032. int numberOfBytes) const;
  10033. /** Appends a string to the end of the file.
  10034. This will try to append a text string to the file, as either 16-bit unicode
  10035. or 8-bit characters in the default system encoding.
  10036. It can also write the 'ff fe' unicode header bytes before the text to indicate
  10037. the endianness of the file.
  10038. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  10039. @see replaceWithText
  10040. */
  10041. bool appendText (const String& textToAppend,
  10042. bool asUnicode = false,
  10043. bool writeUnicodeHeaderBytes = false) const;
  10044. /** Replaces this file's contents with a given text string.
  10045. This will delete the file and replace it with the given text.
  10046. A nice feature of this method is that it's safe - instead of deleting
  10047. the file first and then re-writing it, it creates a new temporary file,
  10048. writes the text to that, and then moves the new file to replace the existing
  10049. file. This means that if the power gets pulled out or something crashes,
  10050. you're a lot less likely to end up with an empty file..
  10051. For an explanation of the parameters here, see the appendText() method.
  10052. Returns true if the operation succeeds, or false if it fails.
  10053. @see appendText
  10054. */
  10055. bool replaceWithText (const String& textToWrite,
  10056. bool asUnicode = false,
  10057. bool writeUnicodeHeaderBytes = false) const;
  10058. /** Attempts to scan the contents of this file and compare it to another file, returning
  10059. true if this is possible and they match byte-for-byte.
  10060. */
  10061. bool hasIdenticalContentTo (const File& other) const;
  10062. /** Creates a set of files to represent each file root.
  10063. e.g. on Windows this will create files for "c:\", "d:\" etc according
  10064. to which ones are available. On the Mac/Linux, this will probably
  10065. just add a single entry for "/".
  10066. */
  10067. static void findFileSystemRoots (Array<File>& results);
  10068. /** Finds the name of the drive on which this file lives.
  10069. @returns the volume label of the drive, or an empty string if this isn't possible
  10070. */
  10071. String getVolumeLabel() const;
  10072. /** Returns the serial number of the volume on which this file lives.
  10073. @returns the serial number, or zero if there's a problem doing this
  10074. */
  10075. int getVolumeSerialNumber() const;
  10076. /** Returns the number of bytes free on the drive that this file lives on.
  10077. @returns the number of bytes free, or 0 if there's a problem finding this out
  10078. @see getVolumeTotalSize
  10079. */
  10080. int64 getBytesFreeOnVolume() const;
  10081. /** Returns the total size of the drive that contains this file.
  10082. @returns the total number of bytes that the volume can hold
  10083. @see getBytesFreeOnVolume
  10084. */
  10085. int64 getVolumeTotalSize() const;
  10086. /** Returns true if this file is on a CD or DVD drive. */
  10087. bool isOnCDRomDrive() const;
  10088. /** Returns true if this file is on a hard disk.
  10089. This will fail if it's a network drive, but will still be true for
  10090. removable hard-disks.
  10091. */
  10092. bool isOnHardDisk() const;
  10093. /** Returns true if this file is on a removable disk drive.
  10094. This might be a usb-drive, a CD-rom, or maybe a network drive.
  10095. */
  10096. bool isOnRemovableDrive() const;
  10097. /** Launches the file as a process.
  10098. - if the file is executable, this will run it.
  10099. - if it's a document of some kind, it will launch the document with its
  10100. default viewer application.
  10101. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  10102. @see revealToUser
  10103. */
  10104. bool startAsProcess (const String& parameters = String::empty) const;
  10105. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  10106. @see startAsProcess
  10107. */
  10108. void revealToUser() const;
  10109. /** A set of types of location that can be passed to the getSpecialLocation() method.
  10110. */
  10111. enum SpecialLocationType
  10112. {
  10113. /** The user's home folder. This is the same as using File ("~"). */
  10114. userHomeDirectory,
  10115. /** The user's default documents folder. On Windows, this might be the user's
  10116. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  10117. doesn't tend to have one of these, so it might just return their home folder.
  10118. */
  10119. userDocumentsDirectory,
  10120. /** The folder that contains the user's desktop objects. */
  10121. userDesktopDirectory,
  10122. /** The folder in which applications store their persistent user-specific settings.
  10123. On Windows, this might be "\Documents and Settings\username\Application Data".
  10124. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  10125. always create your own sub-folder to put them in, to avoid making a mess.
  10126. */
  10127. userApplicationDataDirectory,
  10128. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  10129. of the computer, rather than just the current user.
  10130. On the Mac it'll be "/Library", on Windows, it could be something like
  10131. "\Documents and Settings\All Users\Application Data".
  10132. Depending on the setup, this folder may be read-only.
  10133. */
  10134. commonApplicationDataDirectory,
  10135. /** The folder that should be used for temporary files.
  10136. Always delete them when you're finished, to keep the user's computer tidy!
  10137. */
  10138. tempDirectory,
  10139. /** Returns this application's executable file.
  10140. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  10141. host app.
  10142. On the mac this will return the unix binary, not the package folder - see
  10143. currentApplicationFile for that.
  10144. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  10145. file link, invokedExecutableFile will return the name of the link.
  10146. */
  10147. currentExecutableFile,
  10148. /** Returns this application's location.
  10149. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  10150. host app.
  10151. On the mac this will return the package folder (if it's in one), not the unix binary
  10152. that's inside it - compare with currentExecutableFile.
  10153. */
  10154. currentApplicationFile,
  10155. /** Returns the file that was invoked to launch this executable.
  10156. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  10157. will return the name of the link that was used, whereas currentExecutableFile will return
  10158. the actual location of the target executable.
  10159. */
  10160. invokedExecutableFile,
  10161. /** In a plugin, this will return the path of the host executable. */
  10162. hostApplicationPath,
  10163. /** The directory in which applications normally get installed.
  10164. So on windows, this would be something like "c:\program files", on the
  10165. Mac "/Applications", or "/usr" on linux.
  10166. */
  10167. globalApplicationsDirectory,
  10168. /** The most likely place where a user might store their music files.
  10169. */
  10170. userMusicDirectory,
  10171. /** The most likely place where a user might store their movie files.
  10172. */
  10173. userMoviesDirectory,
  10174. };
  10175. /** Finds the location of a special type of file or directory, such as a home folder or
  10176. documents folder.
  10177. @see SpecialLocationType
  10178. */
  10179. static File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  10180. /** Returns a temporary file in the system's temp directory.
  10181. This will try to return the name of a non-existent temp file.
  10182. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  10183. */
  10184. static File createTempFile (const String& fileNameEnding);
  10185. /** Returns the current working directory.
  10186. @see setAsCurrentWorkingDirectory
  10187. */
  10188. static File getCurrentWorkingDirectory();
  10189. /** Sets the current working directory to be this file.
  10190. For this to work the file must point to a valid directory.
  10191. @returns true if the current directory has been changed.
  10192. @see getCurrentWorkingDirectory
  10193. */
  10194. bool setAsCurrentWorkingDirectory() const;
  10195. /** The system-specific file separator character.
  10196. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  10197. */
  10198. static const juce_wchar separator;
  10199. /** The system-specific file separator character, as a string.
  10200. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  10201. */
  10202. static const String separatorString;
  10203. /** Removes illegal characters from a filename.
  10204. This will return a copy of the given string after removing characters
  10205. that are not allowed in a legal filename, and possibly shortening the
  10206. string if it's too long.
  10207. Because this will remove slashes, don't use it on an absolute pathname.
  10208. @see createLegalPathName
  10209. */
  10210. static String createLegalFileName (const String& fileNameToFix);
  10211. /** Removes illegal characters from a pathname.
  10212. Similar to createLegalFileName(), but this won't remove slashes, so can
  10213. be used on a complete pathname.
  10214. @see createLegalFileName
  10215. */
  10216. static String createLegalPathName (const String& pathNameToFix);
  10217. /** Indicates whether filenames are case-sensitive on the current operating system.
  10218. */
  10219. static bool areFileNamesCaseSensitive();
  10220. /** Returns true if the string seems to be a fully-specified absolute path.
  10221. */
  10222. static bool isAbsolutePath (const String& path);
  10223. /** Creates a file that simply contains this string, without doing the sanity-checking
  10224. that the normal constructors do.
  10225. Best to avoid this unless you really know what you're doing.
  10226. */
  10227. static File createFileWithoutCheckingPath (const String& path);
  10228. /** Adds a separator character to the end of a path if it doesn't already have one. */
  10229. static String addTrailingSeparator (const String& path);
  10230. private:
  10231. String fullPath;
  10232. // internal way of contructing a file without checking the path
  10233. friend class DirectoryIterator;
  10234. File (const String&, int);
  10235. String getPathUpToLastSlash() const;
  10236. Result createDirectoryInternal (const String& fileName) const;
  10237. bool copyInternal (const File& dest) const;
  10238. bool moveInternal (const File& dest) const;
  10239. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  10240. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  10241. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  10242. static String parseAbsolutePath (const String& path);
  10243. JUCE_LEAK_DETECTOR (File);
  10244. };
  10245. #endif // __JUCE_FILE_JUCEHEADER__
  10246. /*** End of inlined file: juce_File.h ***/
  10247. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  10248. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  10249. will be the name of a pointer to each child element.
  10250. E.g. @code
  10251. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  10252. forEachXmlChildElement (*myParentXml, child)
  10253. {
  10254. if (child->hasTagName ("FOO"))
  10255. doSomethingWithXmlElement (child);
  10256. }
  10257. @endcode
  10258. @see forEachXmlChildElementWithTagName
  10259. */
  10260. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  10261. \
  10262. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  10263. childElementVariableName != 0; \
  10264. childElementVariableName = childElementVariableName->getNextElement())
  10265. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  10266. which have a specified tag.
  10267. This does the same job as the forEachXmlChildElement macro, but only for those
  10268. elements that have a particular tag name.
  10269. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  10270. will be the name of a pointer to each child element. The requiredTagName is the
  10271. tag name to match.
  10272. E.g. @code
  10273. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  10274. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  10275. {
  10276. // the child object is now guaranteed to be a <MYTAG> element..
  10277. doSomethingWithMYTAGElement (child);
  10278. }
  10279. @endcode
  10280. @see forEachXmlChildElement
  10281. */
  10282. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  10283. \
  10284. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  10285. childElementVariableName != 0; \
  10286. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  10287. /** Used to build a tree of elements representing an XML document.
  10288. An XML document can be parsed into a tree of XmlElements, each of which
  10289. represents an XML tag structure, and which may itself contain other
  10290. nested elements.
  10291. An XmlElement can also be converted back into a text document, and has
  10292. lots of useful methods for manipulating its attributes and sub-elements,
  10293. so XmlElements can actually be used as a handy general-purpose data
  10294. structure.
  10295. Here's an example of parsing some elements: @code
  10296. // check we're looking at the right kind of document..
  10297. if (myElement->hasTagName ("ANIMALS"))
  10298. {
  10299. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  10300. forEachXmlChildElement (*myElement, e)
  10301. {
  10302. if (e->hasTagName ("GIRAFFE"))
  10303. {
  10304. // found a giraffe, so use some of its attributes..
  10305. String giraffeName = e->getStringAttribute ("name");
  10306. int giraffeAge = e->getIntAttribute ("age");
  10307. bool isFriendly = e->getBoolAttribute ("friendly");
  10308. }
  10309. }
  10310. }
  10311. @endcode
  10312. And here's an example of how to create an XML document from scratch: @code
  10313. // create an outer node called "ANIMALS"
  10314. XmlElement animalsList ("ANIMALS");
  10315. for (int i = 0; i < numAnimals; ++i)
  10316. {
  10317. // create an inner element..
  10318. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  10319. giraffe->setAttribute ("name", "nigel");
  10320. giraffe->setAttribute ("age", 10);
  10321. giraffe->setAttribute ("friendly", true);
  10322. // ..and add our new element to the parent node
  10323. animalsList.addChildElement (giraffe);
  10324. }
  10325. // now we can turn the whole thing into a text document..
  10326. String myXmlDoc = animalsList.createDocument (String::empty);
  10327. @endcode
  10328. @see XmlDocument
  10329. */
  10330. class JUCE_API XmlElement
  10331. {
  10332. public:
  10333. /** Creates an XmlElement with this tag name. */
  10334. explicit XmlElement (const String& tagName) noexcept;
  10335. /** Creates a (deep) copy of another element. */
  10336. XmlElement (const XmlElement& other);
  10337. /** Creates a (deep) copy of another element. */
  10338. XmlElement& operator= (const XmlElement& other);
  10339. /** Deleting an XmlElement will also delete all its child elements. */
  10340. ~XmlElement() noexcept;
  10341. /** Compares two XmlElements to see if they contain the same text and attiributes.
  10342. The elements are only considered equivalent if they contain the same attiributes
  10343. with the same values, and have the same sub-nodes.
  10344. @param other the other element to compare to
  10345. @param ignoreOrderOfAttributes if true, this means that two elements with the
  10346. same attributes in a different order will be
  10347. considered the same; if false, the attributes must
  10348. be in the same order as well
  10349. */
  10350. bool isEquivalentTo (const XmlElement* other,
  10351. bool ignoreOrderOfAttributes) const noexcept;
  10352. /** Returns an XML text document that represents this element.
  10353. The string returned can be parsed to recreate the same XmlElement that
  10354. was used to create it.
  10355. @param dtdToUse the DTD to add to the document
  10356. @param allOnOneLine if true, this means that the document will not contain any
  10357. linefeeds, so it'll be smaller but not very easy to read.
  10358. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  10359. document
  10360. @param encodingType the character encoding format string to put into the xml
  10361. header
  10362. @param lineWrapLength the line length that will be used before items get placed on
  10363. a new line. This isn't an absolute maximum length, it just
  10364. determines how lists of attributes get broken up
  10365. @see writeToStream, writeToFile
  10366. */
  10367. String createDocument (const String& dtdToUse,
  10368. bool allOnOneLine = false,
  10369. bool includeXmlHeader = true,
  10370. const String& encodingType = "UTF-8",
  10371. int lineWrapLength = 60) const;
  10372. /** Writes the document to a stream as UTF-8.
  10373. @param output the stream to write to
  10374. @param dtdToUse the DTD to add to the document
  10375. @param allOnOneLine if true, this means that the document will not contain any
  10376. linefeeds, so it'll be smaller but not very easy to read.
  10377. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  10378. document
  10379. @param encodingType the character encoding format string to put into the xml
  10380. header
  10381. @param lineWrapLength the line length that will be used before items get placed on
  10382. a new line. This isn't an absolute maximum length, it just
  10383. determines how lists of attributes get broken up
  10384. @see writeToFile, createDocument
  10385. */
  10386. void writeToStream (OutputStream& output,
  10387. const String& dtdToUse,
  10388. bool allOnOneLine = false,
  10389. bool includeXmlHeader = true,
  10390. const String& encodingType = "UTF-8",
  10391. int lineWrapLength = 60) const;
  10392. /** Writes the element to a file as an XML document.
  10393. To improve safety in case something goes wrong while writing the file, this
  10394. will actually write the document to a new temporary file in the same
  10395. directory as the destination file, and if this succeeds, it will rename this
  10396. new file as the destination file (overwriting any existing file that was there).
  10397. @param destinationFile the file to write to. If this already exists, it will be
  10398. overwritten.
  10399. @param dtdToUse the DTD to add to the document
  10400. @param encodingType the character encoding format string to put into the xml
  10401. header
  10402. @param lineWrapLength the line length that will be used before items get placed on
  10403. a new line. This isn't an absolute maximum length, it just
  10404. determines how lists of attributes get broken up
  10405. @returns true if the file is written successfully; false if something goes wrong
  10406. in the process
  10407. @see createDocument
  10408. */
  10409. bool writeToFile (const File& destinationFile,
  10410. const String& dtdToUse,
  10411. const String& encodingType = "UTF-8",
  10412. int lineWrapLength = 60) const;
  10413. /** Returns this element's tag type name.
  10414. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  10415. "MOOSE".
  10416. @see hasTagName
  10417. */
  10418. inline const String& getTagName() const noexcept { return tagName; }
  10419. /** Tests whether this element has a particular tag name.
  10420. @param possibleTagName the tag name you're comparing it with
  10421. @see getTagName
  10422. */
  10423. bool hasTagName (const String& possibleTagName) const noexcept;
  10424. /** Returns the number of XML attributes this element contains.
  10425. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  10426. return 2.
  10427. */
  10428. int getNumAttributes() const noexcept;
  10429. /** Returns the name of one of the elements attributes.
  10430. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  10431. getAttributeName(1) would return "antlers".
  10432. @see getAttributeValue, getStringAttribute
  10433. */
  10434. const String& getAttributeName (int attributeIndex) const noexcept;
  10435. /** Returns the value of one of the elements attributes.
  10436. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  10437. getAttributeName(1) would return "2".
  10438. @see getAttributeName, getStringAttribute
  10439. */
  10440. const String& getAttributeValue (int attributeIndex) const noexcept;
  10441. // Attribute-handling methods..
  10442. /** Checks whether the element contains an attribute with a certain name. */
  10443. bool hasAttribute (const String& attributeName) const noexcept;
  10444. /** Returns the value of a named attribute.
  10445. @param attributeName the name of the attribute to look up
  10446. */
  10447. const String& getStringAttribute (const String& attributeName) const noexcept;
  10448. /** Returns the value of a named attribute.
  10449. @param attributeName the name of the attribute to look up
  10450. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10451. with this name
  10452. */
  10453. String getStringAttribute (const String& attributeName,
  10454. const String& defaultReturnValue) const;
  10455. /** Compares the value of a named attribute with a value passed-in.
  10456. @param attributeName the name of the attribute to look up
  10457. @param stringToCompareAgainst the value to compare it with
  10458. @param ignoreCase whether the comparison should be case-insensitive
  10459. @returns true if the value of the attribute is the same as the string passed-in;
  10460. false if it's different (or if no such attribute exists)
  10461. */
  10462. bool compareAttribute (const String& attributeName,
  10463. const String& stringToCompareAgainst,
  10464. bool ignoreCase = false) const noexcept;
  10465. /** Returns the value of a named attribute as an integer.
  10466. This will try to find the attribute and convert it to an integer (using
  10467. the String::getIntValue() method).
  10468. @param attributeName the name of the attribute to look up
  10469. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10470. with this name
  10471. @see setAttribute
  10472. */
  10473. int getIntAttribute (const String& attributeName,
  10474. int defaultReturnValue = 0) const;
  10475. /** Returns the value of a named attribute as floating-point.
  10476. This will try to find the attribute and convert it to an integer (using
  10477. the String::getDoubleValue() method).
  10478. @param attributeName the name of the attribute to look up
  10479. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10480. with this name
  10481. @see setAttribute
  10482. */
  10483. double getDoubleAttribute (const String& attributeName,
  10484. double defaultReturnValue = 0.0) const;
  10485. /** Returns the value of a named attribute as a boolean.
  10486. This will try to find the attribute and interpret it as a boolean. To do this,
  10487. it'll return true if the value is "1", "true", "y", etc, or false for other
  10488. values.
  10489. @param attributeName the name of the attribute to look up
  10490. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10491. with this name
  10492. */
  10493. bool getBoolAttribute (const String& attributeName,
  10494. bool defaultReturnValue = false) const;
  10495. /** Adds a named attribute to the element.
  10496. If the element already contains an attribute with this name, it's value will
  10497. be updated to the new value. If there's no such attribute yet, a new one will
  10498. be added.
  10499. Note that there are other setAttribute() methods that take integers,
  10500. doubles, etc. to make it easy to store numbers.
  10501. @param attributeName the name of the attribute to set
  10502. @param newValue the value to set it to
  10503. @see removeAttribute
  10504. */
  10505. void setAttribute (const String& attributeName,
  10506. const String& newValue);
  10507. /** Adds a named attribute to the element, setting it to an integer value.
  10508. If the element already contains an attribute with this name, it's value will
  10509. be updated to the new value. If there's no such attribute yet, a new one will
  10510. be added.
  10511. Note that there are other setAttribute() methods that take integers,
  10512. doubles, etc. to make it easy to store numbers.
  10513. @param attributeName the name of the attribute to set
  10514. @param newValue the value to set it to
  10515. */
  10516. void setAttribute (const String& attributeName,
  10517. int newValue);
  10518. /** Adds a named attribute to the element, setting it to a floating-point value.
  10519. If the element already contains an attribute with this name, it's value will
  10520. be updated to the new value. If there's no such attribute yet, a new one will
  10521. be added.
  10522. Note that there are other setAttribute() methods that take integers,
  10523. doubles, etc. to make it easy to store numbers.
  10524. @param attributeName the name of the attribute to set
  10525. @param newValue the value to set it to
  10526. */
  10527. void setAttribute (const String& attributeName,
  10528. double newValue);
  10529. /** Removes a named attribute from the element.
  10530. @param attributeName the name of the attribute to remove
  10531. @see removeAllAttributes
  10532. */
  10533. void removeAttribute (const String& attributeName) noexcept;
  10534. /** Removes all attributes from this element.
  10535. */
  10536. void removeAllAttributes() noexcept;
  10537. // Child element methods..
  10538. /** Returns the first of this element's sub-elements.
  10539. see getNextElement() for an example of how to iterate the sub-elements.
  10540. @see forEachXmlChildElement
  10541. */
  10542. XmlElement* getFirstChildElement() const noexcept { return firstChildElement; }
  10543. /** Returns the next of this element's siblings.
  10544. This can be used for iterating an element's sub-elements, e.g.
  10545. @code
  10546. XmlElement* child = myXmlDocument->getFirstChildElement();
  10547. while (child != nullptr)
  10548. {
  10549. ...do stuff with this child..
  10550. child = child->getNextElement();
  10551. }
  10552. @endcode
  10553. Note that when iterating the child elements, some of them might be
  10554. text elements as well as XML tags - use isTextElement() to work this
  10555. out.
  10556. Also, it's much easier and neater to use this method indirectly via the
  10557. forEachXmlChildElement macro.
  10558. @returns the sibling element that follows this one, or zero if this is the last
  10559. element in its parent
  10560. @see getNextElement, isTextElement, forEachXmlChildElement
  10561. */
  10562. inline XmlElement* getNextElement() const noexcept { return nextListItem; }
  10563. /** Returns the next of this element's siblings which has the specified tag
  10564. name.
  10565. This is like getNextElement(), but will scan through the list until it
  10566. finds an element with the given tag name.
  10567. @see getNextElement, forEachXmlChildElementWithTagName
  10568. */
  10569. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  10570. /** Returns the number of sub-elements in this element.
  10571. @see getChildElement
  10572. */
  10573. int getNumChildElements() const noexcept;
  10574. /** Returns the sub-element at a certain index.
  10575. It's not very efficient to iterate the sub-elements by index - see
  10576. getNextElement() for an example of how best to iterate.
  10577. @returns the n'th child of this element, or 0 if the index is out-of-range
  10578. @see getNextElement, isTextElement, getChildByName
  10579. */
  10580. XmlElement* getChildElement (int index) const noexcept;
  10581. /** Returns the first sub-element with a given tag-name.
  10582. @param tagNameToLookFor the tag name of the element you want to find
  10583. @returns the first element with this tag name, or 0 if none is found
  10584. @see getNextElement, isTextElement, getChildElement
  10585. */
  10586. XmlElement* getChildByName (const String& tagNameToLookFor) const noexcept;
  10587. /** Appends an element to this element's list of children.
  10588. Child elements are deleted automatically when their parent is deleted, so
  10589. make sure the object that you pass in will not be deleted by anything else,
  10590. and make sure it's not already the child of another element.
  10591. @see getFirstChildElement, getNextElement, getNumChildElements,
  10592. getChildElement, removeChildElement
  10593. */
  10594. void addChildElement (XmlElement* newChildElement) noexcept;
  10595. /** Inserts an element into this element's list of children.
  10596. Child elements are deleted automatically when their parent is deleted, so
  10597. make sure the object that you pass in will not be deleted by anything else,
  10598. and make sure it's not already the child of another element.
  10599. @param newChildNode the element to add
  10600. @param indexToInsertAt the index at which to insert the new element - if this is
  10601. below zero, it will be added to the end of the list
  10602. @see addChildElement, insertChildElement
  10603. */
  10604. void insertChildElement (XmlElement* newChildNode,
  10605. int indexToInsertAt) noexcept;
  10606. /** Creates a new element with the given name and returns it, after adding it
  10607. as a child element.
  10608. This is a handy method that means that instead of writing this:
  10609. @code
  10610. XmlElement* newElement = new XmlElement ("foobar");
  10611. myParentElement->addChildElement (newElement);
  10612. @endcode
  10613. ..you could just write this:
  10614. @code
  10615. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  10616. @endcode
  10617. */
  10618. XmlElement* createNewChildElement (const String& tagName);
  10619. /** Replaces one of this element's children with another node.
  10620. If the current element passed-in isn't actually a child of this element,
  10621. this will return false and the new one won't be added. Otherwise, the
  10622. existing element will be deleted, replaced with the new one, and it
  10623. will return true.
  10624. */
  10625. bool replaceChildElement (XmlElement* currentChildElement,
  10626. XmlElement* newChildNode) noexcept;
  10627. /** Removes a child element.
  10628. @param childToRemove the child to look for and remove
  10629. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  10630. just remove it
  10631. */
  10632. void removeChildElement (XmlElement* childToRemove,
  10633. bool shouldDeleteTheChild) noexcept;
  10634. /** Deletes all the child elements in the element.
  10635. @see removeChildElement, deleteAllChildElementsWithTagName
  10636. */
  10637. void deleteAllChildElements() noexcept;
  10638. /** Deletes all the child elements with a given tag name.
  10639. @see removeChildElement
  10640. */
  10641. void deleteAllChildElementsWithTagName (const String& tagName) noexcept;
  10642. /** Returns true if the given element is a child of this one. */
  10643. bool containsChildElement (const XmlElement* possibleChild) const noexcept;
  10644. /** Recursively searches all sub-elements to find one that contains the specified
  10645. child element.
  10646. */
  10647. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) noexcept;
  10648. /** Sorts the child elements using a comparator.
  10649. This will use a comparator object to sort the elements into order. The object
  10650. passed must have a method of the form:
  10651. @code
  10652. int compareElements (const XmlElement* first, const XmlElement* second);
  10653. @endcode
  10654. ..and this method must return:
  10655. - a value of < 0 if the first comes before the second
  10656. - a value of 0 if the two objects are equivalent
  10657. - a value of > 0 if the second comes before the first
  10658. To improve performance, the compareElements() method can be declared as static or const.
  10659. @param comparator the comparator to use for comparing elements.
  10660. @param retainOrderOfEquivalentItems if this is true, then items which the comparator
  10661. says are equivalent will be kept in the order in which they
  10662. currently appear in the array. This is slower to perform, but
  10663. may be important in some cases. If it's false, a faster algorithm
  10664. is used, but equivalent elements may be rearranged.
  10665. */
  10666. template <class ElementComparator>
  10667. void sortChildElements (ElementComparator& comparator,
  10668. bool retainOrderOfEquivalentItems = false)
  10669. {
  10670. const int num = getNumChildElements();
  10671. if (num > 1)
  10672. {
  10673. HeapBlock <XmlElement*> elems (num);
  10674. getChildElementsAsArray (elems);
  10675. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  10676. reorderChildElements (elems, num);
  10677. }
  10678. }
  10679. /** Returns true if this element is a section of text.
  10680. Elements can either be an XML tag element or a secton of text, so this
  10681. is used to find out what kind of element this one is.
  10682. @see getAllText, addTextElement, deleteAllTextElements
  10683. */
  10684. bool isTextElement() const noexcept;
  10685. /** Returns the text for a text element.
  10686. Note that if you have an element like this:
  10687. @code<xyz>hello</xyz>@endcode
  10688. then calling getText on the "xyz" element won't return "hello", because that is
  10689. actually stored in a special text sub-element inside the xyz element. To get the
  10690. "hello" string, you could either call getText on the (unnamed) sub-element, or
  10691. use getAllSubText() to do this automatically.
  10692. Note that leading and trailing whitespace will be included in the string - to remove
  10693. if, just call String::trim() on the result.
  10694. @see isTextElement, getAllSubText, getChildElementAllSubText
  10695. */
  10696. const String& getText() const noexcept;
  10697. /** Sets the text in a text element.
  10698. Note that this is only a valid call if this element is a text element. If it's
  10699. not, then no action will be performed. If you're trying to add text inside a normal
  10700. element, you probably want to use addTextElement() instead.
  10701. */
  10702. void setText (const String& newText);
  10703. /** Returns all the text from this element's child nodes.
  10704. This iterates all the child elements and when it finds text elements,
  10705. it concatenates their text into a big string which it returns.
  10706. E.g. @code<xyz>hello <x>there</x> world</xyz>@endcode
  10707. if you called getAllSubText on the "xyz" element, it'd return "hello there world".
  10708. Note that leading and trailing whitespace will be included in the string - to remove
  10709. if, just call String::trim() on the result.
  10710. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  10711. */
  10712. String getAllSubText() const;
  10713. /** Returns all the sub-text of a named child element.
  10714. If there is a child element with the given tag name, this will return
  10715. all of its sub-text (by calling getAllSubText() on it). If there is
  10716. no such child element, this will return the default string passed-in.
  10717. @see getAllSubText
  10718. */
  10719. String getChildElementAllSubText (const String& childTagName,
  10720. const String& defaultReturnValue) const;
  10721. /** Appends a section of text to this element.
  10722. @see isTextElement, getText, getAllSubText
  10723. */
  10724. void addTextElement (const String& text);
  10725. /** Removes all the text elements from this element.
  10726. @see isTextElement, getText, getAllSubText, addTextElement
  10727. */
  10728. void deleteAllTextElements() noexcept;
  10729. /** Creates a text element that can be added to a parent element.
  10730. */
  10731. static XmlElement* createTextElement (const String& text);
  10732. private:
  10733. struct XmlAttributeNode
  10734. {
  10735. XmlAttributeNode (const XmlAttributeNode& other) noexcept;
  10736. XmlAttributeNode (const String& name, const String& value) noexcept;
  10737. LinkedListPointer<XmlAttributeNode> nextListItem;
  10738. String name, value;
  10739. bool hasName (const String& name) const noexcept;
  10740. private:
  10741. XmlAttributeNode& operator= (const XmlAttributeNode&);
  10742. };
  10743. friend class XmlDocument;
  10744. friend class LinkedListPointer<XmlAttributeNode>;
  10745. friend class LinkedListPointer <XmlElement>;
  10746. friend class LinkedListPointer <XmlElement>::Appender;
  10747. LinkedListPointer <XmlElement> nextListItem;
  10748. LinkedListPointer <XmlElement> firstChildElement;
  10749. LinkedListPointer <XmlAttributeNode> attributes;
  10750. String tagName;
  10751. XmlElement (int) noexcept;
  10752. void copyChildrenAndAttributesFrom (const XmlElement& other);
  10753. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  10754. void getChildElementsAsArray (XmlElement**) const noexcept;
  10755. void reorderChildElements (XmlElement**, int) noexcept;
  10756. JUCE_LEAK_DETECTOR (XmlElement);
  10757. };
  10758. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  10759. /*** End of inlined file: juce_XmlElement.h ***/
  10760. /**
  10761. A set of named property values, which can be strings, integers, floating point, etc.
  10762. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  10763. to load and save types other than strings.
  10764. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  10765. messages and saves/loads the list from a file.
  10766. */
  10767. class JUCE_API PropertySet
  10768. {
  10769. public:
  10770. /** Creates an empty PropertySet.
  10771. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  10772. case-insensitive way
  10773. */
  10774. PropertySet (bool ignoreCaseOfKeyNames = false);
  10775. /** Creates a copy of another PropertySet.
  10776. */
  10777. PropertySet (const PropertySet& other);
  10778. /** Copies another PropertySet over this one.
  10779. */
  10780. PropertySet& operator= (const PropertySet& other);
  10781. /** Destructor. */
  10782. virtual ~PropertySet();
  10783. /** Returns one of the properties as a string.
  10784. If the value isn't found in this set, then this will look for it in a fallback
  10785. property set (if you've specified one with the setFallbackPropertySet() method),
  10786. and if it can't find one there, it'll return the default value passed-in.
  10787. @param keyName the name of the property to retrieve
  10788. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10789. */
  10790. String getValue (const String& keyName,
  10791. const String& defaultReturnValue = String::empty) const noexcept;
  10792. /** Returns one of the properties as an integer.
  10793. If the value isn't found in this set, then this will look for it in a fallback
  10794. property set (if you've specified one with the setFallbackPropertySet() method),
  10795. and if it can't find one there, it'll return the default value passed-in.
  10796. @param keyName the name of the property to retrieve
  10797. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10798. */
  10799. int getIntValue (const String& keyName,
  10800. const int defaultReturnValue = 0) const noexcept;
  10801. /** Returns one of the properties as an double.
  10802. If the value isn't found in this set, then this will look for it in a fallback
  10803. property set (if you've specified one with the setFallbackPropertySet() method),
  10804. and if it can't find one there, it'll return the default value passed-in.
  10805. @param keyName the name of the property to retrieve
  10806. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10807. */
  10808. double getDoubleValue (const String& keyName,
  10809. const double defaultReturnValue = 0.0) const noexcept;
  10810. /** Returns one of the properties as an boolean.
  10811. The result will be true if the string found for this key name can be parsed as a non-zero
  10812. integer.
  10813. If the value isn't found in this set, then this will look for it in a fallback
  10814. property set (if you've specified one with the setFallbackPropertySet() method),
  10815. and if it can't find one there, it'll return the default value passed-in.
  10816. @param keyName the name of the property to retrieve
  10817. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10818. */
  10819. bool getBoolValue (const String& keyName,
  10820. const bool defaultReturnValue = false) const noexcept;
  10821. /** Returns one of the properties as an XML element.
  10822. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  10823. key isn't found, or if the entry contains an string that isn't valid XML.
  10824. If the value isn't found in this set, then this will look for it in a fallback
  10825. property set (if you've specified one with the setFallbackPropertySet() method),
  10826. and if it can't find one there, it'll return the default value passed-in.
  10827. @param keyName the name of the property to retrieve
  10828. */
  10829. XmlElement* getXmlValue (const String& keyName) const;
  10830. /** Sets a named property.
  10831. @param keyName the name of the property to set. (This mustn't be an empty string)
  10832. @param value the new value to set it to
  10833. */
  10834. void setValue (const String& keyName, const var& value);
  10835. /** Sets a named property to an XML element.
  10836. @param keyName the name of the property to set. (This mustn't be an empty string)
  10837. @param xml the new element to set it to. If this is zero, the value will be set to
  10838. an empty string
  10839. @see getXmlValue
  10840. */
  10841. void setValue (const String& keyName, const XmlElement* xml);
  10842. /** This copies all the values from a source PropertySet to this one.
  10843. This won't remove any existing settings, it just adds any that it finds in the source set.
  10844. */
  10845. void addAllPropertiesFrom (const PropertySet& source);
  10846. /** Deletes a property.
  10847. @param keyName the name of the property to delete. (This mustn't be an empty string)
  10848. */
  10849. void removeValue (const String& keyName);
  10850. /** Returns true if the properies include the given key. */
  10851. bool containsKey (const String& keyName) const noexcept;
  10852. /** Removes all values. */
  10853. void clear();
  10854. /** Returns the keys/value pair array containing all the properties. */
  10855. StringPairArray& getAllProperties() noexcept { return properties; }
  10856. /** Returns the lock used when reading or writing to this set */
  10857. const CriticalSection& getLock() const noexcept { return lock; }
  10858. /** Returns an XML element which encapsulates all the items in this property set.
  10859. The string parameter is the tag name that should be used for the node.
  10860. @see restoreFromXml
  10861. */
  10862. XmlElement* createXml (const String& nodeName) const;
  10863. /** Reloads a set of properties that were previously stored as XML.
  10864. The node passed in must have been created by the createXml() method.
  10865. @see createXml
  10866. */
  10867. void restoreFromXml (const XmlElement& xml);
  10868. /** Sets up a second PopertySet that will be used to look up any values that aren't
  10869. set in this one.
  10870. If you set this up to be a pointer to a second property set, then whenever one
  10871. of the getValue() methods fails to find an entry in this set, it will look up that
  10872. value in the fallback set, and if it finds it, it will return that.
  10873. Make sure that you don't delete the fallback set while it's still being used by
  10874. another set! To remove the fallback set, just call this method with a null pointer.
  10875. @see getFallbackPropertySet
  10876. */
  10877. void setFallbackPropertySet (PropertySet* fallbackProperties) noexcept;
  10878. /** Returns the fallback property set.
  10879. @see setFallbackPropertySet
  10880. */
  10881. PropertySet* getFallbackPropertySet() const noexcept { return fallbackProperties; }
  10882. protected:
  10883. /** Subclasses can override this to be told when one of the properies has been changed. */
  10884. virtual void propertyChanged();
  10885. private:
  10886. StringPairArray properties;
  10887. PropertySet* fallbackProperties;
  10888. CriticalSection lock;
  10889. bool ignoreCaseOfKeys;
  10890. JUCE_LEAK_DETECTOR (PropertySet);
  10891. };
  10892. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  10893. /*** End of inlined file: juce_PropertySet.h ***/
  10894. #endif
  10895. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10896. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  10897. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10898. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10899. /**
  10900. Holds a list of objects derived from ReferenceCountedObject.
  10901. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  10902. and takes care of incrementing and decrementing their ref counts when they
  10903. are added and removed from the array.
  10904. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  10905. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  10906. @see Array, OwnedArray, StringArray
  10907. */
  10908. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  10909. class ReferenceCountedArray
  10910. {
  10911. public:
  10912. typedef ReferenceCountedObjectPtr<ObjectClass> ObjectClassPtr;
  10913. /** Creates an empty array.
  10914. @see ReferenceCountedObject, Array, OwnedArray
  10915. */
  10916. ReferenceCountedArray() noexcept
  10917. : numUsed (0)
  10918. {
  10919. }
  10920. /** Creates a copy of another array */
  10921. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) noexcept
  10922. {
  10923. const ScopedLockType lock (other.getLock());
  10924. numUsed = other.numUsed;
  10925. data.setAllocatedSize (numUsed);
  10926. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  10927. for (int i = numUsed; --i >= 0;)
  10928. if (data.elements[i] != nullptr)
  10929. data.elements[i]->incReferenceCount();
  10930. }
  10931. /** Copies another array into this one.
  10932. Any existing objects in this array will first be released.
  10933. */
  10934. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) noexcept
  10935. {
  10936. if (this != &other)
  10937. {
  10938. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  10939. swapWithArray (otherCopy);
  10940. }
  10941. return *this;
  10942. }
  10943. /** Destructor.
  10944. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  10945. */
  10946. ~ReferenceCountedArray()
  10947. {
  10948. clear();
  10949. }
  10950. /** Removes all objects from the array.
  10951. Any objects in the array that are not referenced from elsewhere will be deleted.
  10952. */
  10953. void clear()
  10954. {
  10955. const ScopedLockType lock (getLock());
  10956. while (numUsed > 0)
  10957. if (data.elements [--numUsed] != nullptr)
  10958. data.elements [numUsed]->decReferenceCount();
  10959. jassert (numUsed == 0);
  10960. data.setAllocatedSize (0);
  10961. }
  10962. /** Returns the current number of objects in the array. */
  10963. inline int size() const noexcept
  10964. {
  10965. return numUsed;
  10966. }
  10967. /** Returns a pointer to the object at this index in the array.
  10968. If the index is out-of-range, this will return a null pointer, (and
  10969. it could be null anyway, because it's ok for the array to hold null
  10970. pointers as well as objects).
  10971. @see getUnchecked
  10972. */
  10973. inline const ObjectClassPtr operator[] (const int index) const noexcept
  10974. {
  10975. const ScopedLockType lock (getLock());
  10976. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  10977. : static_cast <ObjectClass*> (nullptr);
  10978. }
  10979. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  10980. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  10981. it can be used when you're sure the index if always going to be legal.
  10982. */
  10983. inline const ObjectClassPtr getUnchecked (const int index) const noexcept
  10984. {
  10985. const ScopedLockType lock (getLock());
  10986. jassert (isPositiveAndBelow (index, numUsed));
  10987. return data.elements [index];
  10988. }
  10989. /** Returns a pointer to the first object in the array.
  10990. This will return a null pointer if the array's empty.
  10991. @see getLast
  10992. */
  10993. inline const ObjectClassPtr getFirst() const noexcept
  10994. {
  10995. const ScopedLockType lock (getLock());
  10996. return numUsed > 0 ? data.elements [0]
  10997. : static_cast <ObjectClass*> (nullptr);
  10998. }
  10999. /** Returns a pointer to the last object in the array.
  11000. This will return a null pointer if the array's empty.
  11001. @see getFirst
  11002. */
  11003. inline const ObjectClassPtr getLast() const noexcept
  11004. {
  11005. const ScopedLockType lock (getLock());
  11006. return numUsed > 0 ? data.elements [numUsed - 1]
  11007. : static_cast <ObjectClass*> (nullptr);
  11008. }
  11009. /** Returns a pointer to the first element in the array.
  11010. This method is provided for compatibility with standard C++ iteration mechanisms.
  11011. */
  11012. inline ObjectClass** begin() const noexcept
  11013. {
  11014. return data.elements;
  11015. }
  11016. /** Returns a pointer to the element which follows the last element in the array.
  11017. This method is provided for compatibility with standard C++ iteration mechanisms.
  11018. */
  11019. inline ObjectClass** end() const noexcept
  11020. {
  11021. return data.elements + numUsed;
  11022. }
  11023. /** Finds the index of the first occurrence of an object in the array.
  11024. @param objectToLookFor the object to look for
  11025. @returns the index at which the object was found, or -1 if it's not found
  11026. */
  11027. int indexOf (const ObjectClass* const objectToLookFor) const noexcept
  11028. {
  11029. const ScopedLockType lock (getLock());
  11030. ObjectClass** e = data.elements.getData();
  11031. ObjectClass** const end_ = e + numUsed;
  11032. while (e != end_)
  11033. {
  11034. if (objectToLookFor == *e)
  11035. return static_cast <int> (e - data.elements.getData());
  11036. ++e;
  11037. }
  11038. return -1;
  11039. }
  11040. /** Returns true if the array contains a specified object.
  11041. @param objectToLookFor the object to look for
  11042. @returns true if the object is in the array
  11043. */
  11044. bool contains (const ObjectClass* const objectToLookFor) const noexcept
  11045. {
  11046. const ScopedLockType lock (getLock());
  11047. ObjectClass** e = data.elements.getData();
  11048. ObjectClass** const end_ = e + numUsed;
  11049. while (e != end_)
  11050. {
  11051. if (objectToLookFor == *e)
  11052. return true;
  11053. ++e;
  11054. }
  11055. return false;
  11056. }
  11057. /** Appends a new object to the end of the array.
  11058. This will increase the new object's reference count.
  11059. @param newObject the new object to add to the array
  11060. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  11061. */
  11062. void add (ObjectClass* const newObject) noexcept
  11063. {
  11064. const ScopedLockType lock (getLock());
  11065. data.ensureAllocatedSize (numUsed + 1);
  11066. data.elements [numUsed++] = newObject;
  11067. if (newObject != nullptr)
  11068. newObject->incReferenceCount();
  11069. }
  11070. /** Inserts a new object into the array at the given index.
  11071. If the index is less than 0 or greater than the size of the array, the
  11072. element will be added to the end of the array.
  11073. Otherwise, it will be inserted into the array, moving all the later elements
  11074. along to make room.
  11075. This will increase the new object's reference count.
  11076. @param indexToInsertAt the index at which the new element should be inserted
  11077. @param newObject the new object to add to the array
  11078. @see add, addSorted, addIfNotAlreadyThere, set
  11079. */
  11080. void insert (int indexToInsertAt,
  11081. ObjectClass* const newObject) noexcept
  11082. {
  11083. if (indexToInsertAt >= 0)
  11084. {
  11085. const ScopedLockType lock (getLock());
  11086. if (indexToInsertAt > numUsed)
  11087. indexToInsertAt = numUsed;
  11088. data.ensureAllocatedSize (numUsed + 1);
  11089. ObjectClass** const e = data.elements + indexToInsertAt;
  11090. const int numToMove = numUsed - indexToInsertAt;
  11091. if (numToMove > 0)
  11092. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  11093. *e = newObject;
  11094. if (newObject != nullptr)
  11095. newObject->incReferenceCount();
  11096. ++numUsed;
  11097. }
  11098. else
  11099. {
  11100. add (newObject);
  11101. }
  11102. }
  11103. /** Appends a new object at the end of the array as long as the array doesn't
  11104. already contain it.
  11105. If the array already contains a matching object, nothing will be done.
  11106. @param newObject the new object to add to the array
  11107. */
  11108. void addIfNotAlreadyThere (ObjectClass* const newObject) noexcept
  11109. {
  11110. const ScopedLockType lock (getLock());
  11111. if (! contains (newObject))
  11112. add (newObject);
  11113. }
  11114. /** Replaces an object in the array with a different one.
  11115. If the index is less than zero, this method does nothing.
  11116. If the index is beyond the end of the array, the new object is added to the end of the array.
  11117. The object being added has its reference count increased, and if it's replacing
  11118. another object, then that one has its reference count decreased, and may be deleted.
  11119. @param indexToChange the index whose value you want to change
  11120. @param newObject the new value to set for this index.
  11121. @see add, insert, remove
  11122. */
  11123. void set (const int indexToChange,
  11124. ObjectClass* const newObject)
  11125. {
  11126. if (indexToChange >= 0)
  11127. {
  11128. const ScopedLockType lock (getLock());
  11129. if (newObject != nullptr)
  11130. newObject->incReferenceCount();
  11131. if (indexToChange < numUsed)
  11132. {
  11133. if (data.elements [indexToChange] != nullptr)
  11134. data.elements [indexToChange]->decReferenceCount();
  11135. data.elements [indexToChange] = newObject;
  11136. }
  11137. else
  11138. {
  11139. data.ensureAllocatedSize (numUsed + 1);
  11140. data.elements [numUsed++] = newObject;
  11141. }
  11142. }
  11143. }
  11144. /** Adds elements from another array to the end of this array.
  11145. @param arrayToAddFrom the array from which to copy the elements
  11146. @param startIndex the first element of the other array to start copying from
  11147. @param numElementsToAdd how many elements to add from the other array. If this
  11148. value is negative or greater than the number of available elements,
  11149. all available elements will be copied.
  11150. @see add
  11151. */
  11152. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  11153. int startIndex = 0,
  11154. int numElementsToAdd = -1) noexcept
  11155. {
  11156. const ScopedLockType lock1 (arrayToAddFrom.getLock());
  11157. {
  11158. const ScopedLockType lock2 (getLock());
  11159. if (startIndex < 0)
  11160. {
  11161. jassertfalse;
  11162. startIndex = 0;
  11163. }
  11164. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  11165. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  11166. if (numElementsToAdd > 0)
  11167. {
  11168. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  11169. while (--numElementsToAdd >= 0)
  11170. add (arrayToAddFrom.getUnchecked (startIndex++));
  11171. }
  11172. }
  11173. }
  11174. /** Inserts a new object into the array assuming that the array is sorted.
  11175. This will use a comparator to find the position at which the new object
  11176. should go. If the array isn't sorted, the behaviour of this
  11177. method will be unpredictable.
  11178. @param comparator the comparator object to use to compare the elements - see the
  11179. sort() method for details about this object's form
  11180. @param newObject the new object to insert to the array
  11181. @returns the index at which the new object was added
  11182. @see add, sort
  11183. */
  11184. template <class ElementComparator>
  11185. int addSorted (ElementComparator& comparator, ObjectClass* newObject) noexcept
  11186. {
  11187. const ScopedLockType lock (getLock());
  11188. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  11189. insert (index, newObject);
  11190. return index;
  11191. }
  11192. /** Inserts or replaces an object in the array, assuming it is sorted.
  11193. This is similar to addSorted, but if a matching element already exists, then it will be
  11194. replaced by the new one, rather than the new one being added as well.
  11195. */
  11196. template <class ElementComparator>
  11197. void addOrReplaceSorted (ElementComparator& comparator,
  11198. ObjectClass* newObject) noexcept
  11199. {
  11200. const ScopedLockType lock (getLock());
  11201. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  11202. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  11203. set (index - 1, newObject); // replace an existing object that matches
  11204. else
  11205. insert (index, newObject); // no match, so insert the new one
  11206. }
  11207. /** Removes an object from the array.
  11208. This will remove the object at a given index and move back all the
  11209. subsequent objects to close the gap.
  11210. If the index passed in is out-of-range, nothing will happen.
  11211. The object that is removed will have its reference count decreased,
  11212. and may be deleted if not referenced from elsewhere.
  11213. @param indexToRemove the index of the element to remove
  11214. @see removeObject, removeRange
  11215. */
  11216. void remove (const int indexToRemove)
  11217. {
  11218. const ScopedLockType lock (getLock());
  11219. if (isPositiveAndBelow (indexToRemove, numUsed))
  11220. {
  11221. ObjectClass** const e = data.elements + indexToRemove;
  11222. if (*e != nullptr)
  11223. (*e)->decReferenceCount();
  11224. --numUsed;
  11225. const int numberToShift = numUsed - indexToRemove;
  11226. if (numberToShift > 0)
  11227. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  11228. if ((numUsed << 1) < data.numAllocated)
  11229. minimiseStorageOverheads();
  11230. }
  11231. }
  11232. /** Removes and returns an object from the array.
  11233. This will remove the object at a given index and return it, moving back all
  11234. the subsequent objects to close the gap. If the index passed in is out-of-range,
  11235. nothing will happen and a null pointer will be returned.
  11236. @param indexToRemove the index of the element to remove
  11237. @see remove, removeObject, removeRange
  11238. */
  11239. const ObjectClassPtr removeAndReturn (const int indexToRemove)
  11240. {
  11241. ObjectClassPtr removedItem;
  11242. const ScopedLockType lock (getLock());
  11243. if (isPositiveAndBelow (indexToRemove, numUsed))
  11244. {
  11245. ObjectClass** const e = data.elements + indexToRemove;
  11246. if (*e != nullptr)
  11247. {
  11248. removedItem = *e;
  11249. (*e)->decReferenceCount();
  11250. }
  11251. --numUsed;
  11252. const int numberToShift = numUsed - indexToRemove;
  11253. if (numberToShift > 0)
  11254. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  11255. if ((numUsed << 1) < data.numAllocated)
  11256. minimiseStorageOverheads();
  11257. }
  11258. return removedItem;
  11259. }
  11260. /** Removes the first occurrence of a specified object from the array.
  11261. If the item isn't found, no action is taken. If it is found, it is
  11262. removed and has its reference count decreased.
  11263. @param objectToRemove the object to try to remove
  11264. @see remove, removeRange
  11265. */
  11266. void removeObject (ObjectClass* const objectToRemove)
  11267. {
  11268. const ScopedLockType lock (getLock());
  11269. remove (indexOf (objectToRemove));
  11270. }
  11271. /** Removes a range of objects from the array.
  11272. This will remove a set of objects, starting from the given index,
  11273. and move any subsequent elements down to close the gap.
  11274. If the range extends beyond the bounds of the array, it will
  11275. be safely clipped to the size of the array.
  11276. The objects that are removed will have their reference counts decreased,
  11277. and may be deleted if not referenced from elsewhere.
  11278. @param startIndex the index of the first object to remove
  11279. @param numberToRemove how many objects should be removed
  11280. @see remove, removeObject
  11281. */
  11282. void removeRange (const int startIndex,
  11283. const int numberToRemove)
  11284. {
  11285. const ScopedLockType lock (getLock());
  11286. const int start = jlimit (0, numUsed, startIndex);
  11287. const int end_ = jlimit (0, numUsed, startIndex + numberToRemove);
  11288. if (end_ > start)
  11289. {
  11290. int i;
  11291. for (i = start; i < end_; ++i)
  11292. {
  11293. if (data.elements[i] != nullptr)
  11294. {
  11295. data.elements[i]->decReferenceCount();
  11296. data.elements[i] = nullptr; // (in case one of the destructors accesses this array and hits a dangling pointer)
  11297. }
  11298. }
  11299. const int rangeSize = end_ - start;
  11300. ObjectClass** e = data.elements + start;
  11301. i = numUsed - end_;
  11302. numUsed -= rangeSize;
  11303. while (--i >= 0)
  11304. {
  11305. *e = e [rangeSize];
  11306. ++e;
  11307. }
  11308. if ((numUsed << 1) < data.numAllocated)
  11309. minimiseStorageOverheads();
  11310. }
  11311. }
  11312. /** Removes the last n objects from the array.
  11313. The objects that are removed will have their reference counts decreased,
  11314. and may be deleted if not referenced from elsewhere.
  11315. @param howManyToRemove how many objects to remove from the end of the array
  11316. @see remove, removeObject, removeRange
  11317. */
  11318. void removeLast (int howManyToRemove = 1)
  11319. {
  11320. const ScopedLockType lock (getLock());
  11321. if (howManyToRemove > numUsed)
  11322. howManyToRemove = numUsed;
  11323. while (--howManyToRemove >= 0)
  11324. remove (numUsed - 1);
  11325. }
  11326. /** Swaps a pair of objects in the array.
  11327. If either of the indexes passed in is out-of-range, nothing will happen,
  11328. otherwise the two objects at these positions will be exchanged.
  11329. */
  11330. void swap (const int index1,
  11331. const int index2) noexcept
  11332. {
  11333. const ScopedLockType lock (getLock());
  11334. if (isPositiveAndBelow (index1, numUsed)
  11335. && isPositiveAndBelow (index2, numUsed))
  11336. {
  11337. std::swap (data.elements [index1],
  11338. data.elements [index2]);
  11339. }
  11340. }
  11341. /** Moves one of the objects to a different position.
  11342. This will move the object to a specified index, shuffling along
  11343. any intervening elements as required.
  11344. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  11345. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  11346. @param currentIndex the index of the object to be moved. If this isn't a
  11347. valid index, then nothing will be done
  11348. @param newIndex the index at which you'd like this object to end up. If this
  11349. is less than zero, it will be moved to the end of the array
  11350. */
  11351. void move (const int currentIndex,
  11352. int newIndex) noexcept
  11353. {
  11354. if (currentIndex != newIndex)
  11355. {
  11356. const ScopedLockType lock (getLock());
  11357. if (isPositiveAndBelow (currentIndex, numUsed))
  11358. {
  11359. if (! isPositiveAndBelow (newIndex, numUsed))
  11360. newIndex = numUsed - 1;
  11361. ObjectClass* const value = data.elements [currentIndex];
  11362. if (newIndex > currentIndex)
  11363. {
  11364. memmove (data.elements + currentIndex,
  11365. data.elements + currentIndex + 1,
  11366. (newIndex - currentIndex) * sizeof (ObjectClass*));
  11367. }
  11368. else
  11369. {
  11370. memmove (data.elements + newIndex + 1,
  11371. data.elements + newIndex,
  11372. (currentIndex - newIndex) * sizeof (ObjectClass*));
  11373. }
  11374. data.elements [newIndex] = value;
  11375. }
  11376. }
  11377. }
  11378. /** This swaps the contents of this array with those of another array.
  11379. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  11380. because it just swaps their internal pointers.
  11381. */
  11382. void swapWithArray (ReferenceCountedArray& otherArray) noexcept
  11383. {
  11384. const ScopedLockType lock1 (getLock());
  11385. const ScopedLockType lock2 (otherArray.getLock());
  11386. data.swapWith (otherArray.data);
  11387. std::swap (numUsed, otherArray.numUsed);
  11388. }
  11389. /** Compares this array to another one.
  11390. @returns true only if the other array contains the same objects in the same order
  11391. */
  11392. bool operator== (const ReferenceCountedArray& other) const noexcept
  11393. {
  11394. const ScopedLockType lock2 (other.getLock());
  11395. const ScopedLockType lock1 (getLock());
  11396. if (numUsed != other.numUsed)
  11397. return false;
  11398. for (int i = numUsed; --i >= 0;)
  11399. if (data.elements [i] != other.data.elements [i])
  11400. return false;
  11401. return true;
  11402. }
  11403. /** Compares this array to another one.
  11404. @see operator==
  11405. */
  11406. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const noexcept
  11407. {
  11408. return ! operator== (other);
  11409. }
  11410. /** Sorts the elements in the array.
  11411. This will use a comparator object to sort the elements into order. The object
  11412. passed must have a method of the form:
  11413. @code
  11414. int compareElements (ElementType first, ElementType second);
  11415. @endcode
  11416. ..and this method must return:
  11417. - a value of < 0 if the first comes before the second
  11418. - a value of 0 if the two objects are equivalent
  11419. - a value of > 0 if the second comes before the first
  11420. To improve performance, the compareElements() method can be declared as static or const.
  11421. @param comparator the comparator to use for comparing elements.
  11422. @param retainOrderOfEquivalentItems if this is true, then items
  11423. which the comparator says are equivalent will be
  11424. kept in the order in which they currently appear
  11425. in the array. This is slower to perform, but may
  11426. be important in some cases. If it's false, a faster
  11427. algorithm is used, but equivalent elements may be
  11428. rearranged.
  11429. @see sortArray
  11430. */
  11431. template <class ElementComparator>
  11432. void sort (ElementComparator& comparator,
  11433. const bool retainOrderOfEquivalentItems = false) const noexcept
  11434. {
  11435. (void) comparator; // if you pass in an object with a static compareElements() method, this
  11436. // avoids getting warning messages about the parameter being unused
  11437. const ScopedLockType lock (getLock());
  11438. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  11439. }
  11440. /** Reduces the amount of storage being used by the array.
  11441. Arrays typically allocate slightly more storage than they need, and after
  11442. removing elements, they may have quite a lot of unused space allocated.
  11443. This method will reduce the amount of allocated storage to a minimum.
  11444. */
  11445. void minimiseStorageOverheads() noexcept
  11446. {
  11447. const ScopedLockType lock (getLock());
  11448. data.shrinkToNoMoreThan (numUsed);
  11449. }
  11450. /** Returns the CriticalSection that locks this array.
  11451. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  11452. an object of ScopedLockType as an RAII lock for it.
  11453. */
  11454. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  11455. /** Returns the type of scoped lock to use for locking this array */
  11456. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  11457. private:
  11458. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  11459. int numUsed;
  11460. };
  11461. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  11462. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  11463. #endif
  11464. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11465. /*** Start of inlined file: juce_ScopedValueSetter.h ***/
  11466. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11467. #define __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11468. /**
  11469. Helper class providing an RAII-based mechanism for temporarily setting and
  11470. then re-setting a value.
  11471. E.g. @code
  11472. int x = 1;
  11473. {
  11474. ScopedValueSetter setter (x, 2);
  11475. // x is now 2
  11476. }
  11477. // x is now 1 again
  11478. {
  11479. ScopedValueSetter setter (x, 3, 4);
  11480. // x is now 3
  11481. }
  11482. // x is now 4
  11483. @endcode
  11484. */
  11485. template <typename ValueType>
  11486. class ScopedValueSetter
  11487. {
  11488. public:
  11489. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  11490. given new value, and will then reset it to its original value when this object is deleted.
  11491. */
  11492. ScopedValueSetter (ValueType& valueToSet,
  11493. const ValueType& newValue)
  11494. : value (valueToSet),
  11495. originalValue (valueToSet)
  11496. {
  11497. valueToSet = newValue;
  11498. }
  11499. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  11500. given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
  11501. */
  11502. ScopedValueSetter (ValueType& valueToSet,
  11503. const ValueType& newValue,
  11504. const ValueType& valueWhenDeleted)
  11505. : value (valueToSet),
  11506. originalValue (valueWhenDeleted)
  11507. {
  11508. valueToSet = newValue;
  11509. }
  11510. ~ScopedValueSetter()
  11511. {
  11512. value = originalValue;
  11513. }
  11514. private:
  11515. ValueType& value;
  11516. const ValueType originalValue;
  11517. JUCE_DECLARE_NON_COPYABLE (ScopedValueSetter);
  11518. };
  11519. #endif // __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11520. /*** End of inlined file: juce_ScopedValueSetter.h ***/
  11521. #endif
  11522. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  11523. /*** Start of inlined file: juce_SortedSet.h ***/
  11524. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  11525. #define __JUCE_SORTEDSET_JUCEHEADER__
  11526. #if JUCE_MSVC
  11527. #pragma warning (push)
  11528. #pragma warning (disable: 4512)
  11529. #endif
  11530. /**
  11531. Holds a set of unique primitive objects, such as ints or doubles.
  11532. A set can only hold one item with a given value, so if for example it's a
  11533. set of integers, attempting to add the same integer twice will do nothing
  11534. the second time.
  11535. Internally, the list of items is kept sorted (which means that whatever
  11536. kind of primitive type is used must support the ==, <, >, <= and >= operators
  11537. to determine the order), and searching the set for known values is very fast
  11538. because it uses a binary-chop method.
  11539. Note that if you're using a class or struct as the element type, it must be
  11540. capable of being copied or moved with a straightforward memcpy, rather than
  11541. needing construction and destruction code.
  11542. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  11543. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  11544. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  11545. */
  11546. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  11547. class SortedSet
  11548. {
  11549. public:
  11550. /** Creates an empty set. */
  11551. SortedSet() noexcept
  11552. : numUsed (0)
  11553. {
  11554. }
  11555. /** Creates a copy of another set.
  11556. @param other the set to copy
  11557. */
  11558. SortedSet (const SortedSet& other) noexcept
  11559. {
  11560. const ScopedLockType lock (other.getLock());
  11561. numUsed = other.numUsed;
  11562. data.setAllocatedSize (other.numUsed);
  11563. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  11564. }
  11565. /** Destructor. */
  11566. ~SortedSet() noexcept
  11567. {
  11568. }
  11569. /** Copies another set over this one.
  11570. @param other the set to copy
  11571. */
  11572. SortedSet& operator= (const SortedSet& other) noexcept
  11573. {
  11574. if (this != &other)
  11575. {
  11576. const ScopedLockType lock1 (other.getLock());
  11577. const ScopedLockType lock2 (getLock());
  11578. data.ensureAllocatedSize (other.size());
  11579. numUsed = other.numUsed;
  11580. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  11581. minimiseStorageOverheads();
  11582. }
  11583. return *this;
  11584. }
  11585. /** Compares this set to another one.
  11586. Two sets are considered equal if they both contain the same set of
  11587. elements.
  11588. @param other the other set to compare with
  11589. */
  11590. bool operator== (const SortedSet<ElementType>& other) const noexcept
  11591. {
  11592. const ScopedLockType lock (getLock());
  11593. if (numUsed != other.numUsed)
  11594. return false;
  11595. for (int i = numUsed; --i >= 0;)
  11596. if (! (data.elements[i] == other.data.elements[i]))
  11597. return false;
  11598. return true;
  11599. }
  11600. /** Compares this set to another one.
  11601. Two sets are considered equal if they both contain the same set of
  11602. elements.
  11603. @param other the other set to compare with
  11604. */
  11605. bool operator!= (const SortedSet<ElementType>& other) const noexcept
  11606. {
  11607. return ! operator== (other);
  11608. }
  11609. /** Removes all elements from the set.
  11610. This will remove all the elements, and free any storage that the set is
  11611. using. To clear it without freeing the storage, use the clearQuick()
  11612. method instead.
  11613. @see clearQuick
  11614. */
  11615. void clear() noexcept
  11616. {
  11617. const ScopedLockType lock (getLock());
  11618. data.setAllocatedSize (0);
  11619. numUsed = 0;
  11620. }
  11621. /** Removes all elements from the set without freeing the array's allocated storage.
  11622. @see clear
  11623. */
  11624. void clearQuick() noexcept
  11625. {
  11626. const ScopedLockType lock (getLock());
  11627. numUsed = 0;
  11628. }
  11629. /** Returns the current number of elements in the set.
  11630. */
  11631. inline int size() const noexcept
  11632. {
  11633. return numUsed;
  11634. }
  11635. /** Returns one of the elements in the set.
  11636. If the index passed in is beyond the range of valid elements, this
  11637. will return zero.
  11638. If you're certain that the index will always be a valid element, you
  11639. can call getUnchecked() instead, which is faster.
  11640. @param index the index of the element being requested (0 is the first element in the set)
  11641. @see getUnchecked, getFirst, getLast
  11642. */
  11643. inline ElementType operator[] (const int index) const noexcept
  11644. {
  11645. const ScopedLockType lock (getLock());
  11646. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  11647. : ElementType();
  11648. }
  11649. /** Returns one of the elements in the set, without checking the index passed in.
  11650. Unlike the operator[] method, this will try to return an element without
  11651. checking that the index is within the bounds of the set, so should only
  11652. be used when you're confident that it will always be a valid index.
  11653. @param index the index of the element being requested (0 is the first element in the set)
  11654. @see operator[], getFirst, getLast
  11655. */
  11656. inline ElementType getUnchecked (const int index) const noexcept
  11657. {
  11658. const ScopedLockType lock (getLock());
  11659. jassert (isPositiveAndBelow (index, numUsed));
  11660. return data.elements [index];
  11661. }
  11662. /** Returns a direct reference to one of the elements in the set, without checking the index passed in.
  11663. This is like getUnchecked, but returns a direct reference to the element, so that
  11664. you can alter it directly. Obviously this can be dangerous, so only use it when
  11665. absolutely necessary.
  11666. @param index the index of the element being requested (0 is the first element in the array)
  11667. */
  11668. inline ElementType& getReference (const int index) const noexcept
  11669. {
  11670. const ScopedLockType lock (getLock());
  11671. jassert (isPositiveAndBelow (index, numUsed));
  11672. return data.elements [index];
  11673. }
  11674. /** Returns the first element in the set, or 0 if the set is empty.
  11675. @see operator[], getUnchecked, getLast
  11676. */
  11677. inline ElementType getFirst() const noexcept
  11678. {
  11679. const ScopedLockType lock (getLock());
  11680. return numUsed > 0 ? data.elements [0] : ElementType();
  11681. }
  11682. /** Returns the last element in the set, or 0 if the set is empty.
  11683. @see operator[], getUnchecked, getFirst
  11684. */
  11685. inline ElementType getLast() const noexcept
  11686. {
  11687. const ScopedLockType lock (getLock());
  11688. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  11689. }
  11690. /** Returns a pointer to the first element in the set.
  11691. This method is provided for compatibility with standard C++ iteration mechanisms.
  11692. */
  11693. inline ElementType* begin() const noexcept
  11694. {
  11695. return data.elements;
  11696. }
  11697. /** Returns a pointer to the element which follows the last element in the set.
  11698. This method is provided for compatibility with standard C++ iteration mechanisms.
  11699. */
  11700. inline ElementType* end() const noexcept
  11701. {
  11702. return data.elements + numUsed;
  11703. }
  11704. /** Finds the index of the first element which matches the value passed in.
  11705. This will search the set for the given object, and return the index
  11706. of its first occurrence. If the object isn't found, the method will return -1.
  11707. @param elementToLookFor the value or object to look for
  11708. @returns the index of the object, or -1 if it's not found
  11709. */
  11710. int indexOf (const ElementType elementToLookFor) const noexcept
  11711. {
  11712. const ScopedLockType lock (getLock());
  11713. int start = 0;
  11714. int end_ = numUsed;
  11715. for (;;)
  11716. {
  11717. if (start >= end_)
  11718. {
  11719. return -1;
  11720. }
  11721. else if (elementToLookFor == data.elements [start])
  11722. {
  11723. return start;
  11724. }
  11725. else
  11726. {
  11727. const int halfway = (start + end_) >> 1;
  11728. if (halfway == start)
  11729. return -1;
  11730. else if (elementToLookFor < data.elements [halfway])
  11731. end_ = halfway;
  11732. else
  11733. start = halfway;
  11734. }
  11735. }
  11736. }
  11737. /** Returns true if the set contains at least one occurrence of an object.
  11738. @param elementToLookFor the value or object to look for
  11739. @returns true if the item is found
  11740. */
  11741. bool contains (const ElementType elementToLookFor) const noexcept
  11742. {
  11743. const ScopedLockType lock (getLock());
  11744. int start = 0;
  11745. int end_ = numUsed;
  11746. for (;;)
  11747. {
  11748. if (start >= end_)
  11749. {
  11750. return false;
  11751. }
  11752. else if (elementToLookFor == data.elements [start])
  11753. {
  11754. return true;
  11755. }
  11756. else
  11757. {
  11758. const int halfway = (start + end_) >> 1;
  11759. if (halfway == start)
  11760. return false;
  11761. else if (elementToLookFor < data.elements [halfway])
  11762. end_ = halfway;
  11763. else
  11764. start = halfway;
  11765. }
  11766. }
  11767. }
  11768. /** Adds a new element to the set, (as long as it's not already in there).
  11769. @param newElement the new object to add to the set
  11770. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  11771. */
  11772. void add (const ElementType newElement) noexcept
  11773. {
  11774. const ScopedLockType lock (getLock());
  11775. int start = 0;
  11776. int end_ = numUsed;
  11777. for (;;)
  11778. {
  11779. if (start >= end_)
  11780. {
  11781. jassert (start <= end_);
  11782. insertInternal (start, newElement);
  11783. break;
  11784. }
  11785. else if (newElement == data.elements [start])
  11786. {
  11787. break;
  11788. }
  11789. else
  11790. {
  11791. const int halfway = (start + end_) >> 1;
  11792. if (halfway == start)
  11793. {
  11794. if (newElement < data.elements [halfway])
  11795. insertInternal (start, newElement);
  11796. else
  11797. insertInternal (start + 1, newElement);
  11798. break;
  11799. }
  11800. else if (newElement < data.elements [halfway])
  11801. end_ = halfway;
  11802. else
  11803. start = halfway;
  11804. }
  11805. }
  11806. }
  11807. /** Adds elements from an array to this set.
  11808. @param elementsToAdd the array of elements to add
  11809. @param numElementsToAdd how many elements are in this other array
  11810. @see add
  11811. */
  11812. void addArray (const ElementType* elementsToAdd,
  11813. int numElementsToAdd) noexcept
  11814. {
  11815. const ScopedLockType lock (getLock());
  11816. while (--numElementsToAdd >= 0)
  11817. add (*elementsToAdd++);
  11818. }
  11819. /** Adds elements from another set to this one.
  11820. @param setToAddFrom the set from which to copy the elements
  11821. @param startIndex the first element of the other set to start copying from
  11822. @param numElementsToAdd how many elements to add from the other set. If this
  11823. value is negative or greater than the number of available elements,
  11824. all available elements will be copied.
  11825. @see add
  11826. */
  11827. template <class OtherSetType>
  11828. void addSet (const OtherSetType& setToAddFrom,
  11829. int startIndex = 0,
  11830. int numElementsToAdd = -1) noexcept
  11831. {
  11832. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  11833. {
  11834. const ScopedLockType lock2 (getLock());
  11835. jassert (this != &setToAddFrom);
  11836. if (this != &setToAddFrom)
  11837. {
  11838. if (startIndex < 0)
  11839. {
  11840. jassertfalse;
  11841. startIndex = 0;
  11842. }
  11843. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  11844. numElementsToAdd = setToAddFrom.size() - startIndex;
  11845. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  11846. }
  11847. }
  11848. }
  11849. /** Removes an element from the set.
  11850. This will remove the element at a given index.
  11851. If the index passed in is out-of-range, nothing will happen.
  11852. @param indexToRemove the index of the element to remove
  11853. @returns the element that has been removed
  11854. @see removeValue, removeRange
  11855. */
  11856. ElementType remove (const int indexToRemove) noexcept
  11857. {
  11858. const ScopedLockType lock (getLock());
  11859. if (isPositiveAndBelow (indexToRemove, numUsed))
  11860. {
  11861. --numUsed;
  11862. ElementType* const e = data.elements + indexToRemove;
  11863. ElementType const removed = *e;
  11864. const int numberToShift = numUsed - indexToRemove;
  11865. if (numberToShift > 0)
  11866. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  11867. if ((numUsed << 1) < data.numAllocated)
  11868. minimiseStorageOverheads();
  11869. return removed;
  11870. }
  11871. return ElementType();
  11872. }
  11873. /** Removes an item from the set.
  11874. This will remove the given element from the set, if it's there.
  11875. @param valueToRemove the object to try to remove
  11876. @see remove, removeRange
  11877. */
  11878. void removeValue (const ElementType valueToRemove) noexcept
  11879. {
  11880. const ScopedLockType lock (getLock());
  11881. remove (indexOf (valueToRemove));
  11882. }
  11883. /** Removes any elements which are also in another set.
  11884. @param otherSet the other set in which to look for elements to remove
  11885. @see removeValuesNotIn, remove, removeValue, removeRange
  11886. */
  11887. template <class OtherSetType>
  11888. void removeValuesIn (const OtherSetType& otherSet) noexcept
  11889. {
  11890. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11891. const ScopedLockType lock2 (getLock());
  11892. if (this == &otherSet)
  11893. {
  11894. clear();
  11895. }
  11896. else
  11897. {
  11898. if (otherSet.size() > 0)
  11899. {
  11900. for (int i = numUsed; --i >= 0;)
  11901. if (otherSet.contains (data.elements [i]))
  11902. remove (i);
  11903. }
  11904. }
  11905. }
  11906. /** Removes any elements which are not found in another set.
  11907. Only elements which occur in this other set will be retained.
  11908. @param otherSet the set in which to look for elements NOT to remove
  11909. @see removeValuesIn, remove, removeValue, removeRange
  11910. */
  11911. template <class OtherSetType>
  11912. void removeValuesNotIn (const OtherSetType& otherSet) noexcept
  11913. {
  11914. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11915. const ScopedLockType lock2 (getLock());
  11916. if (this != &otherSet)
  11917. {
  11918. if (otherSet.size() <= 0)
  11919. {
  11920. clear();
  11921. }
  11922. else
  11923. {
  11924. for (int i = numUsed; --i >= 0;)
  11925. if (! otherSet.contains (data.elements [i]))
  11926. remove (i);
  11927. }
  11928. }
  11929. }
  11930. /** Reduces the amount of storage being used by the set.
  11931. Sets typically allocate slightly more storage than they need, and after
  11932. removing elements, they may have quite a lot of unused space allocated.
  11933. This method will reduce the amount of allocated storage to a minimum.
  11934. */
  11935. void minimiseStorageOverheads() noexcept
  11936. {
  11937. const ScopedLockType lock (getLock());
  11938. data.shrinkToNoMoreThan (numUsed);
  11939. }
  11940. /** Increases the set's internal storage to hold a minimum number of elements.
  11941. Calling this before adding a large known number of elements means that
  11942. the set won't have to keep dynamically resizing itself as the elements
  11943. are added, and it'll therefore be more efficient.
  11944. */
  11945. void ensureStorageAllocated (const int minNumElements)
  11946. {
  11947. const ScopedLockType lock (getLock());
  11948. data.ensureAllocatedSize (minNumElements);
  11949. }
  11950. /** Returns the CriticalSection that locks this array.
  11951. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  11952. an object of ScopedLockType as an RAII lock for it.
  11953. */
  11954. inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data; }
  11955. /** Returns the type of scoped lock to use for locking this array */
  11956. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  11957. private:
  11958. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  11959. int numUsed;
  11960. void insertInternal (const int indexToInsertAt, const ElementType newElement) noexcept
  11961. {
  11962. data.ensureAllocatedSize (numUsed + 1);
  11963. ElementType* const insertPos = data.elements + indexToInsertAt;
  11964. const int numberToMove = numUsed - indexToInsertAt;
  11965. if (numberToMove > 0)
  11966. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  11967. *insertPos = newElement;
  11968. ++numUsed;
  11969. }
  11970. };
  11971. #if JUCE_MSVC
  11972. #pragma warning (pop)
  11973. #endif
  11974. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  11975. /*** End of inlined file: juce_SortedSet.h ***/
  11976. #endif
  11977. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11978. /*** Start of inlined file: juce_SparseSet.h ***/
  11979. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11980. #define __JUCE_SPARSESET_JUCEHEADER__
  11981. /*** Start of inlined file: juce_Range.h ***/
  11982. #ifndef __JUCE_RANGE_JUCEHEADER__
  11983. #define __JUCE_RANGE_JUCEHEADER__
  11984. /** A general-purpose range object, that simply represents any linear range with
  11985. a start and end point.
  11986. The templated parameter is expected to be a primitive integer or floating point
  11987. type, though class types could also be used if they behave in a number-like way.
  11988. */
  11989. template <typename ValueType>
  11990. class Range
  11991. {
  11992. public:
  11993. /** Constructs an empty range. */
  11994. Range() noexcept
  11995. : start (ValueType()), end (ValueType())
  11996. {
  11997. }
  11998. /** Constructs a range with given start and end values. */
  11999. Range (const ValueType start_, const ValueType end_) noexcept
  12000. : start (start_), end (jmax (start_, end_))
  12001. {
  12002. }
  12003. /** Constructs a copy of another range. */
  12004. Range (const Range& other) noexcept
  12005. : start (other.start), end (other.end)
  12006. {
  12007. }
  12008. /** Copies another range object. */
  12009. Range& operator= (const Range& other) noexcept
  12010. {
  12011. start = other.start;
  12012. end = other.end;
  12013. return *this;
  12014. }
  12015. /** Destructor. */
  12016. ~Range() noexcept
  12017. {
  12018. }
  12019. /** Returns the range that lies between two positions (in either order). */
  12020. static Range between (const ValueType position1, const ValueType position2) noexcept
  12021. {
  12022. return (position1 < position2) ? Range (position1, position2)
  12023. : Range (position2, position1);
  12024. }
  12025. /** Returns a range with the specified start position and a length of zero. */
  12026. static Range emptyRange (const ValueType start) noexcept
  12027. {
  12028. return Range (start, start);
  12029. }
  12030. /** Returns the start of the range. */
  12031. inline ValueType getStart() const noexcept { return start; }
  12032. /** Returns the length of the range. */
  12033. inline ValueType getLength() const noexcept { return end - start; }
  12034. /** Returns the end of the range. */
  12035. inline ValueType getEnd() const noexcept { return end; }
  12036. /** Returns true if the range has a length of zero. */
  12037. inline bool isEmpty() const noexcept { return start == end; }
  12038. /** Changes the start position of the range, leaving the end position unchanged.
  12039. If the new start position is higher than the current end of the range, the end point
  12040. will be pushed along to equal it, leaving an empty range at the new position.
  12041. */
  12042. void setStart (const ValueType newStart) noexcept
  12043. {
  12044. start = newStart;
  12045. if (end < newStart)
  12046. end = newStart;
  12047. }
  12048. /** Returns a range with the same end as this one, but a different start.
  12049. If the new start position is higher than the current end of the range, the end point
  12050. will be pushed along to equal it, returning an empty range at the new position.
  12051. */
  12052. Range withStart (const ValueType newStart) const noexcept
  12053. {
  12054. return Range (newStart, jmax (newStart, end));
  12055. }
  12056. /** Returns a range with the same length as this one, but moved to have the given start position. */
  12057. Range movedToStartAt (const ValueType newStart) const noexcept
  12058. {
  12059. return Range (newStart, end + (newStart - start));
  12060. }
  12061. /** Changes the end position of the range, leaving the start unchanged.
  12062. If the new end position is below the current start of the range, the start point
  12063. will be pushed back to equal the new end point.
  12064. */
  12065. void setEnd (const ValueType newEnd) noexcept
  12066. {
  12067. end = newEnd;
  12068. if (newEnd < start)
  12069. start = newEnd;
  12070. }
  12071. /** Returns a range with the same start position as this one, but a different end.
  12072. If the new end position is below the current start of the range, the start point
  12073. will be pushed back to equal the new end point.
  12074. */
  12075. Range withEnd (const ValueType newEnd) const noexcept
  12076. {
  12077. return Range (jmin (start, newEnd), newEnd);
  12078. }
  12079. /** Returns a range with the same length as this one, but moved to have the given start position. */
  12080. Range movedToEndAt (const ValueType newEnd) const noexcept
  12081. {
  12082. return Range (start + (newEnd - end), newEnd);
  12083. }
  12084. /** Changes the length of the range.
  12085. Lengths less than zero are treated as zero.
  12086. */
  12087. void setLength (const ValueType newLength) noexcept
  12088. {
  12089. end = start + jmax (ValueType(), newLength);
  12090. }
  12091. /** Returns a range with the same start as this one, but a different length.
  12092. Lengths less than zero are treated as zero.
  12093. */
  12094. Range withLength (const ValueType newLength) const noexcept
  12095. {
  12096. return Range (start, start + newLength);
  12097. }
  12098. /** Adds an amount to the start and end of the range. */
  12099. inline const Range& operator+= (const ValueType amountToAdd) noexcept
  12100. {
  12101. start += amountToAdd;
  12102. end += amountToAdd;
  12103. return *this;
  12104. }
  12105. /** Subtracts an amount from the start and end of the range. */
  12106. inline const Range& operator-= (const ValueType amountToSubtract) noexcept
  12107. {
  12108. start -= amountToSubtract;
  12109. end -= amountToSubtract;
  12110. return *this;
  12111. }
  12112. /** Returns a range that is equal to this one with an amount added to its
  12113. start and end.
  12114. */
  12115. Range operator+ (const ValueType amountToAdd) const noexcept
  12116. {
  12117. return Range (start + amountToAdd, end + amountToAdd);
  12118. }
  12119. /** Returns a range that is equal to this one with the specified amount
  12120. subtracted from its start and end. */
  12121. Range operator- (const ValueType amountToSubtract) const noexcept
  12122. {
  12123. return Range (start - amountToSubtract, end - amountToSubtract);
  12124. }
  12125. bool operator== (const Range& other) const noexcept { return start == other.start && end == other.end; }
  12126. bool operator!= (const Range& other) const noexcept { return start != other.start || end != other.end; }
  12127. /** Returns true if the given position lies inside this range. */
  12128. bool contains (const ValueType position) const noexcept
  12129. {
  12130. return start <= position && position < end;
  12131. }
  12132. /** Returns the nearest value to the one supplied, which lies within the range. */
  12133. ValueType clipValue (const ValueType value) const noexcept
  12134. {
  12135. return jlimit (start, end, value);
  12136. }
  12137. /** Returns true if the given range lies entirely inside this range. */
  12138. bool contains (const Range& other) const noexcept
  12139. {
  12140. return start <= other.start && end >= other.end;
  12141. }
  12142. /** Returns true if the given range intersects this one. */
  12143. bool intersects (const Range& other) const noexcept
  12144. {
  12145. return other.start < end && start < other.end;
  12146. }
  12147. /** Returns the range that is the intersection of the two ranges, or an empty range
  12148. with an undefined start position if they don't overlap. */
  12149. Range getIntersectionWith (const Range& other) const noexcept
  12150. {
  12151. return Range (jmax (start, other.start),
  12152. jmin (end, other.end));
  12153. }
  12154. /** Returns the smallest range that contains both this one and the other one. */
  12155. Range getUnionWith (const Range& other) const noexcept
  12156. {
  12157. return Range (jmin (start, other.start),
  12158. jmax (end, other.end));
  12159. }
  12160. /** Returns a given range, after moving it forwards or backwards to fit it
  12161. within this range.
  12162. If the supplied range has a greater length than this one, the return value
  12163. will be this range.
  12164. Otherwise, if the supplied range is smaller than this one, the return value
  12165. will be the new range, shifted forwards or backwards so that it doesn't extend
  12166. beyond this one, but keeping its original length.
  12167. */
  12168. Range constrainRange (const Range& rangeToConstrain) const noexcept
  12169. {
  12170. const ValueType otherLen = rangeToConstrain.getLength();
  12171. return getLength() <= otherLen
  12172. ? *this
  12173. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  12174. }
  12175. private:
  12176. ValueType start, end;
  12177. };
  12178. #endif // __JUCE_RANGE_JUCEHEADER__
  12179. /*** End of inlined file: juce_Range.h ***/
  12180. /**
  12181. Holds a set of primitive values, storing them as a set of ranges.
  12182. This container acts like an array, but can efficiently hold large continguous
  12183. ranges of values. It's quite a specialised class, mostly useful for things
  12184. like keeping the set of selected rows in a listbox.
  12185. The type used as a template paramter must be an integer type, such as int, short,
  12186. int64, etc.
  12187. */
  12188. template <class Type>
  12189. class SparseSet
  12190. {
  12191. public:
  12192. /** Creates a new empty set. */
  12193. SparseSet()
  12194. {
  12195. }
  12196. /** Creates a copy of another SparseSet. */
  12197. SparseSet (const SparseSet<Type>& other)
  12198. : values (other.values)
  12199. {
  12200. }
  12201. /** Clears the set. */
  12202. void clear()
  12203. {
  12204. values.clear();
  12205. }
  12206. /** Checks whether the set is empty.
  12207. This is much quicker than using (size() == 0).
  12208. */
  12209. bool isEmpty() const noexcept
  12210. {
  12211. return values.size() == 0;
  12212. }
  12213. /** Returns the number of values in the set.
  12214. Because of the way the data is stored, this method can take longer if there
  12215. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  12216. are any items.
  12217. */
  12218. Type size() const
  12219. {
  12220. Type total (0);
  12221. for (int i = 0; i < values.size(); i += 2)
  12222. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  12223. return total;
  12224. }
  12225. /** Returns one of the values in the set.
  12226. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  12227. @returns the value at this index, or 0 if it's out-of-range
  12228. */
  12229. Type operator[] (Type index) const
  12230. {
  12231. for (int i = 0; i < values.size(); i += 2)
  12232. {
  12233. const Type start (values.getUnchecked (i));
  12234. const Type len (values.getUnchecked (i + 1) - start);
  12235. if (index < len)
  12236. return start + index;
  12237. index -= len;
  12238. }
  12239. return Type();
  12240. }
  12241. /** Checks whether a particular value is in the set. */
  12242. bool contains (const Type valueToLookFor) const
  12243. {
  12244. for (int i = 0; i < values.size(); ++i)
  12245. if (valueToLookFor < values.getUnchecked(i))
  12246. return (i & 1) != 0;
  12247. return false;
  12248. }
  12249. /** Returns the number of contiguous blocks of values.
  12250. @see getRange
  12251. */
  12252. int getNumRanges() const noexcept
  12253. {
  12254. return values.size() >> 1;
  12255. }
  12256. /** Returns one of the contiguous ranges of values stored.
  12257. @param rangeIndex the index of the range to look up, between 0
  12258. and (getNumRanges() - 1)
  12259. @see getTotalRange
  12260. */
  12261. const Range<Type> getRange (const int rangeIndex) const
  12262. {
  12263. if (isPositiveAndBelow (rangeIndex, getNumRanges()))
  12264. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  12265. values.getUnchecked ((rangeIndex << 1) + 1));
  12266. else
  12267. return Range<Type>();
  12268. }
  12269. /** Returns the range between the lowest and highest values in the set.
  12270. @see getRange
  12271. */
  12272. const Range<Type> getTotalRange() const
  12273. {
  12274. if (values.size() > 0)
  12275. {
  12276. jassert ((values.size() & 1) == 0);
  12277. return Range<Type> (values.getUnchecked (0),
  12278. values.getUnchecked (values.size() - 1));
  12279. }
  12280. return Range<Type>();
  12281. }
  12282. /** Adds a range of contiguous values to the set.
  12283. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  12284. */
  12285. void addRange (const Range<Type>& range)
  12286. {
  12287. jassert (range.getLength() >= 0);
  12288. if (range.getLength() > 0)
  12289. {
  12290. removeRange (range);
  12291. values.addUsingDefaultSort (range.getStart());
  12292. values.addUsingDefaultSort (range.getEnd());
  12293. simplify();
  12294. }
  12295. }
  12296. /** Removes a range of values from the set.
  12297. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  12298. */
  12299. void removeRange (const Range<Type>& rangeToRemove)
  12300. {
  12301. jassert (rangeToRemove.getLength() >= 0);
  12302. if (rangeToRemove.getLength() > 0
  12303. && values.size() > 0
  12304. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  12305. && values.getUnchecked(0) < rangeToRemove.getEnd())
  12306. {
  12307. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  12308. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  12309. const bool onAtEnd = contains (lastValue);
  12310. for (int i = values.size(); --i >= 0;)
  12311. {
  12312. if (values.getUnchecked(i) <= lastValue)
  12313. {
  12314. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  12315. {
  12316. values.remove (i);
  12317. if (--i < 0)
  12318. break;
  12319. }
  12320. break;
  12321. }
  12322. }
  12323. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  12324. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  12325. simplify();
  12326. }
  12327. }
  12328. /** Does an XOR of the values in a given range. */
  12329. void invertRange (const Range<Type>& range)
  12330. {
  12331. SparseSet newItems;
  12332. newItems.addRange (range);
  12333. int i;
  12334. for (i = getNumRanges(); --i >= 0;)
  12335. newItems.removeRange (getRange (i));
  12336. removeRange (range);
  12337. for (i = newItems.getNumRanges(); --i >= 0;)
  12338. addRange (newItems.getRange(i));
  12339. }
  12340. /** Checks whether any part of a given range overlaps any part of this set. */
  12341. bool overlapsRange (const Range<Type>& range)
  12342. {
  12343. if (range.getLength() > 0)
  12344. {
  12345. for (int i = getNumRanges(); --i >= 0;)
  12346. {
  12347. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  12348. return false;
  12349. if (values.getUnchecked (i << 1) < range.getEnd())
  12350. return true;
  12351. }
  12352. }
  12353. return false;
  12354. }
  12355. /** Checks whether the whole of a given range is contained within this one. */
  12356. bool containsRange (const Range<Type>& range)
  12357. {
  12358. if (range.getLength() > 0)
  12359. {
  12360. for (int i = getNumRanges(); --i >= 0;)
  12361. {
  12362. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  12363. return false;
  12364. if (values.getUnchecked (i << 1) <= range.getStart()
  12365. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  12366. return true;
  12367. }
  12368. }
  12369. return false;
  12370. }
  12371. bool operator== (const SparseSet<Type>& other) noexcept
  12372. {
  12373. return values == other.values;
  12374. }
  12375. bool operator!= (const SparseSet<Type>& other) noexcept
  12376. {
  12377. return values != other.values;
  12378. }
  12379. private:
  12380. // alternating start/end values of ranges of values that are present.
  12381. Array<Type, DummyCriticalSection> values;
  12382. void simplify()
  12383. {
  12384. jassert ((values.size() & 1) == 0);
  12385. for (int i = values.size(); --i > 0;)
  12386. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  12387. values.removeRange (--i, 2);
  12388. }
  12389. };
  12390. #endif // __JUCE_SPARSESET_JUCEHEADER__
  12391. /*** End of inlined file: juce_SparseSet.h ***/
  12392. #endif
  12393. #ifndef __JUCE_VALUE_JUCEHEADER__
  12394. /*** Start of inlined file: juce_Value.h ***/
  12395. #ifndef __JUCE_VALUE_JUCEHEADER__
  12396. #define __JUCE_VALUE_JUCEHEADER__
  12397. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  12398. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  12399. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  12400. /*** Start of inlined file: juce_CallbackMessage.h ***/
  12401. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12402. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12403. /*** Start of inlined file: juce_Message.h ***/
  12404. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  12405. #define __JUCE_MESSAGE_JUCEHEADER__
  12406. class MessageListener;
  12407. class MessageManager;
  12408. /** The base class for objects that can be delivered to a MessageListener.
  12409. The simplest Message object contains a few integer and pointer parameters
  12410. that the user can set, and this is enough for a lot of purposes. For passing more
  12411. complex data, subclasses of Message can also be used.
  12412. @see MessageListener, MessageManager, ActionListener, ChangeListener
  12413. */
  12414. class JUCE_API Message : public ReferenceCountedObject
  12415. {
  12416. public:
  12417. /** Creates an uninitialised message.
  12418. The class's variables will also be left uninitialised.
  12419. */
  12420. Message() noexcept;
  12421. /** Creates a message object, filling in the member variables.
  12422. The corresponding public member variables will be set from the parameters
  12423. passed in.
  12424. */
  12425. Message (int intParameter1,
  12426. int intParameter2,
  12427. int intParameter3,
  12428. void* pointerParameter) noexcept;
  12429. /** Destructor. */
  12430. virtual ~Message();
  12431. // These values can be used for carrying simple data that the application needs to
  12432. // pass around. For more complex messages, just create a subclass.
  12433. int intParameter1; /**< user-defined integer value. */
  12434. int intParameter2; /**< user-defined integer value. */
  12435. int intParameter3; /**< user-defined integer value. */
  12436. void* pointerParameter; /**< user-defined pointer value. */
  12437. /** A typedef for pointers to messages. */
  12438. typedef ReferenceCountedObjectPtr <Message> Ptr;
  12439. private:
  12440. friend class MessageListener;
  12441. friend class MessageManager;
  12442. MessageListener* messageRecipient;
  12443. // Avoid the leak-detector because for plugins, the host can unload our DLL with undelivered
  12444. // messages still in the system event queue. These aren't harmful, but can cause annoying assertions.
  12445. JUCE_DECLARE_NON_COPYABLE (Message);
  12446. };
  12447. #endif // __JUCE_MESSAGE_JUCEHEADER__
  12448. /*** End of inlined file: juce_Message.h ***/
  12449. /**
  12450. A message that calls a custom function when it gets delivered.
  12451. You can use this class to fire off actions that you want to be performed later
  12452. on the message thread.
  12453. Unlike other Message objects, these don't get sent to a MessageListener, you
  12454. just call the post() method to send them, and when they arrive, your
  12455. messageCallback() method will automatically be invoked.
  12456. Always create an instance of a CallbackMessage on the heap, as it will be
  12457. deleted automatically after the message has been delivered.
  12458. @see MessageListener, MessageManager, ActionListener, ChangeListener
  12459. */
  12460. class JUCE_API CallbackMessage : public Message
  12461. {
  12462. public:
  12463. CallbackMessage() noexcept;
  12464. /** Destructor. */
  12465. ~CallbackMessage();
  12466. /** Called when the message is delivered.
  12467. You should implement this method and make it do whatever action you want
  12468. to perform.
  12469. Note that like all other messages, this object will be deleted immediately
  12470. after this method has been invoked.
  12471. */
  12472. virtual void messageCallback() = 0;
  12473. /** Instead of sending this message to a MessageListener, just call this method
  12474. to post it to the event queue.
  12475. After you've called this, this object will belong to the MessageManager,
  12476. which will delete it later. So make sure you don't delete the object yourself,
  12477. call post() more than once, or call post() on a stack-based obect!
  12478. */
  12479. void post();
  12480. private:
  12481. // Avoid the leak-detector because for plugins, the host can unload our DLL with undelivered
  12482. // messages still in the system event queue. These aren't harmful, but can cause annoying assertions.
  12483. JUCE_DECLARE_NON_COPYABLE (CallbackMessage);
  12484. };
  12485. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12486. /*** End of inlined file: juce_CallbackMessage.h ***/
  12487. /**
  12488. Has a callback method that is triggered asynchronously.
  12489. This object allows an asynchronous callback function to be triggered, for
  12490. tasks such as coalescing multiple updates into a single callback later on.
  12491. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  12492. message thread calling handleAsyncUpdate() as soon as it can.
  12493. */
  12494. class JUCE_API AsyncUpdater
  12495. {
  12496. public:
  12497. /** Creates an AsyncUpdater object. */
  12498. AsyncUpdater();
  12499. /** Destructor.
  12500. If there are any pending callbacks when the object is deleted, these are lost.
  12501. */
  12502. virtual ~AsyncUpdater();
  12503. /** Causes the callback to be triggered at a later time.
  12504. This method returns immediately, having made sure that a callback
  12505. to the handleAsyncUpdate() method will occur as soon as possible.
  12506. If an update callback is already pending but hasn't happened yet, calls
  12507. to this method will be ignored.
  12508. It's thread-safe to call this method from any number of threads without
  12509. needing to worry about locking.
  12510. */
  12511. void triggerAsyncUpdate();
  12512. /** This will stop any pending updates from happening.
  12513. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  12514. callback happens, this will cancel the handleAsyncUpdate() callback.
  12515. Note that this method simply cancels the next callback - if a callback is already
  12516. in progress on a different thread, this won't block until it finishes, so there's
  12517. no guarantee that the callback isn't still running when you return from
  12518. */
  12519. void cancelPendingUpdate() noexcept;
  12520. /** If an update has been triggered and is pending, this will invoke it
  12521. synchronously.
  12522. Use this as a kind of "flush" operation - if an update is pending, the
  12523. handleAsyncUpdate() method will be called immediately; if no update is
  12524. pending, then nothing will be done.
  12525. Because this may invoke the callback, this method must only be called on
  12526. the main event thread.
  12527. */
  12528. void handleUpdateNowIfNeeded();
  12529. /** Returns true if there's an update callback in the pipeline. */
  12530. bool isUpdatePending() const noexcept;
  12531. /** Called back to do whatever your class needs to do.
  12532. This method is called by the message thread at the next convenient time
  12533. after the triggerAsyncUpdate() method has been called.
  12534. */
  12535. virtual void handleAsyncUpdate() = 0;
  12536. private:
  12537. ReferenceCountedObjectPtr<CallbackMessage> message;
  12538. Atomic<int>& getDeliveryFlag() const noexcept;
  12539. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncUpdater);
  12540. };
  12541. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  12542. /*** End of inlined file: juce_AsyncUpdater.h ***/
  12543. /*** Start of inlined file: juce_ListenerList.h ***/
  12544. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  12545. #define __JUCE_LISTENERLIST_JUCEHEADER__
  12546. /**
  12547. Holds a set of objects and can invoke a member function callback on each object
  12548. in the set with a single call.
  12549. Use a ListenerList to manage a set of objects which need a callback, and you
  12550. can invoke a member function by simply calling call() or callChecked().
  12551. E.g.
  12552. @code
  12553. class MyListenerType
  12554. {
  12555. public:
  12556. void myCallbackMethod (int foo, bool bar);
  12557. };
  12558. ListenerList <MyListenerType> listeners;
  12559. listeners.add (someCallbackObjects...);
  12560. // This will invoke myCallbackMethod (1234, true) on each of the objects
  12561. // in the list...
  12562. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  12563. @endcode
  12564. If you add or remove listeners from the list during one of the callbacks - i.e. while
  12565. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  12566. will be mistakenly called after they've been removed, but it may mean that some of the
  12567. listeners could be called more than once, or not at all, depending on the list's order.
  12568. Sometimes, there's a chance that invoking one of the callbacks might result in the
  12569. list itself being deleted while it's still iterating - to survive this situation, you can
  12570. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  12571. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  12572. the list will check this after each callback to determine whether it should abort the
  12573. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  12574. which can be used to check when a Component has been deleted. See also
  12575. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  12576. */
  12577. template <class ListenerClass,
  12578. class ArrayType = Array <ListenerClass*> >
  12579. class ListenerList
  12580. {
  12581. // Horrible macros required to support VC6/7..
  12582. #ifndef DOXYGEN
  12583. #if JUCE_VC8_OR_EARLIER
  12584. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  12585. #define LL_PARAM(a) Q##a& param##a
  12586. #else
  12587. #define LL_TEMPLATE(a) typename P##a
  12588. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  12589. #endif
  12590. #endif
  12591. public:
  12592. /** Creates an empty list. */
  12593. ListenerList()
  12594. {
  12595. }
  12596. /** Destructor. */
  12597. ~ListenerList()
  12598. {
  12599. }
  12600. /** Adds a listener to the list.
  12601. A listener can only be added once, so if the listener is already in the list,
  12602. this method has no effect.
  12603. @see remove
  12604. */
  12605. void add (ListenerClass* const listenerToAdd)
  12606. {
  12607. // Listeners can't be null pointers!
  12608. jassert (listenerToAdd != nullptr);
  12609. if (listenerToAdd != nullptr)
  12610. listeners.addIfNotAlreadyThere (listenerToAdd);
  12611. }
  12612. /** Removes a listener from the list.
  12613. If the listener wasn't in the list, this has no effect.
  12614. */
  12615. void remove (ListenerClass* const listenerToRemove)
  12616. {
  12617. // Listeners can't be null pointers!
  12618. jassert (listenerToRemove != nullptr);
  12619. listeners.removeValue (listenerToRemove);
  12620. }
  12621. /** Returns the number of registered listeners. */
  12622. int size() const noexcept
  12623. {
  12624. return listeners.size();
  12625. }
  12626. /** Returns true if any listeners are registered. */
  12627. bool isEmpty() const noexcept
  12628. {
  12629. return listeners.size() == 0;
  12630. }
  12631. /** Clears the list. */
  12632. void clear()
  12633. {
  12634. listeners.clear();
  12635. }
  12636. /** Returns true if the specified listener has been added to the list. */
  12637. bool contains (ListenerClass* const listener) const noexcept
  12638. {
  12639. return listeners.contains (listener);
  12640. }
  12641. /** Calls a member function on each listener in the list, with no parameters. */
  12642. void call (void (ListenerClass::*callbackFunction) ())
  12643. {
  12644. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  12645. }
  12646. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  12647. See the class description for info about writing a bail-out checker. */
  12648. template <class BailOutCheckerType>
  12649. void callChecked (const BailOutCheckerType& bailOutChecker,
  12650. void (ListenerClass::*callbackFunction) ())
  12651. {
  12652. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12653. (iter.getListener()->*callbackFunction) ();
  12654. }
  12655. /** Calls a member function on each listener in the list, with 1 parameter. */
  12656. template <LL_TEMPLATE(1)>
  12657. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  12658. {
  12659. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12660. (iter.getListener()->*callbackFunction) (param1);
  12661. }
  12662. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  12663. See the class description for info about writing a bail-out checker. */
  12664. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  12665. void callChecked (const BailOutCheckerType& bailOutChecker,
  12666. void (ListenerClass::*callbackFunction) (P1),
  12667. LL_PARAM(1))
  12668. {
  12669. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12670. (iter.getListener()->*callbackFunction) (param1);
  12671. }
  12672. /** Calls a member function on each listener in the list, with 2 parameters. */
  12673. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  12674. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  12675. LL_PARAM(1), LL_PARAM(2))
  12676. {
  12677. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12678. (iter.getListener()->*callbackFunction) (param1, param2);
  12679. }
  12680. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  12681. See the class description for info about writing a bail-out checker. */
  12682. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  12683. void callChecked (const BailOutCheckerType& bailOutChecker,
  12684. void (ListenerClass::*callbackFunction) (P1, P2),
  12685. LL_PARAM(1), LL_PARAM(2))
  12686. {
  12687. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12688. (iter.getListener()->*callbackFunction) (param1, param2);
  12689. }
  12690. /** Calls a member function on each listener in the list, with 3 parameters. */
  12691. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  12692. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  12693. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  12694. {
  12695. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12696. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  12697. }
  12698. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  12699. See the class description for info about writing a bail-out checker. */
  12700. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  12701. void callChecked (const BailOutCheckerType& bailOutChecker,
  12702. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  12703. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  12704. {
  12705. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12706. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  12707. }
  12708. /** Calls a member function on each listener in the list, with 4 parameters. */
  12709. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  12710. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  12711. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  12712. {
  12713. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12714. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  12715. }
  12716. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  12717. See the class description for info about writing a bail-out checker. */
  12718. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  12719. void callChecked (const BailOutCheckerType& bailOutChecker,
  12720. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  12721. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  12722. {
  12723. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12724. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  12725. }
  12726. /** Calls a member function on each listener in the list, with 5 parameters. */
  12727. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  12728. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  12729. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  12730. {
  12731. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12732. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  12733. }
  12734. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  12735. See the class description for info about writing a bail-out checker. */
  12736. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  12737. void callChecked (const BailOutCheckerType& bailOutChecker,
  12738. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  12739. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  12740. {
  12741. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12742. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  12743. }
  12744. /** A dummy bail-out checker that always returns false.
  12745. See the ListenerList notes for more info about bail-out checkers.
  12746. */
  12747. class DummyBailOutChecker
  12748. {
  12749. public:
  12750. inline bool shouldBailOut() const noexcept { return false; }
  12751. };
  12752. /** Iterates the listeners in a ListenerList. */
  12753. template <class BailOutCheckerType, class ListType>
  12754. class Iterator
  12755. {
  12756. public:
  12757. Iterator (const ListType& list_)
  12758. : list (list_), index (list_.size())
  12759. {}
  12760. ~Iterator() {}
  12761. bool next()
  12762. {
  12763. if (index <= 0)
  12764. return false;
  12765. const int listSize = list.size();
  12766. if (--index < listSize)
  12767. return true;
  12768. index = listSize - 1;
  12769. return index >= 0;
  12770. }
  12771. bool next (const BailOutCheckerType& bailOutChecker)
  12772. {
  12773. return (! bailOutChecker.shouldBailOut()) && next();
  12774. }
  12775. typename ListType::ListenerType* getListener() const noexcept
  12776. {
  12777. return list.getListeners().getUnchecked (index);
  12778. }
  12779. private:
  12780. const ListType& list;
  12781. int index;
  12782. JUCE_DECLARE_NON_COPYABLE (Iterator);
  12783. };
  12784. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  12785. typedef ListenerClass ListenerType;
  12786. const ArrayType& getListeners() const noexcept { return listeners; }
  12787. private:
  12788. ArrayType listeners;
  12789. JUCE_DECLARE_NON_COPYABLE (ListenerList);
  12790. #undef LL_TEMPLATE
  12791. #undef LL_PARAM
  12792. };
  12793. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  12794. /*** End of inlined file: juce_ListenerList.h ***/
  12795. /**
  12796. Represents a shared variant value.
  12797. A Value object contains a reference to a var object, and can get and set its value.
  12798. Listeners can be attached to be told when the value is changed.
  12799. The Value class is a wrapper around a shared, reference-counted underlying data
  12800. object - this means that multiple Value objects can all refer to the same piece of
  12801. data, allowing all of them to be notified when any of them changes it.
  12802. When you create a Value with its default constructor, it acts as a wrapper around a
  12803. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  12804. you can map the Value onto any kind of underlying data.
  12805. */
  12806. class JUCE_API Value
  12807. {
  12808. public:
  12809. /** Creates an empty Value, containing a void var. */
  12810. Value();
  12811. /** Creates a Value that refers to the same value as another one.
  12812. Note that this doesn't make a copy of the other value - both this and the other
  12813. Value will share the same underlying value, so that when either one alters it, both
  12814. will see it change.
  12815. */
  12816. Value (const Value& other);
  12817. /** Creates a Value that is set to the specified value. */
  12818. explicit Value (const var& initialValue);
  12819. /** Destructor. */
  12820. ~Value();
  12821. /** Returns the current value. */
  12822. var getValue() const;
  12823. /** Returns the current value. */
  12824. operator var() const;
  12825. /** Returns the value as a string.
  12826. This is alternative to writing things like "myValue.getValue().toString()".
  12827. */
  12828. String toString() const;
  12829. /** Sets the current value.
  12830. You can also use operator= to set the value.
  12831. If there are any listeners registered, they will be notified of the
  12832. change asynchronously.
  12833. */
  12834. void setValue (const var& newValue);
  12835. /** Sets the current value.
  12836. This is the same as calling setValue().
  12837. If there are any listeners registered, they will be notified of the
  12838. change asynchronously.
  12839. */
  12840. Value& operator= (const var& newValue);
  12841. /** Makes this object refer to the same underlying ValueSource as another one.
  12842. Once this object has been connected to another one, changing either one
  12843. will update the other.
  12844. Existing listeners will still be registered after you call this method, and
  12845. they'll continue to receive messages when the new value changes.
  12846. */
  12847. void referTo (const Value& valueToReferTo);
  12848. /** Returns true if this value and the other one are references to the same value.
  12849. */
  12850. bool refersToSameSourceAs (const Value& other) const;
  12851. /** Compares two values.
  12852. This is a compare-by-value comparison, so is effectively the same as
  12853. saying (this->getValue() == other.getValue()).
  12854. */
  12855. bool operator== (const Value& other) const;
  12856. /** Compares two values.
  12857. This is a compare-by-value comparison, so is effectively the same as
  12858. saying (this->getValue() != other.getValue()).
  12859. */
  12860. bool operator!= (const Value& other) const;
  12861. /** Receives callbacks when a Value object changes.
  12862. @see Value::addListener
  12863. */
  12864. class JUCE_API Listener
  12865. {
  12866. public:
  12867. Listener() {}
  12868. virtual ~Listener() {}
  12869. /** Called when a Value object is changed.
  12870. Note that the Value object passed as a parameter may not be exactly the same
  12871. object that you registered the listener with - it might be a copy that refers
  12872. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  12873. */
  12874. virtual void valueChanged (Value& value) = 0;
  12875. };
  12876. /** Adds a listener to receive callbacks when the value changes.
  12877. The listener is added to this specific Value object, and not to the shared
  12878. object that it refers to. When this object is deleted, all the listeners will
  12879. be lost, even if other references to the same Value still exist. So when you're
  12880. adding a listener, make sure that you add it to a ValueTree instance that will last
  12881. for as long as you need the listener. In general, you'd never want to add a listener
  12882. to a local stack-based ValueTree, but more likely to one that's a member variable.
  12883. @see removeListener
  12884. */
  12885. void addListener (Listener* listener);
  12886. /** Removes a listener that was previously added with addListener(). */
  12887. void removeListener (Listener* listener);
  12888. /**
  12889. Used internally by the Value class as the base class for its shared value objects.
  12890. The Value class is essentially a reference-counted pointer to a shared instance
  12891. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  12892. ValueSource classes to allow Value objects to represent your own custom data items.
  12893. */
  12894. class JUCE_API ValueSource : public SingleThreadedReferenceCountedObject,
  12895. public AsyncUpdater
  12896. {
  12897. public:
  12898. ValueSource();
  12899. virtual ~ValueSource();
  12900. /** Returns the current value of this object. */
  12901. virtual var getValue() const = 0;
  12902. /** Changes the current value.
  12903. This must also trigger a change message if the value actually changes.
  12904. */
  12905. virtual void setValue (const var& newValue) = 0;
  12906. /** Delivers a change message to all the listeners that are registered with
  12907. this value.
  12908. If dispatchSynchronously is true, the method will call all the listeners
  12909. before returning; otherwise it'll dispatch a message and make the call later.
  12910. */
  12911. void sendChangeMessage (bool dispatchSynchronously);
  12912. protected:
  12913. friend class Value;
  12914. SortedSet <Value*> valuesWithListeners;
  12915. void handleAsyncUpdate();
  12916. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueSource);
  12917. };
  12918. /** Creates a Value object that uses this valueSource object as its underlying data. */
  12919. explicit Value (ValueSource* valueSource);
  12920. /** Returns the ValueSource that this value is referring to. */
  12921. ValueSource& getValueSource() noexcept { return *value; }
  12922. private:
  12923. friend class ValueSource;
  12924. ReferenceCountedObjectPtr <ValueSource> value;
  12925. ListenerList <Listener> listeners;
  12926. void callListeners();
  12927. // This is disallowed to avoid confusion about whether it should
  12928. // do a by-value or by-reference copy.
  12929. Value& operator= (const Value& other);
  12930. };
  12931. /** Writes a Value to an OutputStream as a UTF8 string. */
  12932. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  12933. /** This typedef is just for compatibility with old code - newer code should use the Value::Listener class directly. */
  12934. typedef Value::Listener ValueListener;
  12935. #endif // __JUCE_VALUE_JUCEHEADER__
  12936. /*** End of inlined file: juce_Value.h ***/
  12937. #endif
  12938. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12939. /*** Start of inlined file: juce_ValueTree.h ***/
  12940. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12941. #define __JUCE_VALUETREE_JUCEHEADER__
  12942. /*** Start of inlined file: juce_UndoManager.h ***/
  12943. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  12944. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  12945. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  12946. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12947. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12948. /*** Start of inlined file: juce_ChangeListener.h ***/
  12949. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  12950. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  12951. class ChangeBroadcaster;
  12952. /**
  12953. Receives change event callbacks that are sent out by a ChangeBroadcaster.
  12954. A ChangeBroadcaster keeps a set of listeners to which it broadcasts a message when
  12955. the ChangeBroadcaster::sendChangeMessage() method is called. A subclass of
  12956. ChangeListener is used to receive these callbacks.
  12957. Note that the major difference between an ActionListener and a ChangeListener
  12958. is that for a ChangeListener, multiple changes will be coalesced into fewer
  12959. callbacks, but ActionListeners perform one callback for every event posted.
  12960. @see ChangeBroadcaster, ActionListener
  12961. */
  12962. class JUCE_API ChangeListener
  12963. {
  12964. public:
  12965. /** Destructor. */
  12966. virtual ~ChangeListener() {}
  12967. /** Your subclass should implement this method to receive the callback.
  12968. @param source the ChangeBroadcaster that triggered the callback.
  12969. */
  12970. virtual void changeListenerCallback (ChangeBroadcaster* source) = 0;
  12971. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  12972. // This method's signature has changed to take a ChangeBroadcaster parameter - please update your code!
  12973. private: virtual int changeListenerCallback (void*) { return 0; }
  12974. #endif
  12975. };
  12976. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  12977. /*** End of inlined file: juce_ChangeListener.h ***/
  12978. /**
  12979. Holds a list of ChangeListeners, and sends messages to them when instructed.
  12980. @see ChangeListener
  12981. */
  12982. class JUCE_API ChangeBroadcaster
  12983. {
  12984. public:
  12985. /** Creates an ChangeBroadcaster. */
  12986. ChangeBroadcaster() noexcept;
  12987. /** Destructor. */
  12988. virtual ~ChangeBroadcaster();
  12989. /** Registers a listener to receive change callbacks from this broadcaster.
  12990. Trying to add a listener that's already on the list will have no effect.
  12991. */
  12992. void addChangeListener (ChangeListener* listener);
  12993. /** Unregisters a listener from the list.
  12994. If the listener isn't on the list, this won't have any effect.
  12995. */
  12996. void removeChangeListener (ChangeListener* listener);
  12997. /** Removes all listeners from the list. */
  12998. void removeAllChangeListeners();
  12999. /** Causes an asynchronous change message to be sent to all the registered listeners.
  13000. The message will be delivered asynchronously by the main message thread, so this
  13001. method will return immediately. To call the listeners synchronously use
  13002. sendSynchronousChangeMessage().
  13003. */
  13004. void sendChangeMessage();
  13005. /** Sends a synchronous change message to all the registered listeners.
  13006. This will immediately call all the listeners that are registered. For thread-safety
  13007. reasons, you must only call this method on the main message thread.
  13008. @see dispatchPendingMessages
  13009. */
  13010. void sendSynchronousChangeMessage();
  13011. /** If a change message has been sent but not yet dispatched, this will call
  13012. sendSynchronousChangeMessage() to make the callback immediately.
  13013. For thread-safety reasons, you must only call this method on the main message thread.
  13014. */
  13015. void dispatchPendingMessages();
  13016. private:
  13017. class ChangeBroadcasterCallback : public AsyncUpdater
  13018. {
  13019. public:
  13020. ChangeBroadcasterCallback();
  13021. void handleAsyncUpdate();
  13022. ChangeBroadcaster* owner;
  13023. };
  13024. friend class ChangeBroadcasterCallback;
  13025. ChangeBroadcasterCallback callback;
  13026. ListenerList <ChangeListener> changeListeners;
  13027. void callListeners();
  13028. JUCE_DECLARE_NON_COPYABLE (ChangeBroadcaster);
  13029. };
  13030. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  13031. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  13032. /*** Start of inlined file: juce_UndoableAction.h ***/
  13033. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  13034. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  13035. /**
  13036. Used by the UndoManager class to store an action which can be done
  13037. and undone.
  13038. @see UndoManager
  13039. */
  13040. class JUCE_API UndoableAction
  13041. {
  13042. protected:
  13043. /** Creates an action. */
  13044. UndoableAction() noexcept {}
  13045. public:
  13046. /** Destructor. */
  13047. virtual ~UndoableAction() {}
  13048. /** Overridden by a subclass to perform the action.
  13049. This method is called by the UndoManager, and shouldn't be used directly by
  13050. applications.
  13051. Be careful not to make any calls in a perform() method that could call
  13052. recursively back into the UndoManager::perform() method
  13053. @returns true if the action could be performed.
  13054. @see UndoManager::perform
  13055. */
  13056. virtual bool perform() = 0;
  13057. /** Overridden by a subclass to undo the action.
  13058. This method is called by the UndoManager, and shouldn't be used directly by
  13059. applications.
  13060. Be careful not to make any calls in an undo() method that could call
  13061. recursively back into the UndoManager::perform() method
  13062. @returns true if the action could be undone without any errors.
  13063. @see UndoManager::perform
  13064. */
  13065. virtual bool undo() = 0;
  13066. /** Returns a value to indicate how much memory this object takes up.
  13067. Because the UndoManager keeps a list of UndoableActions, this is used
  13068. to work out how much space each one will take up, so that the UndoManager
  13069. can work out how many to keep.
  13070. The default value returned here is 10 - units are arbitrary and
  13071. don't have to be accurate.
  13072. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  13073. UndoManager::setMaxNumberOfStoredUnits
  13074. */
  13075. virtual int getSizeInUnits() { return 10; }
  13076. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  13077. If possible, this method should create and return a single action that does the same job as
  13078. this one followed by the supplied action.
  13079. If it's not possible to merge the two actions, the method should return zero.
  13080. */
  13081. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return nullptr; }
  13082. };
  13083. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  13084. /*** End of inlined file: juce_UndoableAction.h ***/
  13085. /**
  13086. Manages a list of undo/redo commands.
  13087. An UndoManager object keeps a list of past actions and can use these actions
  13088. to move backwards and forwards through an undo history.
  13089. To use it, create subclasses of UndoableAction which perform all the
  13090. actions you need, then when you need to actually perform an action, create one
  13091. and pass it to the UndoManager's perform() method.
  13092. The manager also uses the concept of 'transactions' to group the actions
  13093. together - all actions performed between calls to beginNewTransaction() are
  13094. grouped together and are all undone/redone as a group.
  13095. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  13096. when actions are performed or undone.
  13097. @see UndoableAction
  13098. */
  13099. class JUCE_API UndoManager : public ChangeBroadcaster
  13100. {
  13101. public:
  13102. /** Creates an UndoManager.
  13103. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  13104. to indicate how much storage it takes up
  13105. (UndoableAction::getSizeInUnits()), so this
  13106. lets you specify the maximum total number of
  13107. units that the undomanager is allowed to
  13108. keep in memory before letting the older actions
  13109. drop off the end of the list.
  13110. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  13111. that will be kept, even if this involves exceeding
  13112. the amount of space specified in maxNumberOfUnitsToKeep
  13113. */
  13114. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  13115. int minimumTransactionsToKeep = 30);
  13116. /** Destructor. */
  13117. ~UndoManager();
  13118. /** Deletes all stored actions in the list. */
  13119. void clearUndoHistory();
  13120. /** Returns the current amount of space to use for storing UndoableAction objects.
  13121. @see setMaxNumberOfStoredUnits
  13122. */
  13123. int getNumberOfUnitsTakenUpByStoredCommands() const;
  13124. /** Sets the amount of space that can be used for storing UndoableAction objects.
  13125. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  13126. to indicate how much storage it takes up
  13127. (UndoableAction::getSizeInUnits()), so this
  13128. lets you specify the maximum total number of
  13129. units that the undomanager is allowed to
  13130. keep in memory before letting the older actions
  13131. drop off the end of the list.
  13132. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  13133. that will be kept, even if this involves exceeding
  13134. the amount of space specified in maxNumberOfUnitsToKeep
  13135. @see getNumberOfUnitsTakenUpByStoredCommands
  13136. */
  13137. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  13138. int minimumTransactionsToKeep);
  13139. /** Performs an action and adds it to the undo history list.
  13140. @param action the action to perform - this will be deleted by the UndoManager
  13141. when no longer needed
  13142. @param actionName if this string is non-empty, the current transaction will be
  13143. given this name; if it's empty, the current transaction name will
  13144. be left unchanged. See setCurrentTransactionName()
  13145. @returns true if the command succeeds - see UndoableAction::perform
  13146. @see beginNewTransaction
  13147. */
  13148. bool perform (UndoableAction* action,
  13149. const String& actionName = String::empty);
  13150. /** Starts a new group of actions that together will be treated as a single transaction.
  13151. All actions that are passed to the perform() method between calls to this
  13152. method are grouped together and undone/redone together by a single call to
  13153. undo() or redo().
  13154. @param actionName a description of the transaction that is about to be
  13155. performed
  13156. */
  13157. void beginNewTransaction (const String& actionName = String::empty);
  13158. /** Changes the name stored for the current transaction.
  13159. Each transaction is given a name when the beginNewTransaction() method is
  13160. called, but this can be used to change that name without starting a new
  13161. transaction.
  13162. */
  13163. void setCurrentTransactionName (const String& newName);
  13164. /** Returns true if there's at least one action in the list to undo.
  13165. @see getUndoDescription, undo, canRedo
  13166. */
  13167. bool canUndo() const;
  13168. /** Returns the description of the transaction that would be next to get undone.
  13169. The description returned is the one that was passed into beginNewTransaction
  13170. before the set of actions was performed.
  13171. @see undo
  13172. */
  13173. String getUndoDescription() const;
  13174. /** Tries to roll-back the last transaction.
  13175. @returns true if the transaction can be undone, and false if it fails, or
  13176. if there aren't any transactions to undo
  13177. */
  13178. bool undo();
  13179. /** Tries to roll-back any actions that were added to the current transaction.
  13180. This will perform an undo() only if there are some actions in the undo list
  13181. that were added after the last call to beginNewTransaction().
  13182. This is useful because it lets you call beginNewTransaction(), then
  13183. perform an operation which may or may not actually perform some actions, and
  13184. then call this method to get rid of any actions that might have been done
  13185. without it rolling back the previous transaction if nothing was actually
  13186. done.
  13187. @returns true if any actions were undone.
  13188. */
  13189. bool undoCurrentTransactionOnly();
  13190. /** Returns a list of the UndoableAction objects that have been performed during the
  13191. transaction that is currently open.
  13192. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  13193. were to be called now.
  13194. The first item in the list is the earliest action performed.
  13195. */
  13196. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  13197. /** Returns the number of UndoableAction objects that have been performed during the
  13198. transaction that is currently open.
  13199. @see getActionsInCurrentTransaction
  13200. */
  13201. int getNumActionsInCurrentTransaction() const;
  13202. /** Returns true if there's at least one action in the list to redo.
  13203. @see getRedoDescription, redo, canUndo
  13204. */
  13205. bool canRedo() const;
  13206. /** Returns the description of the transaction that would be next to get redone.
  13207. The description returned is the one that was passed into beginNewTransaction
  13208. before the set of actions was performed.
  13209. @see redo
  13210. */
  13211. String getRedoDescription() const;
  13212. /** Tries to redo the last transaction that was undone.
  13213. @returns true if the transaction can be redone, and false if it fails, or
  13214. if there aren't any transactions to redo
  13215. */
  13216. bool redo();
  13217. private:
  13218. OwnedArray <OwnedArray <UndoableAction> > transactions;
  13219. StringArray transactionNames;
  13220. String currentTransactionName;
  13221. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  13222. bool newTransaction, reentrancyCheck;
  13223. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UndoManager);
  13224. };
  13225. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  13226. /*** End of inlined file: juce_UndoManager.h ***/
  13227. /**
  13228. A powerful tree structure that can be used to hold free-form data, and which can
  13229. handle its own undo and redo behaviour.
  13230. A ValueTree contains a list of named properties as var objects, and also holds
  13231. any number of sub-trees.
  13232. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  13233. they're simply a lightweight reference to a shared data container. Creating a copy
  13234. of another ValueTree simply creates a new reference to the same underlying object - to
  13235. make a separate, deep copy of a tree you should explicitly call createCopy().
  13236. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  13237. and much of the structure of a ValueTree is similar to an XmlElement tree.
  13238. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  13239. contain text elements, the conversion works well and makes a good serialisation
  13240. format. They can also be serialised to a binary format, which is very fast and compact.
  13241. All the methods that change data take an optional UndoManager, which will be used
  13242. to track any changes to the object. For this to work, you have to be careful to
  13243. consistently always use the same UndoManager for all operations to any node inside
  13244. the tree.
  13245. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  13246. one tree to another, be careful to always remove it first, before adding it. This
  13247. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  13248. assertions if you try to do anything dangerous, but there are still plenty of ways it
  13249. could go wrong.
  13250. Listeners can be added to a ValueTree to be told when properies change and when
  13251. nodes are added or removed.
  13252. @see var, XmlElement
  13253. */
  13254. class JUCE_API ValueTree
  13255. {
  13256. public:
  13257. /** Creates an empty, invalid ValueTree.
  13258. A ValueTree that is created with this constructor can't actually be used for anything,
  13259. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  13260. To create a real one, use the constructor that takes a string.
  13261. @see ValueTree::invalid
  13262. */
  13263. ValueTree() noexcept;
  13264. /** Creates an empty ValueTree with the given type name.
  13265. Like an XmlElement, each ValueTree node has a type, which you can access with
  13266. getType() and hasType().
  13267. */
  13268. explicit ValueTree (const Identifier& type);
  13269. /** Creates a reference to another ValueTree. */
  13270. ValueTree (const ValueTree& other);
  13271. /** Makes this object reference another node. */
  13272. ValueTree& operator= (const ValueTree& other);
  13273. /** Destructor. */
  13274. ~ValueTree();
  13275. /** Returns true if both this and the other tree node refer to the same underlying structure.
  13276. Note that this isn't a value comparison - two independently-created trees which
  13277. contain identical data are not considered equal.
  13278. */
  13279. bool operator== (const ValueTree& other) const noexcept;
  13280. /** Returns true if this and the other node refer to different underlying structures.
  13281. Note that this isn't a value comparison - two independently-created trees which
  13282. contain identical data are not considered equal.
  13283. */
  13284. bool operator!= (const ValueTree& other) const noexcept;
  13285. /** Performs a deep comparison between the properties and children of two trees.
  13286. If all the properties and children of the two trees are the same (recursively), this
  13287. returns true.
  13288. The normal operator==() only checks whether two trees refer to the same shared data
  13289. structure, so use this method if you need to do a proper value comparison.
  13290. */
  13291. bool isEquivalentTo (const ValueTree& other) const;
  13292. /** Returns true if this node refers to some valid data.
  13293. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  13294. call to getChild().
  13295. */
  13296. bool isValid() const { return object != nullptr; }
  13297. /** Returns a deep copy of this tree and all its sub-nodes. */
  13298. ValueTree createCopy() const;
  13299. /** Returns the type of this node.
  13300. The type is specified when the ValueTree is created.
  13301. @see hasType
  13302. */
  13303. Identifier getType() const;
  13304. /** Returns true if the node has this type.
  13305. The comparison is case-sensitive.
  13306. */
  13307. bool hasType (const Identifier& typeName) const;
  13308. /** Returns the value of a named property.
  13309. If no such property has been set, this will return a void variant.
  13310. You can also use operator[] to get a property.
  13311. @see var, setProperty, hasProperty
  13312. */
  13313. const var& getProperty (const Identifier& name) const;
  13314. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  13315. If no such property has been set, this will return the value of defaultReturnValue.
  13316. You can also use operator[] and getProperty to get a property.
  13317. @see var, getProperty, setProperty, hasProperty
  13318. */
  13319. var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  13320. /** Returns the value of a named property.
  13321. If no such property has been set, this will return a void variant. This is the same as
  13322. calling getProperty().
  13323. @see getProperty
  13324. */
  13325. const var& operator[] (const Identifier& name) const;
  13326. /** Changes a named property of the node.
  13327. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13328. so that this change can be undone.
  13329. @see var, getProperty, removeProperty
  13330. */
  13331. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  13332. /** Returns true if the node contains a named property. */
  13333. bool hasProperty (const Identifier& name) const;
  13334. /** Removes a property from the node.
  13335. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13336. so that this change can be undone.
  13337. */
  13338. void removeProperty (const Identifier& name, UndoManager* undoManager);
  13339. /** Removes all properties from the node.
  13340. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13341. so that this change can be undone.
  13342. */
  13343. void removeAllProperties (UndoManager* undoManager);
  13344. /** Returns the total number of properties that the node contains.
  13345. @see getProperty.
  13346. */
  13347. int getNumProperties() const;
  13348. /** Returns the identifier of the property with a given index.
  13349. @see getNumProperties
  13350. */
  13351. Identifier getPropertyName (int index) const;
  13352. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  13353. The Value object will maintain a reference to this tree, and will use the undo manager when
  13354. it needs to change the value. Attaching a Value::Listener to the value object will provide
  13355. callbacks whenever the property changes.
  13356. */
  13357. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  13358. /** Returns the number of child nodes belonging to this one.
  13359. @see getChild
  13360. */
  13361. int getNumChildren() const;
  13362. /** Returns one of this node's child nodes.
  13363. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  13364. whether a node is valid).
  13365. */
  13366. ValueTree getChild (int index) const;
  13367. /** Returns the first child node with the speficied type name.
  13368. If no such node is found, it'll return an invalid node. (See isValid() to find out
  13369. whether a node is valid).
  13370. @see getOrCreateChildWithName
  13371. */
  13372. ValueTree getChildWithName (const Identifier& type) const;
  13373. /** Returns the first child node with the speficied type name, creating and adding
  13374. a child with this name if there wasn't already one there.
  13375. The only time this will return an invalid object is when the object that you're calling
  13376. the method on is itself invalid.
  13377. @see getChildWithName
  13378. */
  13379. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  13380. /** Looks for the first child node that has the speficied property value.
  13381. This will scan the child nodes in order, until it finds one that has property that matches
  13382. the specified value.
  13383. If no such node is found, it'll return an invalid node. (See isValid() to find out
  13384. whether a node is valid).
  13385. */
  13386. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  13387. /** Adds a child to this node.
  13388. Make sure that the child is removed from any former parent node before calling this, or
  13389. you'll hit an assertion.
  13390. If the index is < 0 or greater than the current number of child nodes, the new node will
  13391. be added at the end of the list.
  13392. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13393. so that this change can be undone.
  13394. */
  13395. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  13396. /** Removes the specified child from this node's child-list.
  13397. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13398. so that this change can be undone.
  13399. */
  13400. void removeChild (const ValueTree& child, UndoManager* undoManager);
  13401. /** Removes a child from this node's child-list.
  13402. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13403. so that this change can be undone.
  13404. */
  13405. void removeChild (int childIndex, UndoManager* undoManager);
  13406. /** Removes all child-nodes from this node.
  13407. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13408. so that this change can be undone.
  13409. */
  13410. void removeAllChildren (UndoManager* undoManager);
  13411. /** Moves one of the children to a different index.
  13412. This will move the child to a specified index, shuffling along any intervening
  13413. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  13414. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  13415. @param currentIndex the index of the item to be moved. If this isn't a
  13416. valid index, then nothing will be done
  13417. @param newIndex the index at which you'd like this item to end up. If this
  13418. is less than zero, the value will be moved to the end
  13419. of the list
  13420. @param undoManager the optional UndoManager to use to store this transaction
  13421. */
  13422. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  13423. /** Returns true if this node is anywhere below the specified parent node.
  13424. This returns true if the node is a child-of-a-child, as well as a direct child.
  13425. */
  13426. bool isAChildOf (const ValueTree& possibleParent) const;
  13427. /** Returns the index of a child item in this parent.
  13428. If the child isn't found, this returns -1.
  13429. */
  13430. int indexOf (const ValueTree& child) const;
  13431. /** Returns the parent node that contains this one.
  13432. If the node has no parent, this will return an invalid node. (See isValid() to find out
  13433. whether a node is valid).
  13434. */
  13435. ValueTree getParent() const;
  13436. /** Returns one of this node's siblings in its parent's child list.
  13437. The delta specifies how far to move through the list, so a value of 1 would return the node
  13438. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  13439. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  13440. */
  13441. ValueTree getSibling (int delta) const;
  13442. /** Creates an XmlElement that holds a complete image of this node and all its children.
  13443. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  13444. be used to recreate a similar node by calling fromXml()
  13445. @see fromXml
  13446. */
  13447. XmlElement* createXml() const;
  13448. /** Tries to recreate a node from its XML representation.
  13449. This isn't designed to cope with random XML data - for a sensible result, it should only
  13450. be fed XML that was created by the createXml() method.
  13451. */
  13452. static ValueTree fromXml (const XmlElement& xml);
  13453. /** Stores this tree (and all its children) in a binary format.
  13454. Once written, the data can be read back with readFromStream().
  13455. It's much faster to load/save your tree in binary form than as XML, but
  13456. obviously isn't human-readable.
  13457. */
  13458. void writeToStream (OutputStream& output);
  13459. /** Reloads a tree from a stream that was written with writeToStream(). */
  13460. static ValueTree readFromStream (InputStream& input);
  13461. /** Reloads a tree from a data block that was written with writeToStream(). */
  13462. static ValueTree readFromData (const void* data, size_t numBytes);
  13463. /** Listener class for events that happen to a ValueTree.
  13464. To get events from a ValueTree, make your class implement this interface, and use
  13465. ValueTree::addListener() and ValueTree::removeListener() to register it.
  13466. */
  13467. class JUCE_API Listener
  13468. {
  13469. public:
  13470. /** Destructor. */
  13471. virtual ~Listener() {}
  13472. /** This method is called when a property of this node (or of one of its sub-nodes) has
  13473. changed.
  13474. The tree parameter indicates which tree has had its property changed, and the property
  13475. parameter indicates the property.
  13476. Note that when you register a listener to a tree, it will receive this callback for
  13477. property changes in that tree, and also for any of its children, (recursively, at any depth).
  13478. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13479. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  13480. */
  13481. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  13482. const Identifier& property) = 0;
  13483. /** This method is called when a child sub-tree is added.
  13484. Note that when you register a listener to a tree, it will receive this callback for
  13485. child changes in both that tree and any of its children, (recursively, at any depth).
  13486. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13487. just check the parentTree parameter to make sure it's the one that you're interested in.
  13488. */
  13489. virtual void valueTreeChildAdded (ValueTree& parentTree,
  13490. ValueTree& childWhichHasBeenAdded) = 0;
  13491. /** This method is called when a child sub-tree is removed.
  13492. Note that when you register a listener to a tree, it will receive this callback for
  13493. child changes in both that tree and any of its children, (recursively, at any depth).
  13494. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13495. just check the parentTree parameter to make sure it's the one that you're interested in.
  13496. */
  13497. virtual void valueTreeChildRemoved (ValueTree& parentTree,
  13498. ValueTree& childWhichHasBeenRemoved) = 0;
  13499. /** This method is called when a tree's children have been re-shuffled.
  13500. Note that when you register a listener to a tree, it will receive this callback for
  13501. child changes in both that tree and any of its children, (recursively, at any depth).
  13502. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13503. just check the parameter to make sure it's the tree that you're interested in.
  13504. */
  13505. virtual void valueTreeChildOrderChanged (ValueTree& parentTreeWhoseChildrenHaveMoved) = 0;
  13506. /** This method is called when a tree has been added or removed from a parent node.
  13507. This callback happens when the tree to which the listener was registered is added or
  13508. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  13509. the listener is registered, and not to any of its children.
  13510. */
  13511. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  13512. };
  13513. /** Adds a listener to receive callbacks when this node is changed.
  13514. The listener is added to this specific ValueTree object, and not to the shared
  13515. object that it refers to. When this object is deleted, all the listeners will
  13516. be lost, even if other references to the same ValueTree still exist. And if you
  13517. use the operator= to make this refer to a different ValueTree, any listeners will
  13518. begin listening to changes to the new tree instead of the old one.
  13519. When you're adding a listener, make sure that you add it to a ValueTree instance that
  13520. will last for as long as you need the listener. In general, you'd never want to add a
  13521. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  13522. @see removeListener
  13523. */
  13524. void addListener (Listener* listener);
  13525. /** Removes a listener that was previously added with addListener(). */
  13526. void removeListener (Listener* listener);
  13527. /** This method uses a comparator object to sort the tree's children into order.
  13528. The object provided must have a method of the form:
  13529. @code
  13530. int compareElements (const ValueTree& first, const ValueTree& second);
  13531. @endcode
  13532. ..and this method must return:
  13533. - a value of < 0 if the first comes before the second
  13534. - a value of 0 if the two objects are equivalent
  13535. - a value of > 0 if the second comes before the first
  13536. To improve performance, the compareElements() method can be declared as static or const.
  13537. @param comparator the comparator to use for comparing elements.
  13538. @param undoManager optional UndoManager for storing the changes
  13539. @param retainOrderOfEquivalentItems if this is true, then items which the comparator says are
  13540. equivalent will be kept in the order in which they currently appear in the array.
  13541. This is slower to perform, but may be important in some cases. If it's false, a
  13542. faster algorithm is used, but equivalent elements may be rearranged.
  13543. */
  13544. template <typename ElementComparator>
  13545. void sort (ElementComparator& comparator, UndoManager* undoManager, bool retainOrderOfEquivalentItems)
  13546. {
  13547. if (object != nullptr)
  13548. {
  13549. ReferenceCountedArray <SharedObject> sortedList (object->children);
  13550. ComparatorAdapter <ElementComparator> adapter (comparator);
  13551. sortedList.sort (adapter, retainOrderOfEquivalentItems);
  13552. object->reorderChildren (sortedList, undoManager);
  13553. }
  13554. }
  13555. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  13556. This invalid object is equivalent to ValueTree created with its default constructor.
  13557. */
  13558. static const ValueTree invalid;
  13559. private:
  13560. class SetPropertyAction; friend class SetPropertyAction;
  13561. class AddOrRemoveChildAction; friend class AddOrRemoveChildAction;
  13562. class MoveChildAction; friend class MoveChildAction;
  13563. class JUCE_API SharedObject : public SingleThreadedReferenceCountedObject
  13564. {
  13565. public:
  13566. explicit SharedObject (const Identifier& type);
  13567. SharedObject (const SharedObject& other);
  13568. ~SharedObject();
  13569. const Identifier type;
  13570. NamedValueSet properties;
  13571. ReferenceCountedArray <SharedObject> children;
  13572. SortedSet <ValueTree*> valueTreesWithListeners;
  13573. SharedObject* parent;
  13574. void sendPropertyChangeMessage (const Identifier& property);
  13575. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  13576. void sendChildAddedMessage (ValueTree& parent, ValueTree& child);
  13577. void sendChildAddedMessage (ValueTree child);
  13578. void sendChildRemovedMessage (ValueTree& parent, ValueTree& child);
  13579. void sendChildRemovedMessage (ValueTree child);
  13580. void sendChildOrderChangedMessage (ValueTree& parent);
  13581. void sendChildOrderChangedMessage();
  13582. void sendParentChangeMessage();
  13583. const var& getProperty (const Identifier& name) const;
  13584. var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  13585. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  13586. bool hasProperty (const Identifier& name) const;
  13587. void removeProperty (const Identifier& name, UndoManager*);
  13588. void removeAllProperties (UndoManager*);
  13589. bool isAChildOf (const SharedObject* possibleParent) const;
  13590. int indexOf (const ValueTree& child) const;
  13591. ValueTree getChildWithName (const Identifier& type) const;
  13592. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  13593. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  13594. void addChild (SharedObject* child, int index, UndoManager*);
  13595. void removeChild (int childIndex, UndoManager*);
  13596. void removeAllChildren (UndoManager*);
  13597. void moveChild (int currentIndex, int newIndex, UndoManager*);
  13598. void reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager*);
  13599. bool isEquivalentTo (const SharedObject& other) const;
  13600. XmlElement* createXml() const;
  13601. private:
  13602. SharedObject& operator= (const SharedObject&);
  13603. JUCE_LEAK_DETECTOR (SharedObject);
  13604. };
  13605. template <typename ElementComparator>
  13606. class ComparatorAdapter
  13607. {
  13608. public:
  13609. ComparatorAdapter (ElementComparator& comparator_) noexcept : comparator (comparator_) {}
  13610. int compareElements (SharedObject* const first, SharedObject* const second)
  13611. {
  13612. return comparator.compareElements (ValueTree (first), ValueTree (second));
  13613. }
  13614. private:
  13615. ElementComparator& comparator;
  13616. JUCE_DECLARE_NON_COPYABLE (ComparatorAdapter);
  13617. };
  13618. friend class SharedObject;
  13619. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  13620. SharedObjectPtr object;
  13621. ListenerList <Listener> listeners;
  13622. #if JUCE_MSVC && ! DOXYGEN
  13623. public: // (workaround for VC6)
  13624. #endif
  13625. explicit ValueTree (SharedObject*);
  13626. };
  13627. #endif // __JUCE_VALUETREE_JUCEHEADER__
  13628. /*** End of inlined file: juce_ValueTree.h ***/
  13629. #endif
  13630. #ifndef __JUCE_VARIANT_JUCEHEADER__
  13631. #endif
  13632. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  13633. /*** Start of inlined file: juce_FileLogger.h ***/
  13634. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  13635. #define __JUCE_FILELOGGER_JUCEHEADER__
  13636. /**
  13637. A simple implemenation of a Logger that writes to a file.
  13638. @see Logger
  13639. */
  13640. class JUCE_API FileLogger : public Logger
  13641. {
  13642. public:
  13643. /** Creates a FileLogger for a given file.
  13644. @param fileToWriteTo the file that to use - new messages will be appended
  13645. to the file. If the file doesn't exist, it will be created,
  13646. along with any parent directories that are needed.
  13647. @param welcomeMessage when opened, the logger will write a header to the log, along
  13648. with the current date and time, and this welcome message
  13649. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  13650. but is larger than this number of bytes, then the start of the
  13651. file will be truncated to keep the size down. This prevents a log
  13652. file getting ridiculously large over time. The file will be truncated
  13653. at a new-line boundary. If this value is less than zero, no size limit
  13654. will be imposed; if it's zero, the file will always be deleted. Note that
  13655. the size is only checked once when this object is created - any logging
  13656. that is done later will be appended without any checking
  13657. */
  13658. FileLogger (const File& fileToWriteTo,
  13659. const String& welcomeMessage,
  13660. const int maxInitialFileSizeBytes = 128 * 1024);
  13661. /** Destructor. */
  13662. ~FileLogger();
  13663. void logMessage (const String& message);
  13664. File getLogFile() const { return logFile; }
  13665. /** Helper function to create a log file in the correct place for this platform.
  13666. On Windows this will return a logger with a path such as:
  13667. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  13668. On the Mac it'll create something like:
  13669. ~/Library/Logs/[logFileName]
  13670. The method might return 0 if the file can't be created for some reason.
  13671. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  13672. it's best to use the something like the name of your application here.
  13673. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  13674. call it "log.txt" because if it goes in a directory with logs
  13675. from other applications (as it will do on the Mac) then no-one
  13676. will know which one is yours!
  13677. @param welcomeMessage a message that will be written to the log when it's opened.
  13678. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  13679. */
  13680. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  13681. const String& logFileName,
  13682. const String& welcomeMessage,
  13683. const int maxInitialFileSizeBytes = 128 * 1024);
  13684. private:
  13685. File logFile;
  13686. CriticalSection logLock;
  13687. void trimFileSize (int maxFileSizeBytes) const;
  13688. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileLogger);
  13689. };
  13690. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  13691. /*** End of inlined file: juce_FileLogger.h ***/
  13692. #endif
  13693. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  13694. /*** Start of inlined file: juce_Initialisation.h ***/
  13695. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  13696. #define __JUCE_INITIALISATION_JUCEHEADER__
  13697. /** Initialises Juce's GUI classes.
  13698. If you're embedding Juce into an application that uses its own event-loop rather
  13699. than using the START_JUCE_APPLICATION macro, call this function before making any
  13700. Juce calls, to make sure things are initialised correctly.
  13701. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  13702. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  13703. @see shutdownJuce_GUI()
  13704. */
  13705. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
  13706. /** Clears up any static data being used by Juce's GUI classes.
  13707. If you're embedding Juce into an application that uses its own event-loop rather
  13708. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  13709. code to clean up any juce objects that might be lying around.
  13710. @see initialiseJuce_GUI()
  13711. */
  13712. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  13713. /** A utility object that helps you initialise and shutdown Juce correctly
  13714. using an RAII pattern.
  13715. When an instance of this class is created, it calls initialiseJuce_GUI(),
  13716. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  13717. make sure that these functions are matched correctly.
  13718. This class is particularly handy to use at the beginning of a console app's
  13719. main() function, because it'll take care of shutting down whenever you return
  13720. from the main() call.
  13721. @see ScopedJuceInitialiser_NonGUI
  13722. */
  13723. class ScopedJuceInitialiser_GUI
  13724. {
  13725. public:
  13726. /** The constructor simply calls initialiseJuce_GUI(). */
  13727. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  13728. /** The destructor simply calls shutdownJuce_GUI(). */
  13729. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  13730. };
  13731. /*
  13732. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  13733. AppSubClass is the name of a class derived from JUCEApplication.
  13734. See the JUCEApplication class documentation (juce_Application.h) for more details.
  13735. */
  13736. #if JUCE_ANDROID
  13737. #define START_JUCE_APPLICATION(AppClass) \
  13738. JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); }
  13739. #elif defined (JUCE_GCC) || defined (__MWERKS__)
  13740. #define START_JUCE_APPLICATION(AppClass) \
  13741. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13742. int main (int argc, char* argv[]) \
  13743. { \
  13744. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13745. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv); \
  13746. }
  13747. #elif JUCE_WINDOWS
  13748. #ifdef _CONSOLE
  13749. #define START_JUCE_APPLICATION(AppClass) \
  13750. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13751. int main (int, char* argv[]) \
  13752. { \
  13753. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13754. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13755. }
  13756. #elif ! defined (_AFXDLL)
  13757. #ifdef _WINDOWS_
  13758. #define START_JUCE_APPLICATION(AppClass) \
  13759. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13760. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  13761. { \
  13762. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13763. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13764. }
  13765. #else
  13766. #define START_JUCE_APPLICATION(AppClass) \
  13767. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13768. int __stdcall WinMain (int, int, const char*, int) \
  13769. { \
  13770. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13771. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13772. }
  13773. #endif
  13774. #endif
  13775. #endif
  13776. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  13777. /*** End of inlined file: juce_Initialisation.h ***/
  13778. #endif
  13779. #ifndef __JUCE_LOGGER_JUCEHEADER__
  13780. #endif
  13781. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13782. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  13783. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13784. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13785. /** A timer for measuring performance of code and dumping the results to a file.
  13786. e.g. @code
  13787. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  13788. for (;;)
  13789. {
  13790. pc.start();
  13791. doSomethingFishy();
  13792. pc.stop();
  13793. }
  13794. @endcode
  13795. In this example, the time of each period between calling start/stop will be
  13796. measured and averaged over 50 runs, and the results printed to a file
  13797. every 50 times round the loop.
  13798. */
  13799. class JUCE_API PerformanceCounter
  13800. {
  13801. public:
  13802. /** Creates a PerformanceCounter object.
  13803. @param counterName the name used when printing out the statistics
  13804. @param runsPerPrintout the number of start/stop iterations before calling
  13805. printStatistics()
  13806. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  13807. the results are just written to the debugger output
  13808. */
  13809. PerformanceCounter (const String& counterName,
  13810. int runsPerPrintout = 100,
  13811. const File& loggingFile = File::nonexistent);
  13812. /** Destructor. */
  13813. ~PerformanceCounter();
  13814. /** Starts timing.
  13815. @see stop
  13816. */
  13817. void start();
  13818. /** Stops timing and prints out the results.
  13819. The number of iterations before doing a printout of the
  13820. results is set in the constructor.
  13821. @see start
  13822. */
  13823. void stop();
  13824. /** Dumps the current metrics to the debugger output and to a file.
  13825. As well as using Logger::outputDebugString to print the results,
  13826. this will write then to the file specified in the constructor (if
  13827. this was valid).
  13828. */
  13829. void printStatistics();
  13830. private:
  13831. String name;
  13832. int numRuns, runsPerPrint;
  13833. double totalTime;
  13834. int64 started;
  13835. File outputFile;
  13836. };
  13837. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13838. /*** End of inlined file: juce_PerformanceCounter.h ***/
  13839. #endif
  13840. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  13841. #endif
  13842. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13843. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  13844. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13845. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13846. /**
  13847. A collection of miscellaneous platform-specific utilities.
  13848. */
  13849. class JUCE_API PlatformUtilities
  13850. {
  13851. public:
  13852. /** Plays the operating system's default alert 'beep' sound. */
  13853. static void beep();
  13854. /** Tries to launch the system's default reader for a given file or URL. */
  13855. static bool openDocument (const String& documentURL, const String& parameters);
  13856. /** Tries to launch the system's default email app to let the user create an email.
  13857. */
  13858. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  13859. const String& emailSubject,
  13860. const String& bodyText,
  13861. const StringArray& filesToAttach);
  13862. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  13863. /** MAC ONLY - Turns a Core CF String into a juce one. */
  13864. static String cfStringToJuceString (CFStringRef cfString);
  13865. /** MAC ONLY - Turns a juce string into a Core CF one. */
  13866. static CFStringRef juceStringToCFString (const String& s);
  13867. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  13868. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  13869. /** MAC ONLY - Turns an FSRef into a juce string path. */
  13870. static String makePathFromFSRef (FSRef* file);
  13871. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  13872. their precomposed equivalents.
  13873. */
  13874. static String convertToPrecomposedUnicode (const String& s);
  13875. /** MAC ONLY - Gets the type of a file from the file's resources. */
  13876. static OSType getTypeOfFile (const String& filename);
  13877. /** MAC ONLY - Returns true if this file is actually a bundle. */
  13878. static bool isBundle (const String& filename);
  13879. /** MAC ONLY - Adds an item to the dock */
  13880. static void addItemToDock (const File& file);
  13881. /** MAC ONLY - Returns the current OS version number.
  13882. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  13883. */
  13884. static int getOSXMinorVersionNumber();
  13885. #endif
  13886. #if JUCE_WINDOWS || DOXYGEN
  13887. // Some registry helper functions:
  13888. /** WIN32 ONLY - Returns a string from the registry.
  13889. The path is a string for the entire path of a value in the registry,
  13890. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  13891. */
  13892. static String getRegistryValue (const String& regValuePath,
  13893. const String& defaultValue = String::empty);
  13894. /** WIN32 ONLY - Sets a registry value as a string.
  13895. This will take care of creating any groups needed to get to the given
  13896. registry value.
  13897. */
  13898. static void setRegistryValue (const String& regValuePath,
  13899. const String& value);
  13900. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  13901. static bool registryValueExists (const String& regValuePath);
  13902. /** WIN32 ONLY - Deletes a registry value. */
  13903. static void deleteRegistryValue (const String& regValuePath);
  13904. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  13905. static void deleteRegistryKey (const String& regKeyPath);
  13906. /** WIN32 ONLY - Creates a file association in the registry.
  13907. This lets you set the exe that should be launched by a given file extension.
  13908. @param fileExtension the file extension to associate, including the
  13909. initial dot, e.g. ".txt"
  13910. @param symbolicDescription a space-free short token to identify the file type
  13911. @param fullDescription a human-readable description of the file type
  13912. @param targetExecutable the executable that should be launched
  13913. @param iconResourceNumber the icon that gets displayed for the file type will be
  13914. found by looking up this resource number in the
  13915. executable. Pass 0 here to not use an icon
  13916. */
  13917. static void registerFileAssociation (const String& fileExtension,
  13918. const String& symbolicDescription,
  13919. const String& fullDescription,
  13920. const File& targetExecutable,
  13921. int iconResourceNumber);
  13922. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  13923. In a normal Juce application this will be set to the module handle
  13924. of the application executable.
  13925. If you're writing a DLL using Juce and plan to use any Juce messaging or
  13926. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  13927. to set the correct module handle in your DllMain() function, because
  13928. the win32 system relies on the correct instance handle when opening windows.
  13929. */
  13930. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() noexcept;
  13931. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  13932. @see getCurrentModuleInstanceHandle()
  13933. */
  13934. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) noexcept;
  13935. /** WIN32 ONLY - Gets the command-line params as a string.
  13936. This is needed to avoid unicode problems with the argc type params.
  13937. */
  13938. static String JUCE_CALLTYPE getCurrentCommandLineParams();
  13939. #endif
  13940. /** Clears the floating point unit's flags.
  13941. Only has an effect under win32, currently.
  13942. */
  13943. static void fpuReset();
  13944. #if JUCE_LINUX || JUCE_WINDOWS
  13945. /** Loads a dynamically-linked library into the process's address space.
  13946. @param pathOrFilename the platform-dependent name and search path
  13947. @returns a handle which can be used by getProcedureEntryPoint(), or
  13948. zero if it fails.
  13949. @see freeDynamicLibrary, getProcedureEntryPoint
  13950. */
  13951. static void* loadDynamicLibrary (const String& pathOrFilename);
  13952. /** Frees a dynamically-linked library.
  13953. @param libraryHandle a handle created by loadDynamicLibrary
  13954. @see loadDynamicLibrary, getProcedureEntryPoint
  13955. */
  13956. static void freeDynamicLibrary (void* libraryHandle);
  13957. /** Finds a procedure call in a dynamically-linked library.
  13958. @param libraryHandle a library handle returned by loadDynamicLibrary
  13959. @param procedureName the name of the procedure call to try to load
  13960. @returns a pointer to the function if found, or 0 if it fails
  13961. @see loadDynamicLibrary
  13962. */
  13963. static void* getProcedureEntryPoint (void* libraryHandle,
  13964. const String& procedureName);
  13965. #endif
  13966. private:
  13967. PlatformUtilities();
  13968. JUCE_DECLARE_NON_COPYABLE (PlatformUtilities);
  13969. };
  13970. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  13971. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object using RAII. */
  13972. class JUCE_API ScopedAutoReleasePool
  13973. {
  13974. public:
  13975. ScopedAutoReleasePool();
  13976. ~ScopedAutoReleasePool();
  13977. private:
  13978. void* pool;
  13979. JUCE_DECLARE_NON_COPYABLE (ScopedAutoReleasePool);
  13980. };
  13981. /** A macro that can be used to easily declare a local ScopedAutoReleasePool object for RAII-based obj-C autoreleasing. */
  13982. #define JUCE_AUTORELEASEPOOL const JUCE_NAMESPACE::ScopedAutoReleasePool JUCE_JOIN_MACRO (autoReleasePool_, __LINE__);
  13983. #else
  13984. #define JUCE_AUTORELEASEPOOL
  13985. #endif
  13986. #if JUCE_LINUX
  13987. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  13988. using an RAII approach.
  13989. */
  13990. class ScopedXLock
  13991. {
  13992. public:
  13993. /** Creating a ScopedXLock object locks the X display.
  13994. This uses XLockDisplay() to grab the display that Juce is using.
  13995. */
  13996. ScopedXLock();
  13997. /** Deleting a ScopedXLock object unlocks the X display.
  13998. This calls XUnlockDisplay() to release the lock.
  13999. */
  14000. ~ScopedXLock();
  14001. };
  14002. #endif
  14003. #if JUCE_MAC
  14004. /**
  14005. A wrapper class for picking up events from an Apple IR remote control device.
  14006. To use it, just create a subclass of this class, implementing the buttonPressed()
  14007. callback, then call start() and stop() to start or stop receiving events.
  14008. */
  14009. class JUCE_API AppleRemoteDevice
  14010. {
  14011. public:
  14012. AppleRemoteDevice();
  14013. virtual ~AppleRemoteDevice();
  14014. /** The set of buttons that may be pressed.
  14015. @see buttonPressed
  14016. */
  14017. enum ButtonType
  14018. {
  14019. menuButton = 0, /**< The menu button (if it's held for a short time). */
  14020. playButton, /**< The play button. */
  14021. plusButton, /**< The plus or volume-up button. */
  14022. minusButton, /**< The minus or volume-down button. */
  14023. rightButton, /**< The right button (if it's held for a short time). */
  14024. leftButton, /**< The left button (if it's held for a short time). */
  14025. rightButton_Long, /**< The right button (if it's held for a long time). */
  14026. leftButton_Long, /**< The menu button (if it's held for a long time). */
  14027. menuButton_Long, /**< The menu button (if it's held for a long time). */
  14028. playButtonSleepMode,
  14029. switched
  14030. };
  14031. /** Override this method to receive the callback about a button press.
  14032. The callback will happen on the application's message thread.
  14033. Some buttons trigger matching up and down events, in which the isDown parameter
  14034. will be true and then false. Others only send a single event when the
  14035. button is pressed.
  14036. */
  14037. virtual void buttonPressed (ButtonType buttonId, bool isDown) = 0;
  14038. /** Starts the device running and responding to events.
  14039. Returns true if it managed to open the device.
  14040. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  14041. and will not be available to any other part of the system. If
  14042. false, it will be shared with other apps.
  14043. @see stop
  14044. */
  14045. bool start (bool inExclusiveMode);
  14046. /** Stops the device running.
  14047. @see start
  14048. */
  14049. void stop();
  14050. /** Returns true if the device has been started successfully.
  14051. */
  14052. bool isActive() const;
  14053. /** Returns the ID number of the remote, if it has sent one.
  14054. */
  14055. int getRemoteId() const { return remoteId; }
  14056. /** @internal */
  14057. void handleCallbackInternal();
  14058. private:
  14059. void* device;
  14060. void* queue;
  14061. int remoteId;
  14062. bool open (bool openInExclusiveMode);
  14063. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AppleRemoteDevice);
  14064. };
  14065. #endif
  14066. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  14067. /*** End of inlined file: juce_PlatformUtilities.h ***/
  14068. #endif
  14069. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  14070. #endif
  14071. #ifndef __JUCE_RESULT_JUCEHEADER__
  14072. #endif
  14073. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  14074. /*** Start of inlined file: juce_Singleton.h ***/
  14075. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  14076. #define __JUCE_SINGLETON_JUCEHEADER__
  14077. /**
  14078. Macro to declare member variables and methods for a singleton class.
  14079. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  14080. to the class's definition.
  14081. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  14082. implementation code.
  14083. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  14084. destructor, in case it is deleted by other means than deleteInstance()
  14085. Clients can then call the static method MyClass::getInstance() to get a pointer
  14086. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  14087. no instance currently exists.
  14088. e.g. @code
  14089. class MySingleton
  14090. {
  14091. public:
  14092. MySingleton()
  14093. {
  14094. }
  14095. ~MySingleton()
  14096. {
  14097. // this ensures that no dangling pointers are left when the
  14098. // singleton is deleted.
  14099. clearSingletonInstance();
  14100. }
  14101. juce_DeclareSingleton (MySingleton, false)
  14102. };
  14103. juce_ImplementSingleton (MySingleton)
  14104. // example of usage:
  14105. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  14106. ...
  14107. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  14108. @endcode
  14109. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  14110. than once during the process's lifetime - i.e. after you've created and deleted the
  14111. object, getInstance() will refuse to create another one. This can be useful to stop
  14112. objects being accidentally re-created during your app's shutdown code.
  14113. If you know that your object will only be created and deleted by a single thread, you
  14114. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  14115. of this one.
  14116. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  14117. */
  14118. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  14119. \
  14120. static classname* _singletonInstance; \
  14121. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  14122. \
  14123. static classname* JUCE_CALLTYPE getInstance() \
  14124. { \
  14125. if (_singletonInstance == nullptr) \
  14126. {\
  14127. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  14128. \
  14129. if (_singletonInstance == nullptr) \
  14130. { \
  14131. static bool alreadyInside = false; \
  14132. static bool createdOnceAlready = false; \
  14133. \
  14134. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  14135. jassert (! problem); \
  14136. if (! problem) \
  14137. { \
  14138. createdOnceAlready = true; \
  14139. alreadyInside = true; \
  14140. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  14141. alreadyInside = false; \
  14142. \
  14143. _singletonInstance = newObject; \
  14144. } \
  14145. } \
  14146. } \
  14147. \
  14148. return _singletonInstance; \
  14149. } \
  14150. \
  14151. static inline classname* JUCE_CALLTYPE getInstanceWithoutCreating() noexcept\
  14152. { \
  14153. return _singletonInstance; \
  14154. } \
  14155. \
  14156. static void JUCE_CALLTYPE deleteInstance() \
  14157. { \
  14158. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  14159. if (_singletonInstance != nullptr) \
  14160. { \
  14161. classname* const old = _singletonInstance; \
  14162. _singletonInstance = nullptr; \
  14163. delete old; \
  14164. } \
  14165. } \
  14166. \
  14167. void clearSingletonInstance() noexcept\
  14168. { \
  14169. if (_singletonInstance == this) \
  14170. _singletonInstance = nullptr; \
  14171. }
  14172. /** This is a counterpart to the juce_DeclareSingleton macro.
  14173. After adding the juce_DeclareSingleton to the class definition, this macro has
  14174. to be used in the cpp file.
  14175. */
  14176. #define juce_ImplementSingleton(classname) \
  14177. \
  14178. classname* classname::_singletonInstance = nullptr; \
  14179. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  14180. /**
  14181. Macro to declare member variables and methods for a singleton class.
  14182. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  14183. section to make access to it thread-safe. If you know that your object will
  14184. only ever be created or deleted by a single thread, then this is a
  14185. more efficient version to use.
  14186. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  14187. than once during the process's lifetime - i.e. after you've created and deleted the
  14188. object, getInstance() will refuse to create another one. This can be useful to stop
  14189. objects being accidentally re-created during your app's shutdown code.
  14190. See the documentation for juce_DeclareSingleton for more information about
  14191. how to use it, the only difference being that you have to use
  14192. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  14193. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  14194. */
  14195. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  14196. \
  14197. static classname* _singletonInstance; \
  14198. \
  14199. static classname* getInstance() \
  14200. { \
  14201. if (_singletonInstance == nullptr) \
  14202. { \
  14203. static bool alreadyInside = false; \
  14204. static bool createdOnceAlready = false; \
  14205. \
  14206. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  14207. jassert (! problem); \
  14208. if (! problem) \
  14209. { \
  14210. createdOnceAlready = true; \
  14211. alreadyInside = true; \
  14212. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  14213. alreadyInside = false; \
  14214. \
  14215. _singletonInstance = newObject; \
  14216. } \
  14217. } \
  14218. \
  14219. return _singletonInstance; \
  14220. } \
  14221. \
  14222. static inline classname* getInstanceWithoutCreating() noexcept\
  14223. { \
  14224. return _singletonInstance; \
  14225. } \
  14226. \
  14227. static void deleteInstance() \
  14228. { \
  14229. if (_singletonInstance != nullptr) \
  14230. { \
  14231. classname* const old = _singletonInstance; \
  14232. _singletonInstance = nullptr; \
  14233. delete old; \
  14234. } \
  14235. } \
  14236. \
  14237. void clearSingletonInstance() noexcept\
  14238. { \
  14239. if (_singletonInstance == this) \
  14240. _singletonInstance = nullptr; \
  14241. }
  14242. /**
  14243. Macro to declare member variables and methods for a singleton class.
  14244. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  14245. for recursion or repeated instantiation. It's intended for use as a lightweight
  14246. version of a singleton, where you're using it in very straightforward
  14247. circumstances and don't need the extra checking.
  14248. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  14249. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  14250. See the documentation for juce_DeclareSingleton for more information about
  14251. how to use it, the only difference being that you have to use
  14252. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  14253. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  14254. */
  14255. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  14256. \
  14257. static classname* _singletonInstance; \
  14258. \
  14259. static classname* getInstance() \
  14260. { \
  14261. if (_singletonInstance == nullptr) \
  14262. _singletonInstance = new classname(); \
  14263. \
  14264. return _singletonInstance; \
  14265. } \
  14266. \
  14267. static inline classname* getInstanceWithoutCreating() noexcept\
  14268. { \
  14269. return _singletonInstance; \
  14270. } \
  14271. \
  14272. static void deleteInstance() \
  14273. { \
  14274. if (_singletonInstance != nullptr) \
  14275. { \
  14276. classname* const old = _singletonInstance; \
  14277. _singletonInstance = nullptr; \
  14278. delete old; \
  14279. } \
  14280. } \
  14281. \
  14282. void clearSingletonInstance() noexcept\
  14283. { \
  14284. if (_singletonInstance == this) \
  14285. _singletonInstance = nullptr; \
  14286. }
  14287. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  14288. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  14289. to the class definition, this macro has to be used somewhere in the cpp file.
  14290. */
  14291. #define juce_ImplementSingleton_SingleThreaded(classname) \
  14292. \
  14293. classname* classname::_singletonInstance = nullptr;
  14294. #endif // __JUCE_SINGLETON_JUCEHEADER__
  14295. /*** End of inlined file: juce_Singleton.h ***/
  14296. #endif
  14297. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  14298. #endif
  14299. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  14300. /*** Start of inlined file: juce_SystemStats.h ***/
  14301. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  14302. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  14303. /**
  14304. Contains methods for finding out about the current hardware and OS configuration.
  14305. */
  14306. class JUCE_API SystemStats
  14307. {
  14308. public:
  14309. /** Returns the current version of JUCE,
  14310. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  14311. */
  14312. static String getJUCEVersion();
  14313. /** The set of possible results of the getOperatingSystemType() method.
  14314. */
  14315. enum OperatingSystemType
  14316. {
  14317. UnknownOS = 0,
  14318. MacOSX = 0x1000,
  14319. Linux = 0x2000,
  14320. Android = 0x3000,
  14321. Win95 = 0x4001,
  14322. Win98 = 0x4002,
  14323. WinNT351 = 0x4103,
  14324. WinNT40 = 0x4104,
  14325. Win2000 = 0x4105,
  14326. WinXP = 0x4106,
  14327. WinVista = 0x4107,
  14328. Windows7 = 0x4108,
  14329. Windows = 0x4000, /**< To test whether any version of Windows is running,
  14330. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  14331. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  14332. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  14333. };
  14334. /** Returns the type of operating system we're running on.
  14335. @returns one of the values from the OperatingSystemType enum.
  14336. @see getOperatingSystemName
  14337. */
  14338. static OperatingSystemType getOperatingSystemType();
  14339. /** Returns the name of the type of operating system we're running on.
  14340. @returns a string describing the OS type.
  14341. @see getOperatingSystemType
  14342. */
  14343. static String getOperatingSystemName();
  14344. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  14345. */
  14346. static bool isOperatingSystem64Bit();
  14347. /** Returns the current user's name, if available.
  14348. @see getFullUserName()
  14349. */
  14350. static String getLogonName();
  14351. /** Returns the current user's full name, if available.
  14352. On some OSes, this may just return the same value as getLogonName().
  14353. @see getLogonName()
  14354. */
  14355. static String getFullUserName();
  14356. /** Returns the host-name of the computer. */
  14357. static String getComputerName();
  14358. // CPU and memory information..
  14359. /** Returns the approximate CPU speed.
  14360. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  14361. what year you're reading this...)
  14362. */
  14363. static int getCpuSpeedInMegaherz();
  14364. /** Returns a string to indicate the CPU vendor.
  14365. Might not be known on some systems.
  14366. */
  14367. static String getCpuVendor();
  14368. /** Checks whether Intel MMX instructions are available. */
  14369. static bool hasMMX() noexcept { return getCPUFlags().hasMMX; }
  14370. /** Checks whether Intel SSE instructions are available. */
  14371. static bool hasSSE() noexcept { return getCPUFlags().hasSSE; }
  14372. /** Checks whether Intel SSE2 instructions are available. */
  14373. static bool hasSSE2() noexcept { return getCPUFlags().hasSSE2; }
  14374. /** Checks whether AMD 3DNOW instructions are available. */
  14375. static bool has3DNow() noexcept { return getCPUFlags().has3DNow; }
  14376. /** Returns the number of CPUs. */
  14377. static int getNumCpus() noexcept { return getCPUFlags().numCpus; }
  14378. /** Finds out how much RAM is in the machine.
  14379. @returns the approximate number of megabytes of memory, or zero if
  14380. something goes wrong when finding out.
  14381. */
  14382. static int getMemorySizeInMegabytes();
  14383. /** Returns the system page-size.
  14384. This is only used by programmers with beards.
  14385. */
  14386. static int getPageSize();
  14387. private:
  14388. struct CPUFlags
  14389. {
  14390. CPUFlags();
  14391. int numCpus;
  14392. bool hasMMX : 1;
  14393. bool hasSSE : 1;
  14394. bool hasSSE2 : 1;
  14395. bool has3DNow : 1;
  14396. };
  14397. SystemStats();
  14398. static const CPUFlags& getCPUFlags();
  14399. JUCE_DECLARE_NON_COPYABLE (SystemStats);
  14400. };
  14401. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  14402. /*** End of inlined file: juce_SystemStats.h ***/
  14403. #endif
  14404. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  14405. #endif
  14406. #ifndef __JUCE_TIME_JUCEHEADER__
  14407. #endif
  14408. #ifndef __JUCE_UUID_JUCEHEADER__
  14409. /*** Start of inlined file: juce_Uuid.h ***/
  14410. #ifndef __JUCE_UUID_JUCEHEADER__
  14411. #define __JUCE_UUID_JUCEHEADER__
  14412. /**
  14413. A universally unique 128-bit identifier.
  14414. This class generates very random unique numbers based on the system time
  14415. and MAC addresses if any are available. It's extremely unlikely that two identical
  14416. UUIDs would ever be created by chance.
  14417. The class includes methods for saving the ID as a string or as raw binary data.
  14418. */
  14419. class JUCE_API Uuid
  14420. {
  14421. public:
  14422. /** Creates a new unique ID. */
  14423. Uuid();
  14424. /** Destructor. */
  14425. ~Uuid() noexcept;
  14426. /** Creates a copy of another UUID. */
  14427. Uuid (const Uuid& other);
  14428. /** Copies another UUID. */
  14429. Uuid& operator= (const Uuid& other);
  14430. /** Returns true if the ID is zero. */
  14431. bool isNull() const noexcept;
  14432. /** Compares two UUIDs. */
  14433. bool operator== (const Uuid& other) const;
  14434. /** Compares two UUIDs. */
  14435. bool operator!= (const Uuid& other) const;
  14436. /** Returns a stringified version of this UUID.
  14437. A Uuid object can later be reconstructed from this string using operator= or
  14438. the constructor that takes a string parameter.
  14439. @returns a 32 character hex string.
  14440. */
  14441. String toString() const;
  14442. /** Creates an ID from an encoded string version.
  14443. @see toString
  14444. */
  14445. Uuid (const String& uuidString);
  14446. /** Copies from a stringified UUID.
  14447. The string passed in should be one that was created with the toString() method.
  14448. */
  14449. Uuid& operator= (const String& uuidString);
  14450. /** Returns a pointer to the internal binary representation of the ID.
  14451. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  14452. the constructor or operator= method that takes an array of uint8s.
  14453. */
  14454. const uint8* getRawData() const noexcept { return value.asBytes; }
  14455. /** Creates a UUID from a 16-byte array.
  14456. @see getRawData
  14457. */
  14458. Uuid (const uint8* rawData);
  14459. /** Sets this UUID from 16-bytes of raw data. */
  14460. Uuid& operator= (const uint8* rawData);
  14461. private:
  14462. #ifndef DOXYGEN
  14463. union
  14464. {
  14465. uint8 asBytes [16];
  14466. int asInt[4];
  14467. int64 asInt64[2];
  14468. } value;
  14469. #endif
  14470. JUCE_LEAK_DETECTOR (Uuid);
  14471. };
  14472. #endif // __JUCE_UUID_JUCEHEADER__
  14473. /*** End of inlined file: juce_Uuid.h ***/
  14474. #endif
  14475. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  14476. /*** Start of inlined file: juce_BlowFish.h ***/
  14477. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  14478. #define __JUCE_BLOWFISH_JUCEHEADER__
  14479. /**
  14480. BlowFish encryption class.
  14481. */
  14482. class JUCE_API BlowFish
  14483. {
  14484. public:
  14485. /** Creates an object that can encode/decode based on the specified key.
  14486. The key data can be up to 72 bytes long.
  14487. */
  14488. BlowFish (const void* keyData, int keyBytes);
  14489. /** Creates a copy of another blowfish object. */
  14490. BlowFish (const BlowFish& other);
  14491. /** Copies another blowfish object. */
  14492. BlowFish& operator= (const BlowFish& other);
  14493. /** Destructor. */
  14494. ~BlowFish();
  14495. /** Encrypts a pair of 32-bit integers. */
  14496. void encrypt (uint32& data1, uint32& data2) const noexcept;
  14497. /** Decrypts a pair of 32-bit integers. */
  14498. void decrypt (uint32& data1, uint32& data2) const noexcept;
  14499. private:
  14500. uint32 p[18];
  14501. HeapBlock <uint32> s[4];
  14502. uint32 F (uint32 x) const noexcept;
  14503. JUCE_LEAK_DETECTOR (BlowFish);
  14504. };
  14505. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  14506. /*** End of inlined file: juce_BlowFish.h ***/
  14507. #endif
  14508. #ifndef __JUCE_MD5_JUCEHEADER__
  14509. /*** Start of inlined file: juce_MD5.h ***/
  14510. #ifndef __JUCE_MD5_JUCEHEADER__
  14511. #define __JUCE_MD5_JUCEHEADER__
  14512. /**
  14513. MD5 checksum class.
  14514. Create one of these with a block of source data or a string, and it calculates the
  14515. MD5 checksum of that data.
  14516. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  14517. */
  14518. class JUCE_API MD5
  14519. {
  14520. public:
  14521. /** Creates a null MD5 object. */
  14522. MD5();
  14523. /** Creates a copy of another MD5. */
  14524. MD5 (const MD5& other);
  14525. /** Copies another MD5. */
  14526. MD5& operator= (const MD5& other);
  14527. /** Creates a checksum for a block of binary data. */
  14528. explicit MD5 (const MemoryBlock& data);
  14529. /** Creates a checksum for a block of binary data. */
  14530. MD5 (const void* data, size_t numBytes);
  14531. /** Creates a checksum for a string.
  14532. Note that this operates on the string as a block of unicode characters, so the
  14533. result you get will differ from the value you'd get if the string was treated
  14534. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  14535. of this method with a checksum created by a different framework, which may have
  14536. used a different encoding.
  14537. */
  14538. explicit MD5 (const String& text);
  14539. /** Creates a checksum for the input from a stream.
  14540. This will read up to the given number of bytes from the stream, and produce the
  14541. checksum of that. If the number of bytes to read is negative, it'll read
  14542. until the stream is exhausted.
  14543. */
  14544. MD5 (InputStream& input, int64 numBytesToRead = -1);
  14545. /** Creates a checksum for a file. */
  14546. explicit MD5 (const File& file);
  14547. /** Destructor. */
  14548. ~MD5();
  14549. /** Returns the checksum as a 16-byte block of data. */
  14550. MemoryBlock getRawChecksumData() const;
  14551. /** Returns the checksum as a 32-digit hex string. */
  14552. String toHexString() const;
  14553. /** Compares this to another MD5. */
  14554. bool operator== (const MD5& other) const;
  14555. /** Compares this to another MD5. */
  14556. bool operator!= (const MD5& other) const;
  14557. private:
  14558. uint8 result [16];
  14559. struct ProcessContext
  14560. {
  14561. uint8 buffer [64];
  14562. uint32 state [4];
  14563. uint32 count [2];
  14564. ProcessContext();
  14565. void processBlock (const void* data, size_t dataSize);
  14566. void transform (const void* buffer);
  14567. void finish (void* result);
  14568. };
  14569. void processStream (InputStream&, int64 numBytesToRead);
  14570. JUCE_LEAK_DETECTOR (MD5);
  14571. };
  14572. #endif // __JUCE_MD5_JUCEHEADER__
  14573. /*** End of inlined file: juce_MD5.h ***/
  14574. #endif
  14575. #ifndef __JUCE_PRIMES_JUCEHEADER__
  14576. /*** Start of inlined file: juce_Primes.h ***/
  14577. #ifndef __JUCE_PRIMES_JUCEHEADER__
  14578. #define __JUCE_PRIMES_JUCEHEADER__
  14579. /*** Start of inlined file: juce_BigInteger.h ***/
  14580. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  14581. #define __JUCE_BIGINTEGER_JUCEHEADER__
  14582. class MemoryBlock;
  14583. /**
  14584. An arbitrarily large integer class.
  14585. A BigInteger can be used in a similar way to a normal integer, but has no size
  14586. limit (except for memory and performance constraints).
  14587. Negative values are possible, but the value isn't stored as 2s-complement, so
  14588. be careful if you use negative values and look at the values of individual bits.
  14589. */
  14590. class JUCE_API BigInteger
  14591. {
  14592. public:
  14593. /** Creates an empty BigInteger */
  14594. BigInteger();
  14595. /** Creates a BigInteger containing an integer value in its low bits.
  14596. The low 32 bits of the number are initialised with this value.
  14597. */
  14598. BigInteger (uint32 value);
  14599. /** Creates a BigInteger containing an integer value in its low bits.
  14600. The low 32 bits of the number are initialised with the absolute value
  14601. passed in, and its sign is set to reflect the sign of the number.
  14602. */
  14603. BigInteger (int32 value);
  14604. /** Creates a BigInteger containing an integer value in its low bits.
  14605. The low 64 bits of the number are initialised with the absolute value
  14606. passed in, and its sign is set to reflect the sign of the number.
  14607. */
  14608. BigInteger (int64 value);
  14609. /** Creates a copy of another BigInteger. */
  14610. BigInteger (const BigInteger& other);
  14611. /** Destructor. */
  14612. ~BigInteger();
  14613. /** Copies another BigInteger onto this one. */
  14614. BigInteger& operator= (const BigInteger& other);
  14615. /** Swaps the internal contents of this with another object. */
  14616. void swapWith (BigInteger& other) noexcept;
  14617. /** Returns the value of a specified bit in the number.
  14618. If the index is out-of-range, the result will be false.
  14619. */
  14620. bool operator[] (int bit) const noexcept;
  14621. /** Returns true if no bits are set. */
  14622. bool isZero() const noexcept;
  14623. /** Returns true if the value is 1. */
  14624. bool isOne() const noexcept;
  14625. /** Attempts to get the lowest bits of the value as an integer.
  14626. If the value is bigger than the integer limits, this will return only the lower bits.
  14627. */
  14628. int toInteger() const noexcept;
  14629. /** Resets the value to 0. */
  14630. void clear();
  14631. /** Clears a particular bit in the number. */
  14632. void clearBit (int bitNumber) noexcept;
  14633. /** Sets a specified bit to 1. */
  14634. void setBit (int bitNumber);
  14635. /** Sets or clears a specified bit. */
  14636. void setBit (int bitNumber, bool shouldBeSet);
  14637. /** Sets a range of bits to be either on or off.
  14638. @param startBit the first bit to change
  14639. @param numBits the number of bits to change
  14640. @param shouldBeSet whether to turn these bits on or off
  14641. */
  14642. void setRange (int startBit, int numBits, bool shouldBeSet);
  14643. /** Inserts a bit an a given position, shifting up any bits above it. */
  14644. void insertBit (int bitNumber, bool shouldBeSet);
  14645. /** Returns a range of bits as a new BigInteger.
  14646. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  14647. @see getBitRangeAsInt
  14648. */
  14649. BigInteger getBitRange (int startBit, int numBits) const;
  14650. /** Returns a range of bits as an integer value.
  14651. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  14652. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  14653. getBitRange().
  14654. */
  14655. int getBitRangeAsInt (int startBit, int numBits) const noexcept;
  14656. /** Sets a range of bits to an integer value.
  14657. Copies the given integer onto a range of bits, starting at startBit,
  14658. and using up to numBits of the available bits.
  14659. */
  14660. void setBitRangeAsInt (int startBit, int numBits, uint32 valueToSet);
  14661. /** Shifts a section of bits left or right.
  14662. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  14663. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  14664. */
  14665. void shiftBits (int howManyBitsLeft, int startBit);
  14666. /** Returns the total number of set bits in the value. */
  14667. int countNumberOfSetBits() const noexcept;
  14668. /** Looks for the index of the next set bit after a given starting point.
  14669. This searches from startIndex (inclusive) upwards for the first set bit,
  14670. and returns its index. If no set bits are found, it returns -1.
  14671. */
  14672. int findNextSetBit (int startIndex = 0) const noexcept;
  14673. /** Looks for the index of the next clear bit after a given starting point.
  14674. This searches from startIndex (inclusive) upwards for the first clear bit,
  14675. and returns its index.
  14676. */
  14677. int findNextClearBit (int startIndex = 0) const noexcept;
  14678. /** Returns the index of the highest set bit in the number.
  14679. If the value is zero, this will return -1.
  14680. */
  14681. int getHighestBit() const noexcept;
  14682. // All the standard arithmetic ops...
  14683. BigInteger& operator+= (const BigInteger& other);
  14684. BigInteger& operator-= (const BigInteger& other);
  14685. BigInteger& operator*= (const BigInteger& other);
  14686. BigInteger& operator/= (const BigInteger& other);
  14687. BigInteger& operator|= (const BigInteger& other);
  14688. BigInteger& operator&= (const BigInteger& other);
  14689. BigInteger& operator^= (const BigInteger& other);
  14690. BigInteger& operator%= (const BigInteger& other);
  14691. BigInteger& operator<<= (int numBitsToShift);
  14692. BigInteger& operator>>= (int numBitsToShift);
  14693. BigInteger& operator++();
  14694. BigInteger& operator--();
  14695. BigInteger operator++ (int);
  14696. BigInteger operator-- (int);
  14697. BigInteger operator-() const;
  14698. BigInteger operator+ (const BigInteger& other) const;
  14699. BigInteger operator- (const BigInteger& other) const;
  14700. BigInteger operator* (const BigInteger& other) const;
  14701. BigInteger operator/ (const BigInteger& other) const;
  14702. BigInteger operator| (const BigInteger& other) const;
  14703. BigInteger operator& (const BigInteger& other) const;
  14704. BigInteger operator^ (const BigInteger& other) const;
  14705. BigInteger operator% (const BigInteger& other) const;
  14706. BigInteger operator<< (int numBitsToShift) const;
  14707. BigInteger operator>> (int numBitsToShift) const;
  14708. bool operator== (const BigInteger& other) const noexcept;
  14709. bool operator!= (const BigInteger& other) const noexcept;
  14710. bool operator< (const BigInteger& other) const noexcept;
  14711. bool operator<= (const BigInteger& other) const noexcept;
  14712. bool operator> (const BigInteger& other) const noexcept;
  14713. bool operator>= (const BigInteger& other) const noexcept;
  14714. /** Does a signed comparison of two BigIntegers.
  14715. Return values are:
  14716. - 0 if the numbers are the same
  14717. - < 0 if this number is smaller than the other
  14718. - > 0 if this number is bigger than the other
  14719. */
  14720. int compare (const BigInteger& other) const noexcept;
  14721. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  14722. Return values are:
  14723. - 0 if the numbers are the same
  14724. - < 0 if this number is smaller than the other
  14725. - > 0 if this number is bigger than the other
  14726. */
  14727. int compareAbsolute (const BigInteger& other) const noexcept;
  14728. /** Divides this value by another one and returns the remainder.
  14729. This number is divided by other, leaving the quotient in this number,
  14730. with the remainder being copied to the other BigInteger passed in.
  14731. */
  14732. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  14733. /** Returns the largest value that will divide both this value and the one passed-in.
  14734. */
  14735. BigInteger findGreatestCommonDivisor (BigInteger other) const;
  14736. /** Performs a combined exponent and modulo operation.
  14737. This BigInteger's value becomes (this ^ exponent) % modulus.
  14738. */
  14739. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  14740. /** Performs an inverse modulo on the value.
  14741. i.e. the result is (this ^ -1) mod (modulus).
  14742. */
  14743. void inverseModulo (const BigInteger& modulus);
  14744. /** Returns true if the value is less than zero.
  14745. @see setNegative, negate
  14746. */
  14747. bool isNegative() const noexcept;
  14748. /** Changes the sign of the number to be positive or negative.
  14749. @see isNegative, negate
  14750. */
  14751. void setNegative (bool shouldBeNegative) noexcept;
  14752. /** Inverts the sign of the number.
  14753. @see isNegative, setNegative
  14754. */
  14755. void negate() noexcept;
  14756. /** Converts the number to a string.
  14757. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14758. If minimumNumCharacters is greater than 0, the returned string will be
  14759. padded with leading zeros to reach at least that length.
  14760. */
  14761. String toString (int base, int minimumNumCharacters = 1) const;
  14762. /** Reads the numeric value from a string.
  14763. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14764. Any invalid characters will be ignored.
  14765. */
  14766. void parseString (const String& text, int base);
  14767. /** Turns the number into a block of binary data.
  14768. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14769. of the number, and so on.
  14770. @see loadFromMemoryBlock
  14771. */
  14772. MemoryBlock toMemoryBlock() const;
  14773. /** Converts a block of raw data into a number.
  14774. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14775. of the number, and so on.
  14776. @see toMemoryBlock
  14777. */
  14778. void loadFromMemoryBlock (const MemoryBlock& data);
  14779. private:
  14780. HeapBlock <uint32> values;
  14781. int numValues, highestBit;
  14782. bool negative;
  14783. void ensureSize (int numVals);
  14784. void shiftLeft (int bits, int startBit);
  14785. void shiftRight (int bits, int startBit);
  14786. static BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  14787. static inline int bitToIndex (const int bit) noexcept { return bit >> 5; }
  14788. static inline uint32 bitToMask (const int bit) noexcept { return 1 << (bit & 31); }
  14789. JUCE_LEAK_DETECTOR (BigInteger);
  14790. };
  14791. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  14792. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  14793. #ifndef DOXYGEN
  14794. // For backwards compatibility, BitArray is defined as an alias for BigInteger.
  14795. typedef BigInteger BitArray;
  14796. #endif
  14797. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  14798. /*** End of inlined file: juce_BigInteger.h ***/
  14799. /**
  14800. Prime number creation class.
  14801. This class contains static methods for generating and testing prime numbers.
  14802. @see BigInteger
  14803. */
  14804. class JUCE_API Primes
  14805. {
  14806. public:
  14807. /** Creates a random prime number with a given bit-length.
  14808. The certainty parameter specifies how many iterations to use when testing
  14809. for primality. A safe value might be anything over about 20-30.
  14810. The randomSeeds parameter lets you optionally pass it a set of values with
  14811. which to seed the random number generation, improving the security of the
  14812. keys generated.
  14813. */
  14814. static BigInteger createProbablePrime (int bitLength,
  14815. int certainty,
  14816. const int* randomSeeds = 0,
  14817. int numRandomSeeds = 0);
  14818. /** Tests a number to see if it's prime.
  14819. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  14820. whether the number is prime.
  14821. The certainty parameter specifies how many iterations to use when testing - a
  14822. safe value might be anything over about 20-30.
  14823. */
  14824. static bool isProbablyPrime (const BigInteger& number, int certainty);
  14825. private:
  14826. Primes();
  14827. JUCE_DECLARE_NON_COPYABLE (Primes);
  14828. };
  14829. #endif // __JUCE_PRIMES_JUCEHEADER__
  14830. /*** End of inlined file: juce_Primes.h ***/
  14831. #endif
  14832. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14833. /*** Start of inlined file: juce_RSAKey.h ***/
  14834. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14835. #define __JUCE_RSAKEY_JUCEHEADER__
  14836. /**
  14837. RSA public/private key-pair encryption class.
  14838. An object of this type makes up one half of a public/private RSA key pair. Use the
  14839. createKeyPair() method to create a matching pair for encoding/decoding.
  14840. */
  14841. class JUCE_API RSAKey
  14842. {
  14843. public:
  14844. /** Creates a null key object.
  14845. Initialise a pair of objects for use with the createKeyPair() method.
  14846. */
  14847. RSAKey();
  14848. /** Loads a key from an encoded string representation.
  14849. This reloads a key from a string created by the toString() method.
  14850. */
  14851. explicit RSAKey (const String& stringRepresentation);
  14852. /** Destructor. */
  14853. ~RSAKey();
  14854. bool operator== (const RSAKey& other) const noexcept;
  14855. bool operator!= (const RSAKey& other) const noexcept;
  14856. /** Turns the key into a string representation.
  14857. This can be reloaded using the constructor that takes a string.
  14858. */
  14859. String toString() const;
  14860. /** Encodes or decodes a value.
  14861. Call this on the public key object to encode some data, then use the matching
  14862. private key object to decode it.
  14863. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  14864. initialised correctly.
  14865. NOTE: This method dumbly applies this key to this data. If you encode some data
  14866. and then try to decode it with a key that doesn't match, this method will still
  14867. happily do its job and return true, but the result won't be what you were expecting.
  14868. It's your responsibility to check that the result is what you wanted.
  14869. */
  14870. bool applyToValue (BigInteger& value) const;
  14871. /** Creates a public/private key-pair.
  14872. Each key will perform one-way encryption that can only be reversed by
  14873. using the other key.
  14874. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  14875. sizes are more secure, but this method will take longer to execute.
  14876. The randomSeeds parameter lets you optionally pass it a set of values with
  14877. which to seed the random number generation, improving the security of the
  14878. keys generated. If you supply these, make sure you provide more than 2 values,
  14879. and the more your provide, the better the security.
  14880. */
  14881. static void createKeyPair (RSAKey& publicKey,
  14882. RSAKey& privateKey,
  14883. int numBits,
  14884. const int* randomSeeds = nullptr,
  14885. int numRandomSeeds = 0);
  14886. protected:
  14887. BigInteger part1, part2;
  14888. private:
  14889. static BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q);
  14890. JUCE_LEAK_DETECTOR (RSAKey);
  14891. };
  14892. #endif // __JUCE_RSAKEY_JUCEHEADER__
  14893. /*** End of inlined file: juce_RSAKey.h ***/
  14894. #endif
  14895. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14896. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  14897. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14898. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14899. /**
  14900. Searches through a the files in a directory, returning each file that is found.
  14901. A DirectoryIterator will search through a directory and its subdirectories using
  14902. a wildcard filepattern match.
  14903. If you may be finding a large number of files, this is better than
  14904. using File::findChildFiles() because it doesn't block while it finds them
  14905. all, and this is more memory-efficient.
  14906. It can also guess how far it's got using a wildly inaccurate algorithm.
  14907. */
  14908. class JUCE_API DirectoryIterator
  14909. {
  14910. public:
  14911. /** Creates a DirectoryIterator for a given directory.
  14912. After creating one of these, call its next() method to get the
  14913. first file - e.g. @code
  14914. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  14915. while (iter.next())
  14916. {
  14917. File theFileItFound (iter.getFile());
  14918. ... etc
  14919. }
  14920. @endcode
  14921. @param directory the directory to search in
  14922. @param isRecursive whether all the subdirectories should also be searched
  14923. @param wildCard the file pattern to match
  14924. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  14925. whether to look for files, directories, or both.
  14926. */
  14927. DirectoryIterator (const File& directory,
  14928. bool isRecursive,
  14929. const String& wildCard = "*",
  14930. int whatToLookFor = File::findFiles);
  14931. /** Destructor. */
  14932. ~DirectoryIterator();
  14933. /** Moves the iterator along to the next file.
  14934. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14935. false if there are no more matching files.
  14936. */
  14937. bool next();
  14938. /** Moves the iterator along to the next file, and returns various properties of that file.
  14939. If you need to find out details about the file, it's more efficient to call this method than
  14940. to call the normal next() method and then find out the details afterwards.
  14941. All the parameters are optional, so pass null pointers for any items that you're not
  14942. interested in.
  14943. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14944. false if there are no more matching files. If it returns false, then none of the
  14945. parameters will be filled-in.
  14946. */
  14947. bool next (bool* isDirectory,
  14948. bool* isHidden,
  14949. int64* fileSize,
  14950. Time* modTime,
  14951. Time* creationTime,
  14952. bool* isReadOnly);
  14953. /** Returns the file that the iterator is currently pointing at.
  14954. The result of this call is only valid after a call to next() has returned true.
  14955. */
  14956. const File& getFile() const;
  14957. /** Returns a guess of how far through the search the iterator has got.
  14958. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  14959. very accurate.
  14960. */
  14961. float getEstimatedProgress() const;
  14962. private:
  14963. class NativeIterator
  14964. {
  14965. public:
  14966. NativeIterator (const File& directory, const String& wildCard);
  14967. ~NativeIterator();
  14968. bool next (String& filenameFound,
  14969. bool* isDirectory, bool* isHidden, int64* fileSize,
  14970. Time* modTime, Time* creationTime, bool* isReadOnly);
  14971. class Pimpl;
  14972. private:
  14973. friend class DirectoryIterator;
  14974. friend class ScopedPointer<Pimpl>;
  14975. ScopedPointer<Pimpl> pimpl;
  14976. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeIterator);
  14977. };
  14978. friend class ScopedPointer<NativeIterator::Pimpl>;
  14979. NativeIterator fileFinder;
  14980. String wildCard, path;
  14981. int index;
  14982. mutable int totalNumFiles;
  14983. const int whatToLookFor;
  14984. const bool isRecursive;
  14985. bool hasBeenAdvanced;
  14986. ScopedPointer <DirectoryIterator> subIterator;
  14987. File currentFile;
  14988. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryIterator);
  14989. };
  14990. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14991. /*** End of inlined file: juce_DirectoryIterator.h ***/
  14992. #endif
  14993. #ifndef __JUCE_FILE_JUCEHEADER__
  14994. #endif
  14995. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14996. /*** Start of inlined file: juce_FileInputStream.h ***/
  14997. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14998. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14999. /**
  15000. An input stream that reads from a local file.
  15001. @see InputStream, FileOutputStream, File::createInputStream
  15002. */
  15003. class JUCE_API FileInputStream : public InputStream
  15004. {
  15005. public:
  15006. /** Creates a FileInputStream.
  15007. @param fileToRead the file to read from - if the file can't be accessed for some
  15008. reason, then the stream will just contain no data
  15009. */
  15010. explicit FileInputStream (const File& fileToRead);
  15011. /** Destructor. */
  15012. ~FileInputStream();
  15013. /** Returns the file that this stream is reading from. */
  15014. const File& getFile() const noexcept { return file; }
  15015. /** Returns the status of the file stream.
  15016. The result will be ok if the file opened successfully. If an error occurs while
  15017. opening or reading from the file, this will contain an error message.
  15018. */
  15019. Result getStatus() const { return status; }
  15020. int64 getTotalLength();
  15021. int read (void* destBuffer, int maxBytesToRead);
  15022. bool isExhausted();
  15023. int64 getPosition();
  15024. bool setPosition (int64 pos);
  15025. private:
  15026. File file;
  15027. void* fileHandle;
  15028. int64 currentPosition, totalSize;
  15029. Result status;
  15030. bool needToSeek;
  15031. void openHandle();
  15032. void closeHandle();
  15033. size_t readInternal (void* buffer, size_t numBytes);
  15034. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputStream);
  15035. };
  15036. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  15037. /*** End of inlined file: juce_FileInputStream.h ***/
  15038. #endif
  15039. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  15040. /*** Start of inlined file: juce_FileOutputStream.h ***/
  15041. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  15042. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  15043. /**
  15044. An output stream that writes into a local file.
  15045. @see OutputStream, FileInputStream, File::createOutputStream
  15046. */
  15047. class JUCE_API FileOutputStream : public OutputStream
  15048. {
  15049. public:
  15050. /** Creates a FileOutputStream.
  15051. If the file doesn't exist, it will first be created. If the file can't be
  15052. created or opened, the failedToOpen() method will return
  15053. true.
  15054. If the file already exists when opened, the stream's write-postion will
  15055. be set to the end of the file. To overwrite an existing file,
  15056. use File::deleteFile() before opening the stream, or use setPosition(0)
  15057. after it's opened (although this won't truncate the file).
  15058. It's better to use File::createOutputStream() to create one of these, rather
  15059. than using the class directly.
  15060. @see TemporaryFile
  15061. */
  15062. FileOutputStream (const File& fileToWriteTo,
  15063. int bufferSizeToUse = 16384);
  15064. /** Destructor. */
  15065. ~FileOutputStream();
  15066. /** Returns the file that this stream is writing to.
  15067. */
  15068. const File& getFile() const { return file; }
  15069. /** Returns the status of the file stream.
  15070. The result will be ok if the file opened successfully. If an error occurs while
  15071. opening or writing to the file, this will contain an error message.
  15072. */
  15073. Result getStatus() const { return status; }
  15074. /** Returns true if the stream couldn't be opened for some reason.
  15075. @see getResult()
  15076. */
  15077. bool failedToOpen() const { return status.failed(); }
  15078. void flush();
  15079. int64 getPosition();
  15080. bool setPosition (int64 pos);
  15081. bool write (const void* data, int numBytes);
  15082. void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  15083. private:
  15084. File file;
  15085. void* fileHandle;
  15086. Result status;
  15087. int64 currentPosition;
  15088. int bufferSize, bytesInBuffer;
  15089. HeapBlock <char> buffer;
  15090. void openHandle();
  15091. void closeHandle();
  15092. void flushInternal();
  15093. bool flushBuffer();
  15094. int64 setPositionInternal (int64 newPosition);
  15095. int writeInternal (const void* data, int numBytes);
  15096. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileOutputStream);
  15097. };
  15098. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  15099. /*** End of inlined file: juce_FileOutputStream.h ***/
  15100. #endif
  15101. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  15102. /*** Start of inlined file: juce_FileSearchPath.h ***/
  15103. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  15104. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  15105. /**
  15106. Encapsulates a set of folders that make up a search path.
  15107. @see File
  15108. */
  15109. class JUCE_API FileSearchPath
  15110. {
  15111. public:
  15112. /** Creates an empty search path. */
  15113. FileSearchPath();
  15114. /** Creates a search path from a string of pathnames.
  15115. The path can be semicolon- or comma-separated, e.g.
  15116. "/foo/bar;/foo/moose;/fish/moose"
  15117. The separate folders are tokenised and added to the search path.
  15118. */
  15119. FileSearchPath (const String& path);
  15120. /** Creates a copy of another search path. */
  15121. FileSearchPath (const FileSearchPath& other);
  15122. /** Destructor. */
  15123. ~FileSearchPath();
  15124. /** Uses a string containing a list of pathnames to re-initialise this list.
  15125. This search path is cleared and the semicolon- or comma-separated folders
  15126. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  15127. */
  15128. FileSearchPath& operator= (const String& path);
  15129. /** Returns the number of folders in this search path.
  15130. @see operator[]
  15131. */
  15132. int getNumPaths() const;
  15133. /** Returns one of the folders in this search path.
  15134. The file returned isn't guaranteed to actually be a valid directory.
  15135. @see getNumPaths
  15136. */
  15137. File operator[] (int index) const;
  15138. /** Returns the search path as a semicolon-separated list of directories. */
  15139. String toString() const;
  15140. /** Adds a new directory to the search path.
  15141. The new directory is added to the end of the list if the insertIndex parameter is
  15142. less than zero, otherwise it is inserted at the given index.
  15143. */
  15144. void add (const File& directoryToAdd,
  15145. int insertIndex = -1);
  15146. /** Adds a new directory to the search path if it's not already in there. */
  15147. void addIfNotAlreadyThere (const File& directoryToAdd);
  15148. /** Removes a directory from the search path. */
  15149. void remove (int indexToRemove);
  15150. /** Merges another search path into this one.
  15151. This will remove any duplicate directories.
  15152. */
  15153. void addPath (const FileSearchPath& other);
  15154. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  15155. If the search is intended to be recursive, there's no point having nested folders in the search
  15156. path, because they'll just get searched twice and you'll get duplicate results.
  15157. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  15158. */
  15159. void removeRedundantPaths();
  15160. /** Removes any directories that don't actually exist. */
  15161. void removeNonExistentPaths();
  15162. /** Searches the path for a wildcard.
  15163. This will search all the directories in the search path in order, adding any
  15164. matching files to the results array.
  15165. @param results an array to append the results to
  15166. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  15167. return files, directories, or both.
  15168. @param searchRecursively whether to recursively search the subdirectories too
  15169. @param wildCardPattern a pattern to match against the filenames
  15170. @returns the number of files added to the array
  15171. @see File::findChildFiles
  15172. */
  15173. int findChildFiles (Array<File>& results,
  15174. int whatToLookFor,
  15175. bool searchRecursively,
  15176. const String& wildCardPattern = "*") const;
  15177. /** Finds out whether a file is inside one of the path's directories.
  15178. This will return true if the specified file is a child of one of the
  15179. directories specified by this path. Note that this doesn't actually do any
  15180. searching or check that the files exist - it just looks at the pathnames
  15181. to work out whether the file would be inside a directory.
  15182. @param fileToCheck the file to look for
  15183. @param checkRecursively if true, then this will return true if the file is inside a
  15184. subfolder of one of the path's directories (at any depth). If false
  15185. it will only return true if the file is actually a direct child
  15186. of one of the directories.
  15187. @see File::isAChildOf
  15188. */
  15189. bool isFileInPath (const File& fileToCheck,
  15190. bool checkRecursively) const;
  15191. private:
  15192. StringArray directories;
  15193. void init (const String& path);
  15194. JUCE_LEAK_DETECTOR (FileSearchPath);
  15195. };
  15196. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  15197. /*** End of inlined file: juce_FileSearchPath.h ***/
  15198. #endif
  15199. #ifndef __JUCE_MEMORYMAPPEDFILE_JUCEHEADER__
  15200. /*** Start of inlined file: juce_MemoryMappedFile.h ***/
  15201. #ifndef __JUCE_MEMORYMAPPEDFILE_JUCEHEADER__
  15202. #define __JUCE_MEMORYMAPPEDFILE_JUCEHEADER__
  15203. /**
  15204. Maps a file into virtual memory for easy reading and/or writing.
  15205. */
  15206. class JUCE_API MemoryMappedFile
  15207. {
  15208. public:
  15209. /** The read/write flags used when opening a memory mapped file. */
  15210. enum AccessMode
  15211. {
  15212. readOnly, /**< Indicates that the memory can only be read. */
  15213. readWrite /**< Indicates that the memory can be read and written to - changes that are
  15214. made will be flushed back to disk at the whim of the OS. */
  15215. };
  15216. /** Opens a file and maps it to an area of virtual memory.
  15217. The file should already exist, and should already be the size that you want to work with
  15218. when you call this. If the file is resized after being opened, the behaviour is undefined.
  15219. If the file exists and the operation succeeds, the getData() and getSize() methods will
  15220. return the location and size of the data that can be read or written. Note that the entire
  15221. file is not read into memory immediately - the OS simply creates a virtual mapping, which
  15222. will lazily pull the data into memory when blocks are accessed.
  15223. If the file can't be opened for some reason, the getData() method will return a null pointer.
  15224. */
  15225. MemoryMappedFile (const File& file, AccessMode mode);
  15226. /** Destructor. */
  15227. ~MemoryMappedFile();
  15228. /** Returns the address at which this file has been mapped, or a null pointer if
  15229. the file couldn't be successfully mapped.
  15230. */
  15231. void* getData() const noexcept { return address; }
  15232. /** Returns the number of bytes of data that are available for reading or writing.
  15233. This will normally be the size of the file.
  15234. */
  15235. size_t getSize() const noexcept { return length; }
  15236. private:
  15237. void* address;
  15238. size_t length;
  15239. #if JUCE_WINDOWS
  15240. void* fileHandle;
  15241. #else
  15242. int fileHandle;
  15243. #endif
  15244. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryMappedFile);
  15245. };
  15246. #endif // __JUCE_MEMORYMAPPEDFILE_JUCEHEADER__
  15247. /*** End of inlined file: juce_MemoryMappedFile.h ***/
  15248. #endif
  15249. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  15250. /*** Start of inlined file: juce_NamedPipe.h ***/
  15251. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  15252. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  15253. /**
  15254. A cross-process pipe that can have data written to and read from it.
  15255. Two or more processes can use these for inter-process communication.
  15256. @see InterprocessConnection
  15257. */
  15258. class JUCE_API NamedPipe
  15259. {
  15260. public:
  15261. /** Creates a NamedPipe. */
  15262. NamedPipe();
  15263. /** Destructor. */
  15264. ~NamedPipe();
  15265. /** Tries to open a pipe that already exists.
  15266. Returns true if it succeeds.
  15267. */
  15268. bool openExisting (const String& pipeName);
  15269. /** Tries to create a new pipe.
  15270. Returns true if it succeeds.
  15271. */
  15272. bool createNewPipe (const String& pipeName);
  15273. /** Closes the pipe, if it's open. */
  15274. void close();
  15275. /** True if the pipe is currently open. */
  15276. bool isOpen() const;
  15277. /** Returns the last name that was used to try to open this pipe. */
  15278. String getName() const;
  15279. /** Reads data from the pipe.
  15280. This will block until another thread has written enough data into the pipe to fill
  15281. the number of bytes specified, or until another thread calls the cancelPendingReads()
  15282. method.
  15283. If the operation fails, it returns -1, otherwise, it will return the number of
  15284. bytes read.
  15285. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  15286. this is a maximum timeout for reading from the pipe.
  15287. */
  15288. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  15289. /** Writes some data to the pipe.
  15290. If the operation fails, it returns -1, otherwise, it will return the number of
  15291. bytes written.
  15292. */
  15293. int write (const void* sourceBuffer, int numBytesToWrite,
  15294. int timeOutMilliseconds = 2000);
  15295. /** If any threads are currently blocked on a read operation, this tells them to abort.
  15296. */
  15297. void cancelPendingReads();
  15298. private:
  15299. void* internal;
  15300. String currentPipeName;
  15301. CriticalSection lock;
  15302. bool openInternal (const String& pipeName, const bool createPipe);
  15303. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NamedPipe);
  15304. };
  15305. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  15306. /*** End of inlined file: juce_NamedPipe.h ***/
  15307. #endif
  15308. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  15309. /*** Start of inlined file: juce_TemporaryFile.h ***/
  15310. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  15311. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  15312. /**
  15313. Manages a temporary file, which will be deleted when this object is deleted.
  15314. This object is intended to be used as a stack based object, using its scope
  15315. to make sure the temporary file isn't left lying around.
  15316. For example:
  15317. @code
  15318. {
  15319. File myTargetFile ("~/myfile.txt");
  15320. // this will choose a file called something like "~/myfile_temp239348.txt"
  15321. // which definitely doesn't exist at the time the constructor is called.
  15322. TemporaryFile temp (myTargetFile);
  15323. // create a stream to the temporary file, and write some data to it...
  15324. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  15325. if (out != nullptr)
  15326. {
  15327. out->write ( ...etc )
  15328. out->flush();
  15329. out = nullptr; // (deletes the stream)
  15330. // ..now we've finished writing, this will rename the temp file to
  15331. // make it replace the target file we specified above.
  15332. bool succeeded = temp.overwriteTargetFileWithTemporary();
  15333. }
  15334. // ..and even if something went wrong and our overwrite failed,
  15335. // as the TemporaryFile object goes out of scope here, it'll make sure
  15336. // that the temp file gets deleted.
  15337. }
  15338. @endcode
  15339. @see File, FileOutputStream
  15340. */
  15341. class JUCE_API TemporaryFile
  15342. {
  15343. public:
  15344. enum OptionFlags
  15345. {
  15346. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  15347. i.e. its name should start with a dot. */
  15348. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  15349. the file is unique, they should go in brackets rather
  15350. than just being appended (see File::getNonexistentSibling() )*/
  15351. };
  15352. /** Creates a randomly-named temporary file in the default temp directory.
  15353. @param suffix a file suffix to use for the file
  15354. @param optionFlags a combination of the values listed in the OptionFlags enum
  15355. The file will not be created until you write to it. And remember that when
  15356. this object is deleted, the file will also be deleted!
  15357. */
  15358. TemporaryFile (const String& suffix = String::empty,
  15359. int optionFlags = 0);
  15360. /** Creates a temporary file in the same directory as a specified file.
  15361. This is useful if you have a file that you want to overwrite, but don't
  15362. want to harm the original file if the write operation fails. You can
  15363. use this to create a temporary file next to the target file, then
  15364. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  15365. to replace the target file with the one you've just written.
  15366. This class won't create any files until you actually write to them. And remember
  15367. that when this object is deleted, the temporary file will also be deleted!
  15368. @param targetFile the file that you intend to overwrite - the temporary
  15369. file will be created in the same directory as this
  15370. @param optionFlags a combination of the values listed in the OptionFlags enum
  15371. */
  15372. TemporaryFile (const File& targetFile,
  15373. int optionFlags = 0);
  15374. /** Destructor.
  15375. When this object is deleted it will make sure that its temporary file is
  15376. also deleted! If the operation fails, it'll throw an assertion in debug
  15377. mode.
  15378. */
  15379. ~TemporaryFile();
  15380. /** Returns the temporary file. */
  15381. const File& getFile() const { return temporaryFile; }
  15382. /** Returns the target file that was specified in the constructor. */
  15383. const File& getTargetFile() const { return targetFile; }
  15384. /** Tries to move the temporary file to overwrite the target file that was
  15385. specified in the constructor.
  15386. If you used the constructor that specified a target file, this will attempt
  15387. to replace that file with the temporary one.
  15388. Before calling this, make sure:
  15389. - that you've actually written to the temporary file
  15390. - that you've closed any open streams that you were using to write to it
  15391. - and that you don't have any streams open to the target file, which would
  15392. prevent it being overwritten
  15393. If the file move succeeds, this returns false, and the temporary file will
  15394. have disappeared. If it fails, the temporary file will probably still exist,
  15395. but will be deleted when this object is destroyed.
  15396. */
  15397. bool overwriteTargetFileWithTemporary() const;
  15398. /** Attempts to delete the temporary file, if it exists.
  15399. @returns true if the file is successfully deleted (or if it didn't exist).
  15400. */
  15401. bool deleteTemporaryFile() const;
  15402. private:
  15403. File temporaryFile, targetFile;
  15404. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  15405. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryFile);
  15406. };
  15407. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  15408. /*** End of inlined file: juce_TemporaryFile.h ***/
  15409. #endif
  15410. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  15411. /*** Start of inlined file: juce_ZipFile.h ***/
  15412. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  15413. #define __JUCE_ZIPFILE_JUCEHEADER__
  15414. /*** Start of inlined file: juce_InputSource.h ***/
  15415. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  15416. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  15417. /**
  15418. A lightweight object that can create a stream to read some kind of resource.
  15419. This may be used to refer to a file, or some other kind of source, allowing a
  15420. caller to create an input stream that can read from it when required.
  15421. @see FileInputSource
  15422. */
  15423. class JUCE_API InputSource
  15424. {
  15425. public:
  15426. InputSource() noexcept {}
  15427. /** Destructor. */
  15428. virtual ~InputSource() {}
  15429. /** Returns a new InputStream to read this item.
  15430. @returns an inputstream that the caller will delete, or 0 if
  15431. the filename isn't found.
  15432. */
  15433. virtual InputStream* createInputStream() = 0;
  15434. /** Returns a new InputStream to read an item, relative.
  15435. @param relatedItemPath the relative pathname of the resource that is required
  15436. @returns an inputstream that the caller will delete, or 0 if
  15437. the item isn't found.
  15438. */
  15439. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  15440. /** Returns a hash code that uniquely represents this item.
  15441. */
  15442. virtual int64 hashCode() const = 0;
  15443. private:
  15444. JUCE_LEAK_DETECTOR (InputSource);
  15445. };
  15446. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  15447. /*** End of inlined file: juce_InputSource.h ***/
  15448. /**
  15449. Decodes a ZIP file from a stream.
  15450. This can enumerate the items in a ZIP file and can create suitable stream objects
  15451. to read each one.
  15452. */
  15453. class JUCE_API ZipFile
  15454. {
  15455. public:
  15456. /** Creates a ZipFile for a given stream.
  15457. @param inputStream the stream to read from
  15458. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  15459. will be deleted when this ZipFile object is deleted
  15460. */
  15461. ZipFile (InputStream* inputStream, bool deleteStreamWhenDestroyed);
  15462. /** Creates a ZipFile based for a file. */
  15463. ZipFile (const File& file);
  15464. /** Creates a ZipFile for an input source.
  15465. The inputSource object will be owned by the zip file, which will delete
  15466. it later when not needed.
  15467. */
  15468. ZipFile (InputSource* inputSource);
  15469. /** Destructor. */
  15470. ~ZipFile();
  15471. /**
  15472. Contains information about one of the entries in a ZipFile.
  15473. @see ZipFile::getEntry
  15474. */
  15475. struct ZipEntry
  15476. {
  15477. /** The name of the file, which may also include a partial pathname. */
  15478. String filename;
  15479. /** The file's original size. */
  15480. unsigned int uncompressedSize;
  15481. /** The last time the file was modified. */
  15482. Time fileTime;
  15483. };
  15484. /** Returns the number of items in the zip file. */
  15485. int getNumEntries() const noexcept;
  15486. /** Returns a structure that describes one of the entries in the zip file.
  15487. This may return zero if the index is out of range.
  15488. @see ZipFile::ZipEntry
  15489. */
  15490. const ZipEntry* getEntry (int index) const noexcept;
  15491. /** Returns the index of the first entry with a given filename.
  15492. This uses a case-sensitive comparison to look for a filename in the
  15493. list of entries. It might return -1 if no match is found.
  15494. @see ZipFile::ZipEntry
  15495. */
  15496. int getIndexOfFileName (const String& fileName) const noexcept;
  15497. /** Returns a structure that describes one of the entries in the zip file.
  15498. This uses a case-sensitive comparison to look for a filename in the
  15499. list of entries. It might return 0 if no match is found.
  15500. @see ZipFile::ZipEntry
  15501. */
  15502. const ZipEntry* getEntry (const String& fileName) const noexcept;
  15503. /** Sorts the list of entries, based on the filename.
  15504. */
  15505. void sortEntriesByFilename();
  15506. /** Creates a stream that can read from one of the zip file's entries.
  15507. The stream that is returned must be deleted by the caller (and
  15508. zero might be returned if a stream can't be opened for some reason).
  15509. The stream must not be used after the ZipFile object that created
  15510. has been deleted.
  15511. */
  15512. InputStream* createStreamForEntry (int index);
  15513. /** Creates a stream that can read from one of the zip file's entries.
  15514. The stream that is returned must be deleted by the caller (and
  15515. zero might be returned if a stream can't be opened for some reason).
  15516. The stream must not be used after the ZipFile object that created
  15517. has been deleted.
  15518. */
  15519. InputStream* createStreamForEntry (ZipEntry& entry);
  15520. /** Uncompresses all of the files in the zip file.
  15521. This will expand all the entries into a target directory. The relative
  15522. paths of the entries are used.
  15523. @param targetDirectory the root folder to uncompress to
  15524. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  15525. @returns true if all the files are successfully unzipped
  15526. */
  15527. bool uncompressTo (const File& targetDirectory,
  15528. bool shouldOverwriteFiles = true);
  15529. /** Uncompresses one of the entries from the zip file.
  15530. This will expand the entry and write it in a target directory. The entry's path is used to
  15531. determine which subfolder of the target should contain the new file.
  15532. @param index the index of the entry to uncompress
  15533. @param targetDirectory the root folder to uncompress into
  15534. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  15535. @returns true if the files is successfully unzipped
  15536. */
  15537. bool uncompressEntry (int index,
  15538. const File& targetDirectory,
  15539. bool shouldOverwriteFiles = true);
  15540. /** Used to create a new zip file.
  15541. Create a ZipFile::Builder object, and call its addFile() method to add some files,
  15542. then you can write it to a stream with write().
  15543. Currently this just stores the files with no compression.. That will be added
  15544. soon!
  15545. */
  15546. class Builder
  15547. {
  15548. public:
  15549. Builder();
  15550. ~Builder();
  15551. /** Adds a file while should be added to the archive.
  15552. The file isn't read immediately, all the files will be read later when the writeToStream()
  15553. method is called.
  15554. The compressionLevel can be between 0 (no compression), and 9 (maximum compression).
  15555. If the storedPathName parameter is specified, you can customise the partial pathname that
  15556. will be stored for this file.
  15557. */
  15558. void addFile (const File& fileToAdd, int compressionLevel,
  15559. const String& storedPathName = String::empty);
  15560. /** Generates the zip file, writing it to the specified stream. */
  15561. bool writeToStream (OutputStream& target) const;
  15562. private:
  15563. class Item;
  15564. friend class OwnedArray<Item>;
  15565. OwnedArray<Item> items;
  15566. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Builder);
  15567. };
  15568. private:
  15569. class ZipInputStream;
  15570. class ZipFilenameComparator;
  15571. class ZipEntryInfo;
  15572. friend class ZipInputStream;
  15573. friend class ZipFilenameComparator;
  15574. friend class ZipEntryInfo;
  15575. OwnedArray <ZipEntryInfo> entries;
  15576. CriticalSection lock;
  15577. InputStream* inputStream;
  15578. ScopedPointer <InputStream> streamToDelete;
  15579. ScopedPointer <InputSource> inputSource;
  15580. #if JUCE_DEBUG
  15581. int numOpenStreams;
  15582. #endif
  15583. void init();
  15584. int findEndOfZipEntryTable (InputStream& input, int& numEntries);
  15585. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  15586. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipFile);
  15587. };
  15588. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  15589. /*** End of inlined file: juce_ZipFile.h ***/
  15590. #endif
  15591. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  15592. /*** Start of inlined file: juce_MACAddress.h ***/
  15593. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  15594. #define __JUCE_MACADDRESS_JUCEHEADER__
  15595. /**
  15596. A wrapper for a streaming (TCP) socket.
  15597. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15598. sockets, you could also try the InterprocessConnection class.
  15599. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  15600. */
  15601. class JUCE_API MACAddress
  15602. {
  15603. public:
  15604. /** Populates a list of the MAC addresses of all the available network cards. */
  15605. static void findAllAddresses (Array<MACAddress>& results);
  15606. /** Creates a null address (00-00-00-00-00-00). */
  15607. MACAddress();
  15608. /** Creates a copy of another address. */
  15609. MACAddress (const MACAddress& other);
  15610. /** Creates a copy of another address. */
  15611. MACAddress& operator= (const MACAddress& other);
  15612. /** Creates an address from 6 bytes. */
  15613. explicit MACAddress (const uint8 bytes[6]);
  15614. /** Returns a pointer to the 6 bytes that make up this address. */
  15615. const uint8* getBytes() const noexcept { return asBytes; }
  15616. /** Returns a dash-separated string in the form "11-22-33-44-55-66" */
  15617. String toString() const;
  15618. /** Returns the address in the lower 6 bytes of an int64.
  15619. This uses a little-endian arrangement, with the first byte of the address being
  15620. stored in the least-significant byte of the result value.
  15621. */
  15622. int64 toInt64() const noexcept;
  15623. /** Returns true if this address is null (00-00-00-00-00-00). */
  15624. bool isNull() const noexcept;
  15625. bool operator== (const MACAddress& other) const noexcept;
  15626. bool operator!= (const MACAddress& other) const noexcept;
  15627. private:
  15628. #ifndef DOXYGEN
  15629. union
  15630. {
  15631. uint64 asInt64;
  15632. uint8 asBytes[6];
  15633. };
  15634. #endif
  15635. };
  15636. #endif // __JUCE_MACADDRESS_JUCEHEADER__
  15637. /*** End of inlined file: juce_MACAddress.h ***/
  15638. #endif
  15639. #ifndef __JUCE_SOCKET_JUCEHEADER__
  15640. /*** Start of inlined file: juce_Socket.h ***/
  15641. #ifndef __JUCE_SOCKET_JUCEHEADER__
  15642. #define __JUCE_SOCKET_JUCEHEADER__
  15643. /**
  15644. A wrapper for a streaming (TCP) socket.
  15645. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15646. sockets, you could also try the InterprocessConnection class.
  15647. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  15648. */
  15649. class JUCE_API StreamingSocket
  15650. {
  15651. public:
  15652. /** Creates an uninitialised socket.
  15653. To connect it, use the connect() method, after which you can read() or write()
  15654. to it.
  15655. To wait for other sockets to connect to this one, the createListener() method
  15656. enters "listener" mode, and can be used to spawn new sockets for each connection
  15657. that comes along.
  15658. */
  15659. StreamingSocket();
  15660. /** Destructor. */
  15661. ~StreamingSocket();
  15662. /** Binds the socket to the specified local port.
  15663. @returns true on success; false may indicate that another socket is already bound
  15664. on the same port
  15665. */
  15666. bool bindToPort (int localPortNumber);
  15667. /** Tries to connect the socket to hostname:port.
  15668. If timeOutMillisecs is 0, then this method will block until the operating system
  15669. rejects the connection (which could take a long time).
  15670. @returns true if it succeeds.
  15671. @see isConnected
  15672. */
  15673. bool connect (const String& remoteHostname,
  15674. int remotePortNumber,
  15675. int timeOutMillisecs = 3000);
  15676. /** True if the socket is currently connected. */
  15677. bool isConnected() const noexcept { return connected; }
  15678. /** Closes the connection. */
  15679. void close();
  15680. /** Returns the name of the currently connected host. */
  15681. const String& getHostName() const noexcept { return hostName; }
  15682. /** Returns the port number that's currently open. */
  15683. int getPort() const noexcept { return portNumber; }
  15684. /** True if the socket is connected to this machine rather than over the network. */
  15685. bool isLocal() const noexcept;
  15686. /** Waits until the socket is ready for reading or writing.
  15687. If readyForReading is true, it will wait until the socket is ready for
  15688. reading; if false, it will wait until it's ready for writing.
  15689. If the timeout is < 0, it will wait forever, or else will give up after
  15690. the specified time.
  15691. If the socket is ready on return, this returns 1. If it times-out before
  15692. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  15693. */
  15694. int waitUntilReady (bool readyForReading,
  15695. int timeoutMsecs) const;
  15696. /** Reads bytes from the socket.
  15697. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  15698. maxBytesToRead bytes have been read, (or until an error occurs). If this
  15699. flag is false, the method will return as much data as is currently available
  15700. without blocking.
  15701. @returns the number of bytes read, or -1 if there was an error.
  15702. @see waitUntilReady
  15703. */
  15704. int read (void* destBuffer, int maxBytesToRead,
  15705. bool blockUntilSpecifiedAmountHasArrived);
  15706. /** Writes bytes to the socket from a buffer.
  15707. Note that this method will block unless you have checked the socket is ready
  15708. for writing before calling it (see the waitUntilReady() method).
  15709. @returns the number of bytes written, or -1 if there was an error.
  15710. */
  15711. int write (const void* sourceBuffer, int numBytesToWrite);
  15712. /** Puts this socket into "listener" mode.
  15713. When in this mode, your thread can call waitForNextConnection() repeatedly,
  15714. which will spawn new sockets for each new connection, so that these can
  15715. be handled in parallel by other threads.
  15716. @param portNumber the port number to listen on
  15717. @param localHostName the interface address to listen on - pass an empty
  15718. string to listen on all addresses
  15719. @returns true if it manages to open the socket successfully.
  15720. @see waitForNextConnection
  15721. */
  15722. bool createListener (int portNumber, const String& localHostName = String::empty);
  15723. /** When in "listener" mode, this waits for a connection and spawns it as a new
  15724. socket.
  15725. The object that gets returned will be owned by the caller.
  15726. This method can only be called after using createListener().
  15727. @see createListener
  15728. */
  15729. StreamingSocket* waitForNextConnection() const;
  15730. private:
  15731. String hostName;
  15732. int volatile portNumber, handle;
  15733. bool connected, isListener;
  15734. StreamingSocket (const String& hostname, int portNumber, int handle);
  15735. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StreamingSocket);
  15736. };
  15737. /**
  15738. A wrapper for a datagram (UDP) socket.
  15739. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15740. sockets, you could also try the InterprocessConnection class.
  15741. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  15742. */
  15743. class JUCE_API DatagramSocket
  15744. {
  15745. public:
  15746. /**
  15747. Creates an (uninitialised) datagram socket.
  15748. The localPortNumber is the port on which to bind this socket. If this value is 0,
  15749. the port number is assigned by the operating system.
  15750. To use the socket for sending, call the connect() method. This will not immediately
  15751. make a connection, but will save the destination you've provided. After this, you can
  15752. call read() or write().
  15753. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  15754. (may require extra privileges on linux)
  15755. To wait for other sockets to connect to this one, call waitForNextConnection().
  15756. */
  15757. DatagramSocket (int localPortNumber,
  15758. bool enableBroadcasting = false);
  15759. /** Destructor. */
  15760. ~DatagramSocket();
  15761. /** Binds the socket to the specified local port.
  15762. @returns true on success; false may indicate that another socket is already bound
  15763. on the same port
  15764. */
  15765. bool bindToPort (int localPortNumber);
  15766. /** Tries to connect the socket to hostname:port.
  15767. If timeOutMillisecs is 0, then this method will block until the operating system
  15768. rejects the connection (which could take a long time).
  15769. @returns true if it succeeds.
  15770. @see isConnected
  15771. */
  15772. bool connect (const String& remoteHostname,
  15773. int remotePortNumber,
  15774. int timeOutMillisecs = 3000);
  15775. /** True if the socket is currently connected. */
  15776. bool isConnected() const noexcept { return connected; }
  15777. /** Closes the connection. */
  15778. void close();
  15779. /** Returns the name of the currently connected host. */
  15780. const String& getHostName() const noexcept { return hostName; }
  15781. /** Returns the port number that's currently open. */
  15782. int getPort() const noexcept { return portNumber; }
  15783. /** True if the socket is connected to this machine rather than over the network. */
  15784. bool isLocal() const noexcept;
  15785. /** Waits until the socket is ready for reading or writing.
  15786. If readyForReading is true, it will wait until the socket is ready for
  15787. reading; if false, it will wait until it's ready for writing.
  15788. If the timeout is < 0, it will wait forever, or else will give up after
  15789. the specified time.
  15790. If the socket is ready on return, this returns 1. If it times-out before
  15791. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  15792. */
  15793. int waitUntilReady (bool readyForReading,
  15794. int timeoutMsecs) const;
  15795. /** Reads bytes from the socket.
  15796. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  15797. maxBytesToRead bytes have been read, (or until an error occurs). If this
  15798. flag is false, the method will return as much data as is currently available
  15799. without blocking.
  15800. @returns the number of bytes read, or -1 if there was an error.
  15801. @see waitUntilReady
  15802. */
  15803. int read (void* destBuffer, int maxBytesToRead,
  15804. bool blockUntilSpecifiedAmountHasArrived);
  15805. /** Writes bytes to the socket from a buffer.
  15806. Note that this method will block unless you have checked the socket is ready
  15807. for writing before calling it (see the waitUntilReady() method).
  15808. @returns the number of bytes written, or -1 if there was an error.
  15809. */
  15810. int write (const void* sourceBuffer, int numBytesToWrite);
  15811. /** This waits for incoming data to be sent, and returns a socket that can be used
  15812. to read it.
  15813. The object that gets returned is owned by the caller, and can't be used for
  15814. sending, but can be used to read the data.
  15815. */
  15816. DatagramSocket* waitForNextConnection() const;
  15817. private:
  15818. String hostName;
  15819. int volatile portNumber, handle;
  15820. bool connected, allowBroadcast;
  15821. void* serverAddress;
  15822. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  15823. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DatagramSocket);
  15824. };
  15825. #endif // __JUCE_SOCKET_JUCEHEADER__
  15826. /*** End of inlined file: juce_Socket.h ***/
  15827. #endif
  15828. #ifndef __JUCE_URL_JUCEHEADER__
  15829. /*** Start of inlined file: juce_URL.h ***/
  15830. #ifndef __JUCE_URL_JUCEHEADER__
  15831. #define __JUCE_URL_JUCEHEADER__
  15832. class InputStream;
  15833. class XmlElement;
  15834. /**
  15835. Represents a URL and has a bunch of useful functions to manipulate it.
  15836. This class can be used to launch URLs in browsers, and also to create
  15837. InputStreams that can read from remote http or ftp sources.
  15838. */
  15839. class JUCE_API URL
  15840. {
  15841. public:
  15842. /** Creates an empty URL. */
  15843. URL();
  15844. /** Creates a URL from a string. */
  15845. URL (const String& url);
  15846. /** Creates a copy of another URL. */
  15847. URL (const URL& other);
  15848. /** Destructor. */
  15849. ~URL();
  15850. /** Copies this URL from another one. */
  15851. URL& operator= (const URL& other);
  15852. /** Returns a string version of the URL.
  15853. If includeGetParameters is true and any parameters have been set with the
  15854. withParameter() method, then the string will have these appended on the
  15855. end and url-encoded.
  15856. */
  15857. String toString (bool includeGetParameters) const;
  15858. /** True if it seems to be valid. */
  15859. bool isWellFormed() const;
  15860. /** Returns just the domain part of the URL.
  15861. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  15862. */
  15863. String getDomain() const;
  15864. /** Returns the path part of the URL.
  15865. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  15866. */
  15867. String getSubPath() const;
  15868. /** Returns the scheme of the URL.
  15869. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  15870. include the colon).
  15871. */
  15872. String getScheme() const;
  15873. /** Returns a new version of this URL that uses a different sub-path.
  15874. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  15875. "bar", it'll return "http://www.xyz.com/bar?x=1".
  15876. */
  15877. const URL withNewSubPath (const String& newPath) const;
  15878. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  15879. Any control characters in the value will be encoded.
  15880. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  15881. would produce a new url whose toString(true) method would return
  15882. "www.fish.com?amount=some+fish".
  15883. */
  15884. const URL withParameter (const String& parameterName,
  15885. const String& parameterValue) const;
  15886. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  15887. When performing a POST where one of your parameters is a binary file, this
  15888. lets you specify the file.
  15889. Note that the filename is stored, but the file itself won't actually be read
  15890. until this URL is later used to create a network input stream.
  15891. */
  15892. const URL withFileToUpload (const String& parameterName,
  15893. const File& fileToUpload,
  15894. const String& mimeType) const;
  15895. /** Returns a set of all the parameters encoded into the url.
  15896. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  15897. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  15898. The values returned will have been cleaned up to remove any escape characters.
  15899. @see getNamedParameter, withParameter
  15900. */
  15901. const StringPairArray& getParameters() const;
  15902. /** Returns the set of files that should be uploaded as part of a POST operation.
  15903. This is the set of files that were added to the URL with the withFileToUpload()
  15904. method.
  15905. */
  15906. const StringPairArray& getFilesToUpload() const;
  15907. /** Returns the set of mime types associated with each of the upload files.
  15908. */
  15909. const StringPairArray& getMimeTypesOfUploadFiles() const;
  15910. /** Returns a copy of this URL, with a block of data to send as the POST data.
  15911. If you're setting the POST data, be careful not to have any parameters set
  15912. as well, otherwise it'll all get thrown in together, and might not have the
  15913. desired effect.
  15914. If the URL already contains some POST data, this will replace it, rather
  15915. than being appended to it.
  15916. This data will only be used if you specify a post operation when you call
  15917. createInputStream().
  15918. */
  15919. const URL withPOSTData (const String& postData) const;
  15920. /** Returns the data that was set using withPOSTData().
  15921. */
  15922. String getPostData() const { return postData; }
  15923. /** Tries to launch the system's default browser to open the URL.
  15924. Returns true if this seems to have worked.
  15925. */
  15926. bool launchInDefaultBrowser() const;
  15927. /** Takes a guess as to whether a string might be a valid website address.
  15928. This isn't foolproof!
  15929. */
  15930. static bool isProbablyAWebsiteURL (const String& possibleURL);
  15931. /** Takes a guess as to whether a string might be a valid email address.
  15932. This isn't foolproof!
  15933. */
  15934. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  15935. /** This callback function can be used by the createInputStream() method.
  15936. It allows your app to receive progress updates during a lengthy POST operation. If you
  15937. want to continue the operation, this should return true, or false to abort.
  15938. */
  15939. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  15940. /** Attempts to open a stream that can read from this URL.
  15941. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  15942. the paramters, otherwise it'll encode them into the
  15943. URL and do a 'GET'.
  15944. @param progressCallback if this is non-zero, it lets you supply a callback function
  15945. to keep track of the operation's progress. This can be useful
  15946. for lengthy POST operations, so that you can provide user feedback.
  15947. @param progressCallbackContext if a callback is specified, this value will be passed to
  15948. the function
  15949. @param extraHeaders if not empty, this string is appended onto the headers that
  15950. are used for the request. It must therefore be a valid set of HTML
  15951. header directives, separated by newlines.
  15952. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  15953. a negative number, it will be infinite. Otherwise it specifies a
  15954. time in milliseconds.
  15955. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  15956. in the response will be stored in this array
  15957. @returns an input stream that the caller must delete, or a null pointer if there was an
  15958. error trying to open it.
  15959. */
  15960. InputStream* createInputStream (bool usePostCommand,
  15961. OpenStreamProgressCallback* progressCallback = nullptr,
  15962. void* progressCallbackContext = nullptr,
  15963. const String& extraHeaders = String::empty,
  15964. int connectionTimeOutMs = 0,
  15965. StringPairArray* responseHeaders = nullptr) const;
  15966. /** Tries to download the entire contents of this URL into a binary data block.
  15967. If it succeeds, this will return true and append the data it read onto the end
  15968. of the memory block.
  15969. @param destData the memory block to append the new data to
  15970. @param usePostCommand whether to use a POST command to get the data (uses
  15971. a GET command if this is false)
  15972. @see readEntireTextStream, readEntireXmlStream
  15973. */
  15974. bool readEntireBinaryStream (MemoryBlock& destData,
  15975. bool usePostCommand = false) const;
  15976. /** Tries to download the entire contents of this URL as a string.
  15977. If it fails, this will return an empty string, otherwise it will return the
  15978. contents of the downloaded file. If you need to distinguish between a read
  15979. operation that fails and one that returns an empty string, you'll need to use
  15980. a different method, such as readEntireBinaryStream().
  15981. @param usePostCommand whether to use a POST command to get the data (uses
  15982. a GET command if this is false)
  15983. @see readEntireBinaryStream, readEntireXmlStream
  15984. */
  15985. String readEntireTextStream (bool usePostCommand = false) const;
  15986. /** Tries to download the entire contents of this URL and parse it as XML.
  15987. If it fails, or if the text that it reads can't be parsed as XML, this will
  15988. return 0.
  15989. When it returns a valid XmlElement object, the caller is responsibile for deleting
  15990. this object when no longer needed.
  15991. @param usePostCommand whether to use a POST command to get the data (uses
  15992. a GET command if this is false)
  15993. @see readEntireBinaryStream, readEntireTextStream
  15994. */
  15995. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  15996. /** Adds escape sequences to a string to encode any characters that aren't
  15997. legal in a URL.
  15998. E.g. any spaces will be replaced with "%20".
  15999. This is the opposite of removeEscapeChars().
  16000. If isParameter is true, it means that the string is going to be used
  16001. as a parameter, so it also encodes '$' and ',' (which would otherwise
  16002. be legal in a URL.
  16003. @see removeEscapeChars
  16004. */
  16005. static String addEscapeChars (const String& stringToAddEscapeCharsTo,
  16006. bool isParameter);
  16007. /** Replaces any escape character sequences in a string with their original
  16008. character codes.
  16009. E.g. any instances of "%20" will be replaced by a space.
  16010. This is the opposite of addEscapeChars().
  16011. @see addEscapeChars
  16012. */
  16013. static String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  16014. private:
  16015. String url, postData;
  16016. StringPairArray parameters, filesToUpload, mimeTypes;
  16017. static InputStream* createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  16018. OpenStreamProgressCallback* progressCallback,
  16019. void* progressCallbackContext, const String& headers,
  16020. const int timeOutMs, StringPairArray* responseHeaders);
  16021. JUCE_LEAK_DETECTOR (URL);
  16022. };
  16023. #endif // __JUCE_URL_JUCEHEADER__
  16024. /*** End of inlined file: juce_URL.h ***/
  16025. #endif
  16026. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  16027. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  16028. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  16029. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  16030. /*** Start of inlined file: juce_OptionalScopedPointer.h ***/
  16031. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  16032. #define __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  16033. /**
  16034. Holds a pointer to an object which can optionally be deleted when this pointer
  16035. goes out of scope.
  16036. This acts in many ways like a ScopedPointer, but allows you to specify whether or
  16037. not the object is deleted.
  16038. @see ScopedPointer
  16039. */
  16040. template <class ObjectType>
  16041. class OptionalScopedPointer
  16042. {
  16043. public:
  16044. /** Creates an empty OptionalScopedPointer. */
  16045. OptionalScopedPointer() : shouldDelete (false) {}
  16046. /** Creates an OptionalScopedPointer to point to a given object, and specifying whether
  16047. the OptionalScopedPointer will delete it.
  16048. If takeOwnership is true, then the OptionalScopedPointer will act like a ScopedPointer,
  16049. deleting the object when it is itself deleted. If this parameter is false, then the
  16050. OptionalScopedPointer just holds a normal pointer to the object, and won't delete it.
  16051. */
  16052. OptionalScopedPointer (ObjectType* objectToHold, bool takeOwnership)
  16053. : object (objectToHold), shouldDelete (takeOwnership)
  16054. {
  16055. }
  16056. /** Takes ownership of the object that another OptionalScopedPointer holds.
  16057. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  16058. as ownership of the managed object is transferred to this object.
  16059. The flag to indicate whether or not to delete the managed object is also
  16060. copied from the source object.
  16061. */
  16062. OptionalScopedPointer (OptionalScopedPointer& objectToTransferFrom)
  16063. : object (objectToTransferFrom.release()),
  16064. shouldDelete (objectToTransferFrom.shouldDelete)
  16065. {
  16066. }
  16067. /** Takes ownership of the object that another OptionalScopedPointer holds.
  16068. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  16069. as ownership of the managed object is transferred to this object.
  16070. The ownership flag that says whether or not to delete the managed object is also
  16071. copied from the source object.
  16072. */
  16073. OptionalScopedPointer& operator= (OptionalScopedPointer& objectToTransferFrom)
  16074. {
  16075. if (object != objectToTransferFrom.object)
  16076. {
  16077. clear();
  16078. object = objectToTransferFrom.object;
  16079. }
  16080. shouldDelete = objectToTransferFrom.shouldDelete;
  16081. return *this;
  16082. }
  16083. /** The destructor may or may not delete the object that is being held, depending on the
  16084. takeOwnership flag that was specified when the object was first passed into an
  16085. OptionalScopedPointer constructor.
  16086. */
  16087. ~OptionalScopedPointer()
  16088. {
  16089. clear();
  16090. }
  16091. /** Returns the object that this pointer is managing. */
  16092. inline operator ObjectType*() const noexcept { return object; }
  16093. /** Returns the object that this pointer is managing. */
  16094. inline ObjectType& operator*() const noexcept { return *object; }
  16095. /** Lets you access methods and properties of the object that this pointer is holding. */
  16096. inline ObjectType* operator->() const noexcept { return object; }
  16097. /** Removes the current object from this OptionalScopedPointer without deleting it.
  16098. This will return the current object, and set this OptionalScopedPointer to a null pointer.
  16099. */
  16100. ObjectType* release() noexcept { return object.release(); }
  16101. /** Resets this pointer to null, possibly deleting the object that it holds, if it has
  16102. ownership of it.
  16103. */
  16104. void clear()
  16105. {
  16106. if (! shouldDelete)
  16107. object.release();
  16108. }
  16109. /** Swaps this object with another OptionalScopedPointer.
  16110. The two objects simply exchange their states.
  16111. */
  16112. void swapWith (OptionalScopedPointer<ObjectType>& other) noexcept
  16113. {
  16114. object.swapWith (other.object);
  16115. std::swap (shouldDelete, other.shouldDelete);
  16116. }
  16117. private:
  16118. ScopedPointer<ObjectType> object;
  16119. bool shouldDelete;
  16120. };
  16121. #endif // __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  16122. /*** End of inlined file: juce_OptionalScopedPointer.h ***/
  16123. /** Wraps another input stream, and reads from it using an intermediate buffer
  16124. If you're using an input stream such as a file input stream, and making lots of
  16125. small read accesses to it, it's probably sensible to wrap it in one of these,
  16126. so that the source stream gets accessed in larger chunk sizes, meaning less
  16127. work for the underlying stream.
  16128. */
  16129. class JUCE_API BufferedInputStream : public InputStream
  16130. {
  16131. public:
  16132. /** Creates a BufferedInputStream from an input source.
  16133. @param sourceStream the source stream to read from
  16134. @param bufferSize the size of reservoir to use to buffer the source
  16135. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  16136. deleted by this object when it is itself deleted.
  16137. */
  16138. BufferedInputStream (InputStream* sourceStream,
  16139. int bufferSize,
  16140. bool deleteSourceWhenDestroyed);
  16141. /** Creates a BufferedInputStream from an input source.
  16142. @param sourceStream the source stream to read from - the source stream must not
  16143. be deleted until this object has been destroyed.
  16144. @param bufferSize the size of reservoir to use to buffer the source
  16145. */
  16146. BufferedInputStream (InputStream& sourceStream, int bufferSize);
  16147. /** Destructor.
  16148. This may also delete the source stream, if that option was chosen when the
  16149. buffered stream was created.
  16150. */
  16151. ~BufferedInputStream();
  16152. int64 getTotalLength();
  16153. int64 getPosition();
  16154. bool setPosition (int64 newPosition);
  16155. int read (void* destBuffer, int maxBytesToRead);
  16156. String readString();
  16157. bool isExhausted();
  16158. private:
  16159. OptionalScopedPointer<InputStream> source;
  16160. int bufferSize;
  16161. int64 position, lastReadPos, bufferStart, bufferOverlap;
  16162. HeapBlock <char> buffer;
  16163. void ensureBuffered();
  16164. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferedInputStream);
  16165. };
  16166. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  16167. /*** End of inlined file: juce_BufferedInputStream.h ***/
  16168. #endif
  16169. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  16170. /*** Start of inlined file: juce_FileInputSource.h ***/
  16171. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  16172. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  16173. /**
  16174. A type of InputSource that represents a normal file.
  16175. @see InputSource
  16176. */
  16177. class JUCE_API FileInputSource : public InputSource
  16178. {
  16179. public:
  16180. FileInputSource (const File& file, bool useFileTimeInHashGeneration = false);
  16181. ~FileInputSource();
  16182. InputStream* createInputStream();
  16183. InputStream* createInputStreamFor (const String& relatedItemPath);
  16184. int64 hashCode() const;
  16185. private:
  16186. const File file;
  16187. bool useFileTimeInHashGeneration;
  16188. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputSource);
  16189. };
  16190. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  16191. /*** End of inlined file: juce_FileInputSource.h ***/
  16192. #endif
  16193. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16194. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  16195. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16196. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16197. /**
  16198. A stream which uses zlib to compress the data written into it.
  16199. @see GZIPDecompressorInputStream
  16200. */
  16201. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  16202. {
  16203. public:
  16204. /** Creates a compression stream.
  16205. @param destStream the stream into which the compressed data should
  16206. be written
  16207. @param compressionLevel how much to compress the data, between 1 and 9, where
  16208. 1 is the fastest/lowest compression, and 9 is the
  16209. slowest/highest compression. Any value outside this range
  16210. indicates that a default compression level should be used.
  16211. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  16212. this stream is destroyed
  16213. @param windowBits this is used internally to change the window size used
  16214. by zlib - leave it as 0 unless you specifically need to set
  16215. its value for some reason
  16216. */
  16217. GZIPCompressorOutputStream (OutputStream* destStream,
  16218. int compressionLevel = 0,
  16219. bool deleteDestStreamWhenDestroyed = false,
  16220. int windowBits = 0);
  16221. /** Destructor. */
  16222. ~GZIPCompressorOutputStream();
  16223. void flush();
  16224. int64 getPosition();
  16225. bool setPosition (int64 newPosition);
  16226. bool write (const void* destBuffer, int howMany);
  16227. /** These are preset values that can be used for the constructor's windowBits paramter.
  16228. For more info about this, see the zlib documentation for its windowBits parameter.
  16229. */
  16230. enum WindowBitsValues
  16231. {
  16232. windowBitsRaw = -15,
  16233. windowBitsGZIP = 15 + 16
  16234. };
  16235. private:
  16236. OptionalScopedPointer<OutputStream> destStream;
  16237. HeapBlock <uint8> buffer;
  16238. class GZIPCompressorHelper;
  16239. friend class ScopedPointer <GZIPCompressorHelper>;
  16240. ScopedPointer <GZIPCompressorHelper> helper;
  16241. bool doNextBlock();
  16242. void flushInternal();
  16243. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPCompressorOutputStream);
  16244. };
  16245. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  16246. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  16247. #endif
  16248. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16249. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  16250. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16251. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16252. /**
  16253. This stream will decompress a source-stream using zlib.
  16254. Tip: if you're reading lots of small items from one of these streams, you
  16255. can increase the performance enormously by passing it through a
  16256. BufferedInputStream, so that it has to read larger blocks less often.
  16257. @see GZIPCompressorOutputStream
  16258. */
  16259. class JUCE_API GZIPDecompressorInputStream : public InputStream
  16260. {
  16261. public:
  16262. /** Creates a decompressor stream.
  16263. @param sourceStream the stream to read from
  16264. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  16265. when this object is destroyed
  16266. @param noWrap this is used internally by the ZipFile class
  16267. and should be ignored by user applications
  16268. @param uncompressedStreamLength if the creator knows the length that the
  16269. uncompressed stream will be, then it can supply this
  16270. value, which will be returned by getTotalLength()
  16271. */
  16272. GZIPDecompressorInputStream (InputStream* sourceStream,
  16273. bool deleteSourceWhenDestroyed,
  16274. bool noWrap = false,
  16275. int64 uncompressedStreamLength = -1);
  16276. /** Creates a decompressor stream.
  16277. @param sourceStream the stream to read from - the source stream must not be
  16278. deleted until this object has been destroyed
  16279. */
  16280. GZIPDecompressorInputStream (InputStream& sourceStream);
  16281. /** Destructor. */
  16282. ~GZIPDecompressorInputStream();
  16283. int64 getPosition();
  16284. bool setPosition (int64 pos);
  16285. int64 getTotalLength();
  16286. bool isExhausted();
  16287. int read (void* destBuffer, int maxBytesToRead);
  16288. private:
  16289. OptionalScopedPointer<InputStream> sourceStream;
  16290. const int64 uncompressedStreamLength;
  16291. const bool noWrap;
  16292. bool isEof;
  16293. int activeBufferSize;
  16294. int64 originalSourcePos, currentPos;
  16295. HeapBlock <uint8> buffer;
  16296. class GZIPDecompressHelper;
  16297. friend class ScopedPointer <GZIPDecompressHelper>;
  16298. ScopedPointer <GZIPDecompressHelper> helper;
  16299. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPDecompressorInputStream);
  16300. };
  16301. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16302. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  16303. #endif
  16304. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  16305. #endif
  16306. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  16307. #endif
  16308. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16309. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  16310. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16311. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16312. /**
  16313. Allows a block of data and to be accessed as a stream.
  16314. This can either be used to refer to a shared block of memory, or can make its
  16315. own internal copy of the data when the MemoryInputStream is created.
  16316. */
  16317. class JUCE_API MemoryInputStream : public InputStream
  16318. {
  16319. public:
  16320. /** Creates a MemoryInputStream.
  16321. @param sourceData the block of data to use as the stream's source
  16322. @param sourceDataSize the number of bytes in the source data block
  16323. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  16324. the source data, so this data shouldn't be changed
  16325. for the lifetime of the stream; if this parameter is
  16326. true, the stream will make its own copy of the
  16327. data and use that.
  16328. */
  16329. MemoryInputStream (const void* sourceData,
  16330. size_t sourceDataSize,
  16331. bool keepInternalCopyOfData);
  16332. /** Creates a MemoryInputStream.
  16333. @param data a block of data to use as the stream's source
  16334. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  16335. the source data, so this data shouldn't be changed
  16336. for the lifetime of the stream; if this parameter is
  16337. true, the stream will make its own copy of the
  16338. data and use that.
  16339. */
  16340. MemoryInputStream (const MemoryBlock& data,
  16341. bool keepInternalCopyOfData);
  16342. /** Destructor. */
  16343. ~MemoryInputStream();
  16344. int64 getPosition();
  16345. bool setPosition (int64 pos);
  16346. int64 getTotalLength();
  16347. bool isExhausted();
  16348. int read (void* destBuffer, int maxBytesToRead);
  16349. private:
  16350. const char* data;
  16351. size_t dataSize, position;
  16352. HeapBlock<char> internalCopy;
  16353. void createInternalCopy();
  16354. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryInputStream);
  16355. };
  16356. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16357. /*** End of inlined file: juce_MemoryInputStream.h ***/
  16358. #endif
  16359. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16360. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  16361. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16362. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16363. /**
  16364. Writes data to an internal memory buffer, which grows as required.
  16365. The data that was written into the stream can then be accessed later as
  16366. a contiguous block of memory.
  16367. */
  16368. class JUCE_API MemoryOutputStream : public OutputStream
  16369. {
  16370. public:
  16371. /** Creates an empty memory stream ready for writing into.
  16372. @param initialSize the intial amount of capacity to allocate for writing into
  16373. */
  16374. MemoryOutputStream (size_t initialSize = 256);
  16375. /** Creates a memory stream for writing into into a pre-existing MemoryBlock object.
  16376. Note that the destination block will always be larger than the amount of data
  16377. that has been written to the stream, because the MemoryOutputStream keeps some
  16378. spare capactity at its end. To trim the block's size down to fit the actual
  16379. data, call flush(), or delete the MemoryOutputStream.
  16380. @param memoryBlockToWriteTo the block into which new data will be written.
  16381. @param appendToExistingBlockContent if this is true, the contents of the block will be
  16382. kept, and new data will be appended to it. If false,
  16383. the block will be cleared before use
  16384. */
  16385. MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  16386. bool appendToExistingBlockContent);
  16387. /** Destructor.
  16388. This will free any data that was written to it.
  16389. */
  16390. ~MemoryOutputStream();
  16391. /** Returns a pointer to the data that has been written to the stream.
  16392. @see getDataSize
  16393. */
  16394. const void* getData() const noexcept;
  16395. /** Returns the number of bytes of data that have been written to the stream.
  16396. @see getData
  16397. */
  16398. size_t getDataSize() const noexcept { return size; }
  16399. /** Resets the stream, clearing any data that has been written to it so far. */
  16400. void reset() noexcept;
  16401. /** Increases the internal storage capacity to be able to contain at least the specified
  16402. amount of data without needing to be resized.
  16403. */
  16404. void preallocate (size_t bytesToPreallocate);
  16405. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  16406. String toUTF8() const;
  16407. /** Attempts to detect the encoding of the data and convert it to a string.
  16408. @see String::createStringFromData
  16409. */
  16410. String toString() const;
  16411. /** If the stream is writing to a user-supplied MemoryBlock, this will trim any excess
  16412. capacity off the block, so that its length matches the amount of actual data that
  16413. has been written so far.
  16414. */
  16415. void flush();
  16416. bool write (const void* buffer, int howMany);
  16417. int64 getPosition() { return position; }
  16418. bool setPosition (int64 newPosition);
  16419. int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  16420. void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  16421. private:
  16422. MemoryBlock& data;
  16423. MemoryBlock internalBlock;
  16424. size_t position, size;
  16425. void trimExternalBlockSize();
  16426. void prepareToWrite (int numBytes);
  16427. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryOutputStream);
  16428. };
  16429. /** Copies all the data that has been written to a MemoryOutputStream into another stream. */
  16430. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead);
  16431. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16432. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  16433. #endif
  16434. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  16435. #endif
  16436. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16437. /*** Start of inlined file: juce_SubregionStream.h ***/
  16438. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16439. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16440. /** Wraps another input stream, and reads from a specific part of it.
  16441. This lets you take a subsection of a stream and present it as an entire
  16442. stream in its own right.
  16443. */
  16444. class JUCE_API SubregionStream : public InputStream
  16445. {
  16446. public:
  16447. /** Creates a SubregionStream from an input source.
  16448. @param sourceStream the source stream to read from
  16449. @param startPositionInSourceStream this is the position in the source stream that
  16450. corresponds to position 0 in this stream
  16451. @param lengthOfSourceStream this specifies the maximum number of bytes
  16452. from the source stream that will be passed through
  16453. by this stream. When the position of this stream
  16454. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  16455. If the length passed in here is greater than the length
  16456. of the source stream (as returned by getTotalLength()),
  16457. then the smaller value will be used.
  16458. Passing a negative value for this parameter means it
  16459. will keep reading until the source's end-of-stream.
  16460. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  16461. deleted by this object when it is itself deleted.
  16462. */
  16463. SubregionStream (InputStream* sourceStream,
  16464. int64 startPositionInSourceStream,
  16465. int64 lengthOfSourceStream,
  16466. bool deleteSourceWhenDestroyed);
  16467. /** Destructor.
  16468. This may also delete the source stream, if that option was chosen when the
  16469. buffered stream was created.
  16470. */
  16471. ~SubregionStream();
  16472. int64 getTotalLength();
  16473. int64 getPosition();
  16474. bool setPosition (int64 newPosition);
  16475. int read (void* destBuffer, int maxBytesToRead);
  16476. bool isExhausted();
  16477. private:
  16478. OptionalScopedPointer<InputStream> source;
  16479. const int64 startPositionInSourceStream, lengthOfSourceStream;
  16480. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubregionStream);
  16481. };
  16482. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16483. /*** End of inlined file: juce_SubregionStream.h ***/
  16484. #endif
  16485. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  16486. #endif
  16487. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  16488. /*** Start of inlined file: juce_Expression.h ***/
  16489. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  16490. #define __JUCE_EXPRESSION_JUCEHEADER__
  16491. /**
  16492. A class for dynamically evaluating simple numeric expressions.
  16493. This class can parse a simple C-style string expression involving floating point
  16494. numbers, named symbols and functions. The basic arithmetic operations of +, -, *, /
  16495. are supported, as well as parentheses, and any alphanumeric identifiers are
  16496. assumed to be named symbols which will be resolved when the expression is
  16497. evaluated.
  16498. Expressions which use identifiers and functions require a subclass of
  16499. Expression::Scope to be supplied when evaluating them, and this object
  16500. is expected to be able to resolve the symbol names and perform the functions that
  16501. are used.
  16502. */
  16503. class JUCE_API Expression
  16504. {
  16505. public:
  16506. /** Creates a simple expression with a value of 0. */
  16507. Expression();
  16508. /** Destructor. */
  16509. ~Expression();
  16510. /** Creates a simple expression with a specified constant value. */
  16511. explicit Expression (double constant);
  16512. /** Creates a copy of an expression. */
  16513. Expression (const Expression& other);
  16514. /** Copies another expression. */
  16515. Expression& operator= (const Expression& other);
  16516. /** Creates an expression by parsing a string.
  16517. If there's a syntax error in the string, this will throw a ParseError exception.
  16518. @throws ParseError
  16519. */
  16520. explicit Expression (const String& stringToParse);
  16521. /** Returns a string version of the expression. */
  16522. String toString() const;
  16523. /** Returns an expression which is an addtion operation of two existing expressions. */
  16524. Expression operator+ (const Expression& other) const;
  16525. /** Returns an expression which is a subtraction operation of two existing expressions. */
  16526. Expression operator- (const Expression& other) const;
  16527. /** Returns an expression which is a multiplication operation of two existing expressions. */
  16528. Expression operator* (const Expression& other) const;
  16529. /** Returns an expression which is a division operation of two existing expressions. */
  16530. Expression operator/ (const Expression& other) const;
  16531. /** Returns an expression which performs a negation operation on an existing expression. */
  16532. Expression operator-() const;
  16533. /** Returns an Expression which is an identifier reference. */
  16534. static Expression symbol (const String& symbol);
  16535. /** Returns an Expression which is a function call. */
  16536. static Expression function (const String& functionName, const Array<Expression>& parameters);
  16537. /** Returns an Expression which parses a string from a character pointer, and updates the pointer
  16538. to indicate where it finished.
  16539. The pointer is incremented so that on return, it indicates the character that follows
  16540. the end of the expression that was parsed.
  16541. If there's a syntax error in the string, this will throw a ParseError exception.
  16542. @throws ParseError
  16543. */
  16544. static Expression parse (String::CharPointerType& stringToParse);
  16545. /** When evaluating an Expression object, this class is used to resolve symbols and
  16546. perform functions that the expression uses.
  16547. */
  16548. class JUCE_API Scope
  16549. {
  16550. public:
  16551. Scope();
  16552. virtual ~Scope();
  16553. /** Returns some kind of globally unique ID that identifies this scope. */
  16554. virtual String getScopeUID() const;
  16555. /** Returns the value of a symbol.
  16556. If the symbol is unknown, this can throw an Expression::EvaluationError exception.
  16557. The member value is set to the part of the symbol that followed the dot, if there is
  16558. one, e.g. for "foo.bar", symbol = "foo" and member = "bar".
  16559. @throws Expression::EvaluationError
  16560. */
  16561. virtual Expression getSymbolValue (const String& symbol) const;
  16562. /** Executes a named function.
  16563. If the function name is unknown, this can throw an Expression::EvaluationError exception.
  16564. @throws Expression::EvaluationError
  16565. */
  16566. virtual double evaluateFunction (const String& functionName,
  16567. const double* parameters, int numParameters) const;
  16568. /** Used as a callback by the Scope::visitRelativeScope() method.
  16569. You should never create an instance of this class yourself, it's used by the
  16570. expression evaluation code.
  16571. */
  16572. class Visitor
  16573. {
  16574. public:
  16575. virtual ~Visitor() {}
  16576. virtual void visit (const Scope&) = 0;
  16577. };
  16578. /** Creates a Scope object for a named scope, and then calls a visitor
  16579. to do some kind of processing with this new scope.
  16580. If the name is valid, this method must create a suitable (temporary) Scope
  16581. object to represent it, and must call the Visitor::visit() method with this
  16582. new scope.
  16583. */
  16584. virtual void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  16585. };
  16586. /** Evaluates this expression, without using a Scope.
  16587. Without a Scope, no symbols can be used, and only basic functions such as sin, cos, tan,
  16588. min, max are available.
  16589. To find out about any errors during evaluation, use the other version of this method which
  16590. takes a String parameter.
  16591. */
  16592. double evaluate() const;
  16593. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  16594. or functions that it uses.
  16595. To find out about any errors during evaluation, use the other version of this method which
  16596. takes a String parameter.
  16597. */
  16598. double evaluate (const Scope& scope) const;
  16599. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  16600. or functions that it uses.
  16601. */
  16602. double evaluate (const Scope& scope, String& evaluationError) const;
  16603. /** Attempts to return an expression which is a copy of this one, but with a constant adjusted
  16604. to make the expression resolve to a target value.
  16605. E.g. if the expression is "x + 10" and x is 5, then asking for a target value of 8 will return
  16606. the expression "x + 3". Obviously some expressions can't be reversed in this way, in which
  16607. case they might just be adjusted by adding a constant to the original expression.
  16608. @throws Expression::EvaluationError
  16609. */
  16610. Expression adjustedToGiveNewResult (double targetValue, const Scope& scope) const;
  16611. /** Represents a symbol that is used in an Expression. */
  16612. struct Symbol
  16613. {
  16614. Symbol (const String& scopeUID, const String& symbolName);
  16615. bool operator== (const Symbol&) const noexcept;
  16616. bool operator!= (const Symbol&) const noexcept;
  16617. String scopeUID; /**< The unique ID of the Scope that contains this symbol. */
  16618. String symbolName; /**< The name of the symbol. */
  16619. };
  16620. /** Returns a copy of this expression in which all instances of a given symbol have been renamed. */
  16621. Expression withRenamedSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope) const;
  16622. /** Returns true if this expression makes use of the specified symbol.
  16623. If a suitable scope is supplied, the search will dereference and recursively check
  16624. all symbols, so that it can be determined whether this expression relies on the given
  16625. symbol at any level in its evaluation. If the scope parameter is null, this just checks
  16626. whether the expression contains any direct references to the symbol.
  16627. @throws Expression::EvaluationError
  16628. */
  16629. bool referencesSymbol (const Symbol& symbol, const Scope& scope) const;
  16630. /** Returns true if this expression contains any symbols. */
  16631. bool usesAnySymbols() const;
  16632. /** Returns a list of all symbols that may be needed to resolve this expression in the given scope. */
  16633. void findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const;
  16634. /** An exception that can be thrown by Expression::parse(). */
  16635. class ParseError : public std::exception
  16636. {
  16637. public:
  16638. ParseError (const String& message);
  16639. String description;
  16640. };
  16641. /** Expression type.
  16642. @see Expression::getType()
  16643. */
  16644. enum Type
  16645. {
  16646. constantType,
  16647. functionType,
  16648. operatorType,
  16649. symbolType
  16650. };
  16651. /** Returns the type of this expression. */
  16652. Type getType() const noexcept;
  16653. /** If this expression is a symbol, function or operator, this returns its identifier. */
  16654. String getSymbolOrFunction() const;
  16655. /** Returns the number of inputs to this expression.
  16656. @see getInput
  16657. */
  16658. int getNumInputs() const;
  16659. /** Retrieves one of the inputs to this expression.
  16660. @see getNumInputs
  16661. */
  16662. Expression getInput (int index) const;
  16663. private:
  16664. class Term;
  16665. class Helpers;
  16666. friend class Term;
  16667. friend class Helpers;
  16668. friend class ScopedPointer<Term>;
  16669. friend class ReferenceCountedObjectPtr<Term>;
  16670. ReferenceCountedObjectPtr<Term> term;
  16671. explicit Expression (Term* term);
  16672. };
  16673. #endif // __JUCE_EXPRESSION_JUCEHEADER__
  16674. /*** End of inlined file: juce_Expression.h ***/
  16675. #endif
  16676. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  16677. #endif
  16678. #ifndef __JUCE_RANDOM_JUCEHEADER__
  16679. /*** Start of inlined file: juce_Random.h ***/
  16680. #ifndef __JUCE_RANDOM_JUCEHEADER__
  16681. #define __JUCE_RANDOM_JUCEHEADER__
  16682. /**
  16683. A random number generator.
  16684. You can create a Random object and use it to generate a sequence of random numbers.
  16685. As a handy shortcut to avoid having to create and seed one yourself, you can call
  16686. Random::getSystemRandom() to return a global RNG that is seeded randomly when the
  16687. app launches.
  16688. */
  16689. class JUCE_API Random
  16690. {
  16691. public:
  16692. /** Creates a Random object based on a seed value.
  16693. For a given seed value, the subsequent numbers generated by this object
  16694. will be predictable, so a good idea is to set this value based
  16695. on the time, e.g.
  16696. new Random (Time::currentTimeMillis())
  16697. */
  16698. explicit Random (int64 seedValue) noexcept;
  16699. /** Creates a Random object using a random seed value.
  16700. Internally, this calls setSeedRandomly() to randomise the seed.
  16701. */
  16702. Random();
  16703. /** Destructor. */
  16704. ~Random() noexcept;
  16705. /** Returns the next random 32 bit integer.
  16706. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  16707. */
  16708. int nextInt() noexcept;
  16709. /** Returns the next random number, limited to a given range.
  16710. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  16711. */
  16712. int nextInt (int maxValue) noexcept;
  16713. /** Returns the next 64-bit random number.
  16714. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  16715. */
  16716. int64 nextInt64() noexcept;
  16717. /** Returns the next random floating-point number.
  16718. @returns a random value in the range 0 to 1.0
  16719. */
  16720. float nextFloat() noexcept;
  16721. /** Returns the next random floating-point number.
  16722. @returns a random value in the range 0 to 1.0
  16723. */
  16724. double nextDouble() noexcept;
  16725. /** Returns the next random boolean value.
  16726. */
  16727. bool nextBool() noexcept;
  16728. /** Returns a BigInteger containing a random number.
  16729. @returns a random value in the range 0 to (maximumValue - 1).
  16730. */
  16731. BigInteger nextLargeNumber (const BigInteger& maximumValue);
  16732. /** Sets a range of bits in a BigInteger to random values. */
  16733. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  16734. /** To avoid the overhead of having to create a new Random object whenever
  16735. you need a number, this is a shared application-wide object that
  16736. can be used.
  16737. It's not thread-safe though, so threads should use their own Random object.
  16738. */
  16739. static Random& getSystemRandom() noexcept;
  16740. /** Resets this Random object to a given seed value. */
  16741. void setSeed (int64 newSeed) noexcept;
  16742. /** Merges this object's seed with another value.
  16743. This sets the seed to be a value created by combining the current seed and this
  16744. new value.
  16745. */
  16746. void combineSeed (int64 seedValue) noexcept;
  16747. /** Reseeds this generator using a value generated from various semi-random system
  16748. properties like the current time, etc.
  16749. Because this function convolves the time with the last seed value, calling
  16750. it repeatedly will increase the randomness of the final result.
  16751. */
  16752. void setSeedRandomly();
  16753. private:
  16754. int64 seed;
  16755. JUCE_LEAK_DETECTOR (Random);
  16756. };
  16757. #endif // __JUCE_RANDOM_JUCEHEADER__
  16758. /*** End of inlined file: juce_Random.h ***/
  16759. #endif
  16760. #ifndef __JUCE_RANGE_JUCEHEADER__
  16761. #endif
  16762. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  16763. #endif
  16764. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  16765. #endif
  16766. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  16767. #endif
  16768. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  16769. #endif
  16770. #ifndef __JUCE_MEMORY_JUCEHEADER__
  16771. #endif
  16772. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  16773. #endif
  16774. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  16775. #endif
  16776. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  16777. #endif
  16778. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  16779. #endif
  16780. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  16781. /*** Start of inlined file: juce_WeakReference.h ***/
  16782. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  16783. #define __JUCE_WEAKREFERENCE_JUCEHEADER__
  16784. /**
  16785. This class acts as a pointer which will automatically become null if the object
  16786. to which it points is deleted.
  16787. To accomplish this, the source object needs to cooperate by performing a couple of simple tasks.
  16788. It must provide a getWeakReference() method and embed a WeakReference::Master object, which stores
  16789. a shared pointer object. It must also clear this master pointer when it's getting deleted.
  16790. E.g.
  16791. @code
  16792. class MyObject
  16793. {
  16794. public:
  16795. MyObject()
  16796. {
  16797. // If you're planning on using your WeakReferences in a multi-threaded situation, you may choose
  16798. // to call getWeakReference() here in the constructor, which will pre-initialise it, avoiding an
  16799. // (extremely unlikely) race condition that could occur if multiple threads overlap while making
  16800. // the first call to getWeakReference().
  16801. }
  16802. ~MyObject()
  16803. {
  16804. // This will zero all the references - you need to call this in your destructor.
  16805. masterReference.clear();
  16806. }
  16807. // Your object must provide a method that looks pretty much identical to this (except
  16808. // for the templated class name, of course).
  16809. const WeakReference<MyObject>::SharedRef& getWeakReference()
  16810. {
  16811. return masterReference (this);
  16812. }
  16813. private:
  16814. // You need to embed one of these inside your object. It can be private.
  16815. WeakReference<MyObject>::Master masterReference;
  16816. };
  16817. // Here's an example of using a pointer..
  16818. MyObject* n = new MyObject();
  16819. WeakReference<MyObject> myObjectRef = n;
  16820. MyObject* pointer1 = myObjectRef; // returns a valid pointer to 'n'
  16821. delete n;
  16822. MyObject* pointer2 = myObjectRef; // returns a null pointer
  16823. @endcode
  16824. @see WeakReference::Master
  16825. */
  16826. template <class ObjectType, class ReferenceCountingType = ReferenceCountedObject>
  16827. class WeakReference
  16828. {
  16829. public:
  16830. /** Creates a null SafePointer. */
  16831. inline WeakReference() noexcept {}
  16832. /** Creates a WeakReference that points at the given object. */
  16833. WeakReference (ObjectType* const object) : holder (object != nullptr ? object->getWeakReference() : nullptr) {}
  16834. /** Creates a copy of another WeakReference. */
  16835. WeakReference (const WeakReference& other) noexcept : holder (other.holder) {}
  16836. /** Copies another pointer to this one. */
  16837. WeakReference& operator= (const WeakReference& other) { holder = other.holder; return *this; }
  16838. /** Copies another pointer to this one. */
  16839. WeakReference& operator= (ObjectType* const newObject) { holder = (newObject != nullptr) ? newObject->getWeakReference() : nullptr; return *this; }
  16840. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16841. ObjectType* get() const noexcept { return holder != nullptr ? holder->get() : nullptr; }
  16842. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16843. operator ObjectType*() const noexcept { return get(); }
  16844. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16845. ObjectType* operator->() noexcept { return get(); }
  16846. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16847. const ObjectType* operator->() const noexcept { return get(); }
  16848. /** This returns true if this reference has been pointing at an object, but that object has
  16849. since been deleted.
  16850. If this reference was only ever pointing at a null pointer, this will return false. Using
  16851. operator=() to make this refer to a different object will reset this flag to match the status
  16852. of the reference from which you're copying.
  16853. */
  16854. bool wasObjectDeleted() const noexcept { return holder != nullptr && holder->get() == nullptr; }
  16855. bool operator== (ObjectType* const object) const noexcept { return get() == object; }
  16856. bool operator!= (ObjectType* const object) const noexcept { return get() != object; }
  16857. /** This class is used internally by the WeakReference class - don't use it directly
  16858. in your code!
  16859. @see WeakReference
  16860. */
  16861. class SharedPointer : public ReferenceCountingType
  16862. {
  16863. public:
  16864. explicit SharedPointer (ObjectType* const owner_) noexcept : owner (owner_) {}
  16865. inline ObjectType* get() const noexcept { return owner; }
  16866. void clearPointer() noexcept { owner = nullptr; }
  16867. private:
  16868. ObjectType* volatile owner;
  16869. JUCE_DECLARE_NON_COPYABLE (SharedPointer);
  16870. };
  16871. typedef ReferenceCountedObjectPtr<SharedPointer> SharedRef;
  16872. /**
  16873. This class is embedded inside an object to which you want to attach WeakReference pointers.
  16874. See the WeakReference class notes for an example of how to use this class.
  16875. @see WeakReference
  16876. */
  16877. class Master
  16878. {
  16879. public:
  16880. Master() noexcept {}
  16881. ~Master()
  16882. {
  16883. // You must remember to call clear() in your source object's destructor! See the notes
  16884. // for the WeakReference class for an example of how to do this.
  16885. jassert (sharedPointer == nullptr || sharedPointer->get() == nullptr);
  16886. }
  16887. /** The first call to this method will create an internal object that is shared by all weak
  16888. references to the object.
  16889. You need to call this from your main object's getWeakReference() method - see the WeakReference
  16890. class notes for an example.
  16891. */
  16892. const SharedRef& operator() (ObjectType* const object)
  16893. {
  16894. if (sharedPointer == nullptr)
  16895. {
  16896. sharedPointer = new SharedPointer (object);
  16897. }
  16898. else
  16899. {
  16900. // You're trying to create a weak reference to an object that has already been deleted!!
  16901. jassert (sharedPointer->get() != nullptr);
  16902. }
  16903. return sharedPointer;
  16904. }
  16905. /** The object that owns this master pointer should call this before it gets destroyed,
  16906. to zero all the references to this object that may be out there. See the WeakReference
  16907. class notes for an example of how to do this.
  16908. */
  16909. void clear()
  16910. {
  16911. if (sharedPointer != nullptr)
  16912. sharedPointer->clearPointer();
  16913. }
  16914. private:
  16915. SharedRef sharedPointer;
  16916. JUCE_DECLARE_NON_COPYABLE (Master);
  16917. };
  16918. private:
  16919. SharedRef holder;
  16920. };
  16921. #endif // __JUCE_WEAKREFERENCE_JUCEHEADER__
  16922. /*** End of inlined file: juce_WeakReference.h ***/
  16923. #endif
  16924. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  16925. #endif
  16926. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  16927. #endif
  16928. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  16929. #endif
  16930. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  16931. #endif
  16932. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  16933. #endif
  16934. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  16935. #endif
  16936. #ifndef __JUCE_JSON_JUCEHEADER__
  16937. /*** Start of inlined file: juce_JSON.h ***/
  16938. #ifndef __JUCE_JSON_JUCEHEADER__
  16939. #define __JUCE_JSON_JUCEHEADER__
  16940. class InputStream;
  16941. class OutputStream;
  16942. class File;
  16943. /**
  16944. Contains static methods for converting JSON-formatted text to and from var objects.
  16945. The var class is structurally compatible with JSON-formatted data, so these
  16946. functions allow you to parse JSON into a var object, and to convert a var
  16947. object to JSON-formatted text.
  16948. @see var
  16949. */
  16950. class JSON
  16951. {
  16952. public:
  16953. /** Parses a string of JSON-formatted text, and returns a result code containing
  16954. any parse errors.
  16955. This will return the parsed structure in the parsedResult parameter, and will
  16956. return a Result object to indicate whether parsing was successful, and if not,
  16957. it will contain an error message.
  16958. If you're not interested in the error message, you can use one of the other
  16959. shortcut parse methods, which simply return a var::null if the parsing fails.
  16960. */
  16961. static Result parse (const String& text, var& parsedResult);
  16962. /** Attempts to parse some JSON-formatted text, and returns the result as a var object.
  16963. If the parsing fails, this simply returns var::null - if you need to find out more
  16964. detail about the parse error, use the alternative parse() method which returns a Result.
  16965. */
  16966. static var parse (const String& text);
  16967. /** Attempts to parse some JSON-formatted text from a file, and returns the result
  16968. as a var object.
  16969. Note that this is just a short-cut for reading the entire file into a string and
  16970. parsing the result.
  16971. If the parsing fails, this simply returns var::null - if you need to find out more
  16972. detail about the parse error, use the alternative parse() method which returns a Result.
  16973. */
  16974. static var parse (const File& file);
  16975. /** Attempts to parse some JSON-formatted text from a stream, and returns the result
  16976. as a var object.
  16977. Note that this is just a short-cut for reading the entire stream into a string and
  16978. parsing the result.
  16979. If the parsing fails, this simply returns var::null - if you need to find out more
  16980. detail about the parse error, use the alternative parse() method which returns a Result.
  16981. */
  16982. static var parse (InputStream& input);
  16983. /** Returns a string which contains a JSON-formatted representation of the var object.
  16984. If allOnOneLine is true, the result will be compacted into a single line of text
  16985. with no carriage-returns. If false, it will be laid-out in a more human-readable format.
  16986. @see writeToStream
  16987. */
  16988. static String toString (const var& objectToFormat,
  16989. bool allOnOneLine = false);
  16990. /** Writes a JSON-formatted representation of the var object to the given stream.
  16991. If allOnOneLine is true, the result will be compacted into a single line of text
  16992. with no carriage-returns. If false, it will be laid-out in a more human-readable format.
  16993. @see toString
  16994. */
  16995. static void writeToStream (OutputStream& output,
  16996. const var& objectToFormat,
  16997. bool allOnOneLine = false);
  16998. private:
  16999. JSON(); // This class can't be instantiated - just use its static methods.
  17000. };
  17001. #endif // __JUCE_JSON_JUCEHEADER__
  17002. /*** End of inlined file: juce_JSON.h ***/
  17003. #endif
  17004. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  17005. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  17006. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  17007. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  17008. /** Used in the same way as the T(text) macro, this will attempt to translate a
  17009. string into a localised version using the LocalisedStrings class.
  17010. @see LocalisedStrings
  17011. */
  17012. #define TRANS(stringLiteral) \
  17013. JUCE_NAMESPACE::LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  17014. /**
  17015. Used to convert strings to localised foreign-language versions.
  17016. This is basically a look-up table of strings and their translated equivalents.
  17017. It can be loaded from a text file, so that you can supply a set of localised
  17018. versions of strings that you use in your app.
  17019. To use it in your code, simply call the translate() method on each string that
  17020. might have foreign versions, and if none is found, the method will just return
  17021. the original string.
  17022. The translation file should start with some lines specifying a description of
  17023. the language it contains, and also a list of ISO country codes where it might
  17024. be appropriate to use the file. After that, each line of the file should contain
  17025. a pair of quoted strings with an '=' sign.
  17026. E.g. for a french translation, the file might be:
  17027. @code
  17028. language: French
  17029. countries: fr be mc ch lu
  17030. "hello" = "bonjour"
  17031. "goodbye" = "au revoir"
  17032. @endcode
  17033. If the strings need to contain a quote character, they can use '\"' instead, and
  17034. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  17035. (you can use this to add comments).
  17036. Note that this is a singleton class, so don't create or destroy the object directly.
  17037. There's also a TRANS(text) macro defined to make it easy to use the this.
  17038. E.g. @code
  17039. printSomething (TRANS("hello"));
  17040. @endcode
  17041. This macro is used in the Juce classes themselves, so your application has a chance to
  17042. intercept and translate any internal Juce text strings that might be shown. (You can easily
  17043. get a list of all the messages by searching for the TRANS() macro in the Juce source
  17044. code).
  17045. */
  17046. class JUCE_API LocalisedStrings
  17047. {
  17048. public:
  17049. /** Creates a set of translations from the text of a translation file.
  17050. When you create one of these, you can call setCurrentMappings() to make it
  17051. the set of mappings that the system's using.
  17052. */
  17053. LocalisedStrings (const String& fileContents);
  17054. /** Creates a set of translations from a file.
  17055. When you create one of these, you can call setCurrentMappings() to make it
  17056. the set of mappings that the system's using.
  17057. */
  17058. LocalisedStrings (const File& fileToLoad);
  17059. /** Destructor. */
  17060. ~LocalisedStrings();
  17061. /** Selects the current set of mappings to be used by the system.
  17062. The object you pass in will be automatically deleted when no longer needed, so
  17063. don't keep a pointer to it. You can also pass in zero to remove the current
  17064. mappings.
  17065. See also the TRANS() macro, which uses the current set to do its translation.
  17066. @see translateWithCurrentMappings
  17067. */
  17068. static void setCurrentMappings (LocalisedStrings* newTranslations);
  17069. /** Returns the currently selected set of mappings.
  17070. This is the object that was last passed to setCurrentMappings(). It may
  17071. be 0 if none has been created.
  17072. */
  17073. static LocalisedStrings* getCurrentMappings();
  17074. /** Tries to translate a string using the currently selected set of mappings.
  17075. If no mapping has been set, or if the mapping doesn't contain a translation
  17076. for the string, this will just return the original string.
  17077. See also the TRANS() macro, which uses this method to do its translation.
  17078. @see setCurrentMappings, getCurrentMappings
  17079. */
  17080. static String translateWithCurrentMappings (const String& text);
  17081. /** Tries to translate a string using the currently selected set of mappings.
  17082. If no mapping has been set, or if the mapping doesn't contain a translation
  17083. for the string, this will just return the original string.
  17084. See also the TRANS() macro, which uses this method to do its translation.
  17085. @see setCurrentMappings, getCurrentMappings
  17086. */
  17087. static String translateWithCurrentMappings (const char* text);
  17088. /** Attempts to look up a string and return its localised version.
  17089. If the string isn't found in the list, the original string will be returned.
  17090. */
  17091. String translate (const String& text) const;
  17092. /** Returns the name of the language specified in the translation file.
  17093. This is specified in the file using a line starting with "language:", e.g.
  17094. @code
  17095. language: german
  17096. @endcode
  17097. */
  17098. String getLanguageName() const { return languageName; }
  17099. /** Returns the list of suitable country codes listed in the translation file.
  17100. These is specified in the file using a line starting with "countries:", e.g.
  17101. @code
  17102. countries: fr be mc ch lu
  17103. @endcode
  17104. The country codes are supposed to be 2-character ISO complient codes.
  17105. */
  17106. const StringArray& getCountryCodes() const { return countryCodes; }
  17107. /** Indicates whether to use a case-insensitive search when looking up a string.
  17108. This defaults to true.
  17109. */
  17110. void setIgnoresCase (bool shouldIgnoreCase);
  17111. private:
  17112. String languageName;
  17113. StringArray countryCodes;
  17114. StringPairArray translations;
  17115. void loadFromText (const String& fileContents);
  17116. JUCE_LEAK_DETECTOR (LocalisedStrings);
  17117. };
  17118. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  17119. /*** End of inlined file: juce_LocalisedStrings.h ***/
  17120. #endif
  17121. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  17122. #endif
  17123. #ifndef __JUCE_STRING_JUCEHEADER__
  17124. #endif
  17125. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  17126. #endif
  17127. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  17128. #endif
  17129. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  17130. /*** Start of inlined file: juce_StringPool.h ***/
  17131. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  17132. #define __JUCE_STRINGPOOL_JUCEHEADER__
  17133. /**
  17134. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  17135. comparison speed when dealing with many duplicate strings.
  17136. When you add a string to a pool using getPooledString, it'll return a character
  17137. array containing the same string. This array is owned by the pool, and the same array
  17138. is returned every time a matching string is asked for. This means that it's trivial to
  17139. compare two pooled strings for equality, as you can simply compare their pointers. It
  17140. also cuts down on storage if you're using many copies of the same string.
  17141. */
  17142. class JUCE_API StringPool
  17143. {
  17144. public:
  17145. /** Creates an empty pool. */
  17146. StringPool() noexcept;
  17147. /** Destructor */
  17148. ~StringPool();
  17149. /** Returns a pointer to a copy of the string that is passed in.
  17150. The pool will always return the same pointer when asked for a string that matches it.
  17151. The pool will own all the pointers that it returns, deleting them when the pool itself
  17152. is deleted.
  17153. */
  17154. const String::CharPointerType getPooledString (const String& original);
  17155. /** Returns a pointer to a copy of the string that is passed in.
  17156. The pool will always return the same pointer when asked for a string that matches it.
  17157. The pool will own all the pointers that it returns, deleting them when the pool itself
  17158. is deleted.
  17159. */
  17160. const String::CharPointerType getPooledString (const char* original);
  17161. /** Returns a pointer to a copy of the string that is passed in.
  17162. The pool will always return the same pointer when asked for a string that matches it.
  17163. The pool will own all the pointers that it returns, deleting them when the pool itself
  17164. is deleted.
  17165. */
  17166. const String::CharPointerType getPooledString (const wchar_t* original);
  17167. /** Returns the number of strings in the pool. */
  17168. int size() const noexcept;
  17169. /** Returns one of the strings in the pool, by index. */
  17170. const String::CharPointerType operator[] (int index) const noexcept;
  17171. private:
  17172. Array <String> strings;
  17173. };
  17174. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  17175. /*** End of inlined file: juce_StringPool.h ***/
  17176. #endif
  17177. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  17178. /*** Start of inlined file: juce_XmlDocument.h ***/
  17179. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  17180. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  17181. class InputSource;
  17182. /**
  17183. Parses a text-based XML document and creates an XmlElement object from it.
  17184. The parser will parse DTDs to load external entities but won't
  17185. check the document for validity against the DTD.
  17186. e.g.
  17187. @code
  17188. XmlDocument myDocument (File ("myfile.xml"));
  17189. XmlElement* mainElement = myDocument.getDocumentElement();
  17190. if (mainElement == nullptr)
  17191. {
  17192. String error = myDocument.getLastParseError();
  17193. }
  17194. else
  17195. {
  17196. ..use the element
  17197. }
  17198. @endcode
  17199. Or you can use the static helper methods for quick parsing..
  17200. @code
  17201. XmlElement* xml = XmlDocument::parse (myXmlFile);
  17202. if (xml != nullptr && xml->hasTagName ("foobar"))
  17203. {
  17204. ...etc
  17205. @endcode
  17206. @see XmlElement
  17207. */
  17208. class JUCE_API XmlDocument
  17209. {
  17210. public:
  17211. /** Creates an XmlDocument from the xml text.
  17212. The text doesn't actually get parsed until the getDocumentElement() method is called.
  17213. */
  17214. XmlDocument (const String& documentText);
  17215. /** Creates an XmlDocument from a file.
  17216. The text doesn't actually get parsed until the getDocumentElement() method is called.
  17217. */
  17218. XmlDocument (const File& file);
  17219. /** Destructor. */
  17220. ~XmlDocument();
  17221. /** Creates an XmlElement object to represent the main document node.
  17222. This method will do the actual parsing of the text, and if there's a
  17223. parse error, it may returns 0 (and you can find out the error using
  17224. the getLastParseError() method).
  17225. See also the parse() methods, which provide a shorthand way to quickly
  17226. parse a file or string.
  17227. @param onlyReadOuterDocumentElement if true, the parser will only read the
  17228. first section of the file, and will only
  17229. return the outer document element - this
  17230. allows quick checking of large files to
  17231. see if they contain the correct type of
  17232. tag, without having to parse the entire file
  17233. @returns a new XmlElement which the caller will need to delete, or null if
  17234. there was an error.
  17235. @see getLastParseError
  17236. */
  17237. XmlElement* getDocumentElement (bool onlyReadOuterDocumentElement = false);
  17238. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  17239. @returns the error, or an empty string if there was no error.
  17240. */
  17241. const String& getLastParseError() const noexcept;
  17242. /** Sets an input source object to use for parsing documents that reference external entities.
  17243. If the document has been created from a file, this probably won't be needed, but
  17244. if you're parsing some text and there might be a DTD that references external
  17245. files, you may need to create a custom input source that can retrieve the
  17246. other files it needs.
  17247. The object that is passed-in will be deleted automatically when no longer needed.
  17248. @see InputSource
  17249. */
  17250. void setInputSource (InputSource* newSource) noexcept;
  17251. /** Sets a flag to change the treatment of empty text elements.
  17252. If this is true (the default state), then any text elements that contain only
  17253. whitespace characters will be ingored during parsing. If you need to catch
  17254. whitespace-only text, then you should set this to false before calling the
  17255. getDocumentElement() method.
  17256. */
  17257. void setEmptyTextElementsIgnored (bool shouldBeIgnored) noexcept;
  17258. /** A handy static method that parses a file.
  17259. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  17260. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  17261. */
  17262. static XmlElement* parse (const File& file);
  17263. /** A handy static method that parses some XML data.
  17264. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  17265. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  17266. */
  17267. static XmlElement* parse (const String& xmlData);
  17268. private:
  17269. String originalText;
  17270. String::CharPointerType input;
  17271. bool outOfData, errorOccurred;
  17272. String lastError, dtdText;
  17273. StringArray tokenisedDTD;
  17274. bool needToLoadDTD, ignoreEmptyTextElements;
  17275. ScopedPointer <InputSource> inputSource;
  17276. void setLastError (const String& desc, bool carryOn);
  17277. void skipHeader();
  17278. void skipNextWhiteSpace();
  17279. juce_wchar readNextChar() noexcept;
  17280. XmlElement* readNextElement (bool alsoParseSubElements);
  17281. void readChildElements (XmlElement* parent);
  17282. int findNextTokenLength() noexcept;
  17283. void readQuotedString (String& result);
  17284. void readEntity (String& result);
  17285. String getFileContents (const String& filename) const;
  17286. String expandEntity (const String& entity);
  17287. String expandExternalEntity (const String& entity);
  17288. String getParameterEntity (const String& entity);
  17289. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XmlDocument);
  17290. };
  17291. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  17292. /*** End of inlined file: juce_XmlDocument.h ***/
  17293. #endif
  17294. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  17295. #endif
  17296. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  17297. #endif
  17298. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17299. /*** Start of inlined file: juce_InterProcessLock.h ***/
  17300. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17301. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17302. /**
  17303. Acts as a critical section which processes can use to block each other.
  17304. @see CriticalSection
  17305. */
  17306. class JUCE_API InterProcessLock
  17307. {
  17308. public:
  17309. /** Creates a lock object.
  17310. @param name a name that processes will use to identify this lock object
  17311. */
  17312. explicit InterProcessLock (const String& name);
  17313. /** Destructor.
  17314. This will also release the lock if it's currently held by this process.
  17315. */
  17316. ~InterProcessLock();
  17317. /** Attempts to lock the critical section.
  17318. @param timeOutMillisecs how many milliseconds to wait if the lock
  17319. is already held by another process - a value of
  17320. 0 will return immediately, negative values will wait
  17321. forever
  17322. @returns true if the lock could be gained within the timeout period, or
  17323. false if the timeout expired.
  17324. */
  17325. bool enter (int timeOutMillisecs = -1);
  17326. /** Releases the lock if it's currently held by this process.
  17327. */
  17328. void exit();
  17329. /**
  17330. Automatically locks and unlocks an InterProcessLock object.
  17331. This works like a ScopedLock, but using an InterprocessLock rather than
  17332. a CriticalSection.
  17333. @see ScopedLock
  17334. */
  17335. class ScopedLockType
  17336. {
  17337. public:
  17338. /** Creates a scoped lock.
  17339. As soon as it is created, this will lock the InterProcessLock, and
  17340. when the ScopedLockType object is deleted, the InterProcessLock will
  17341. be unlocked.
  17342. Note that since an InterprocessLock can fail due to errors, you should check
  17343. isLocked() to make sure that the lock was successful before using it.
  17344. Make sure this object is created and deleted by the same thread,
  17345. otherwise there are no guarantees what will happen! Best just to use it
  17346. as a local stack object, rather than creating one with the new() operator.
  17347. */
  17348. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  17349. /** Destructor.
  17350. The InterProcessLock will be unlocked when the destructor is called.
  17351. Make sure this object is created and deleted by the same thread,
  17352. otherwise there are no guarantees what will happen!
  17353. */
  17354. inline ~ScopedLockType() { lock_.exit(); }
  17355. /** Returns true if the InterProcessLock was successfully locked. */
  17356. bool isLocked() const noexcept { return lockWasSuccessful; }
  17357. private:
  17358. InterProcessLock& lock_;
  17359. bool lockWasSuccessful;
  17360. JUCE_DECLARE_NON_COPYABLE (ScopedLockType);
  17361. };
  17362. private:
  17363. class Pimpl;
  17364. friend class ScopedPointer <Pimpl>;
  17365. ScopedPointer <Pimpl> pimpl;
  17366. CriticalSection lock;
  17367. String name;
  17368. JUCE_DECLARE_NON_COPYABLE (InterProcessLock);
  17369. };
  17370. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  17371. /*** End of inlined file: juce_InterProcessLock.h ***/
  17372. #endif
  17373. #ifndef __JUCE_PROCESS_JUCEHEADER__
  17374. /*** Start of inlined file: juce_Process.h ***/
  17375. #ifndef __JUCE_PROCESS_JUCEHEADER__
  17376. #define __JUCE_PROCESS_JUCEHEADER__
  17377. /** Represents the current executable's process.
  17378. This contains methods for controlling the current application at the
  17379. process-level.
  17380. @see Thread, JUCEApplication
  17381. */
  17382. class JUCE_API Process
  17383. {
  17384. public:
  17385. enum ProcessPriority
  17386. {
  17387. LowPriority = 0,
  17388. NormalPriority = 1,
  17389. HighPriority = 2,
  17390. RealtimePriority = 3
  17391. };
  17392. /** Changes the current process's priority.
  17393. @param priority the process priority, where
  17394. 0=low, 1=normal, 2=high, 3=realtime
  17395. */
  17396. static void setPriority (const ProcessPriority priority);
  17397. /** Kills the current process immediately.
  17398. This is an emergency process terminator that kills the application
  17399. immediately - it's intended only for use only when something goes
  17400. horribly wrong.
  17401. @see JUCEApplication::quit
  17402. */
  17403. static void terminate();
  17404. /** Returns true if this application process is the one that the user is
  17405. currently using.
  17406. */
  17407. static bool isForegroundProcess();
  17408. /** Raises the current process's privilege level.
  17409. Does nothing if this isn't supported by the current OS, or if process
  17410. privilege level is fixed.
  17411. */
  17412. static void raisePrivilege();
  17413. /** Lowers the current process's privilege level.
  17414. Does nothing if this isn't supported by the current OS, or if process
  17415. privilege level is fixed.
  17416. */
  17417. static void lowerPrivilege();
  17418. /** Returns true if this process is being hosted by a debugger.
  17419. */
  17420. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  17421. private:
  17422. Process();
  17423. JUCE_DECLARE_NON_COPYABLE (Process);
  17424. };
  17425. #endif // __JUCE_PROCESS_JUCEHEADER__
  17426. /*** End of inlined file: juce_Process.h ***/
  17427. #endif
  17428. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  17429. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  17430. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  17431. #define __JUCE_READWRITELOCK_JUCEHEADER__
  17432. /*** Start of inlined file: juce_SpinLock.h ***/
  17433. #ifndef __JUCE_SPINLOCK_JUCEHEADER__
  17434. #define __JUCE_SPINLOCK_JUCEHEADER__
  17435. /**
  17436. A simple spin-lock class that can be used as a simple, low-overhead mutex for
  17437. uncontended situations.
  17438. Note that unlike a CriticalSection, this type of lock is not re-entrant, and may
  17439. be less efficient when used it a highly contended situation, but it's very small and
  17440. requires almost no initialisation.
  17441. It's most appropriate for simple situations where you're only going to hold the
  17442. lock for a very brief time.
  17443. @see CriticalSection
  17444. */
  17445. class JUCE_API SpinLock
  17446. {
  17447. public:
  17448. inline SpinLock() noexcept {}
  17449. inline ~SpinLock() noexcept {}
  17450. /** Acquires the lock.
  17451. This will block until the lock has been successfully acquired by this thread.
  17452. Note that a SpinLock is NOT re-entrant, and is not smart enough to know whether the
  17453. caller thread already has the lock - so if a thread tries to acquire a lock that it
  17454. already holds, this method will never return!
  17455. It's strongly recommended that you never call this method directly - instead use the
  17456. ScopedLockType class to manage the locking using an RAII pattern instead.
  17457. */
  17458. void enter() const noexcept;
  17459. /** Attempts to acquire the lock, returning true if this was successful. */
  17460. inline bool tryEnter() const noexcept
  17461. {
  17462. return lock.compareAndSetBool (1, 0);
  17463. }
  17464. /** Releases the lock. */
  17465. inline void exit() const noexcept
  17466. {
  17467. jassert (lock.value == 1); // Agh! Releasing a lock that isn't currently held!
  17468. lock = 0;
  17469. }
  17470. /** Provides the type of scoped lock to use for locking a SpinLock. */
  17471. typedef GenericScopedLock <SpinLock> ScopedLockType;
  17472. /** Provides the type of scoped unlocker to use with a SpinLock. */
  17473. typedef GenericScopedUnlock <SpinLock> ScopedUnlockType;
  17474. private:
  17475. mutable Atomic<int> lock;
  17476. JUCE_DECLARE_NON_COPYABLE (SpinLock);
  17477. };
  17478. #endif // __JUCE_SPINLOCK_JUCEHEADER__
  17479. /*** End of inlined file: juce_SpinLock.h ***/
  17480. /*** Start of inlined file: juce_WaitableEvent.h ***/
  17481. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  17482. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  17483. /**
  17484. Allows threads to wait for events triggered by other threads.
  17485. A thread can call wait() on a WaitableObject, and this will suspend the
  17486. calling thread until another thread wakes it up by calling the signal()
  17487. method.
  17488. */
  17489. class JUCE_API WaitableEvent
  17490. {
  17491. public:
  17492. /** Creates a WaitableEvent object.
  17493. @param manualReset If this is false, the event will be reset automatically when the wait()
  17494. method is called. If manualReset is true, then once the event is signalled,
  17495. the only way to reset it will be by calling the reset() method.
  17496. */
  17497. WaitableEvent (bool manualReset = false) noexcept;
  17498. /** Destructor.
  17499. If other threads are waiting on this object when it gets deleted, this
  17500. can cause nasty errors, so be careful!
  17501. */
  17502. ~WaitableEvent() noexcept;
  17503. /** Suspends the calling thread until the event has been signalled.
  17504. This will wait until the object's signal() method is called by another thread,
  17505. or until the timeout expires.
  17506. After the event has been signalled, this method will return true and if manualReset
  17507. was set to false in the WaitableEvent's constructor, then the event will be reset.
  17508. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  17509. value will cause it to wait forever.
  17510. @returns true if the object has been signalled, false if the timeout expires first.
  17511. @see signal, reset
  17512. */
  17513. bool wait (int timeOutMilliseconds = -1) const noexcept;
  17514. /** Wakes up any threads that are currently waiting on this object.
  17515. If signal() is called when nothing is waiting, the next thread to call wait()
  17516. will return immediately and reset the signal.
  17517. If the WaitableEvent is manual reset, all current and future threads that wait upon this
  17518. object will be woken, until reset() is explicitly called.
  17519. If the WaitableEvent is automatic reset, and one or more threads is waiting upon the object,
  17520. then one of them will be woken up. If no threads are currently waiting, then the next thread
  17521. to call wait() will be woken up. As soon as a thread is woken, the signal is automatically
  17522. reset.
  17523. @see wait, reset
  17524. */
  17525. void signal() const noexcept;
  17526. /** Resets the event to an unsignalled state.
  17527. If it's not already signalled, this does nothing.
  17528. */
  17529. void reset() const noexcept;
  17530. private:
  17531. void* internal;
  17532. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WaitableEvent);
  17533. };
  17534. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  17535. /*** End of inlined file: juce_WaitableEvent.h ***/
  17536. /*** Start of inlined file: juce_Thread.h ***/
  17537. #ifndef __JUCE_THREAD_JUCEHEADER__
  17538. #define __JUCE_THREAD_JUCEHEADER__
  17539. /**
  17540. Encapsulates a thread.
  17541. Subclasses derive from Thread and implement the run() method, in which they
  17542. do their business. The thread can then be started with the startThread() method
  17543. and controlled with various other methods.
  17544. This class also contains some thread-related static methods, such
  17545. as sleep(), yield(), getCurrentThreadId() etc.
  17546. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  17547. MessageManagerLock
  17548. */
  17549. class JUCE_API Thread
  17550. {
  17551. public:
  17552. /**
  17553. Creates a thread.
  17554. When first created, the thread is not running. Use the startThread()
  17555. method to start it.
  17556. */
  17557. explicit Thread (const String& threadName);
  17558. /** Destructor.
  17559. Deleting a Thread object that is running will only give the thread a
  17560. brief opportunity to stop itself cleanly, so it's recommended that you
  17561. should always call stopThread() with a decent timeout before deleting,
  17562. to avoid the thread being forcibly killed (which is a Bad Thing).
  17563. */
  17564. virtual ~Thread();
  17565. /** Must be implemented to perform the thread's actual code.
  17566. Remember that the thread must regularly check the threadShouldExit()
  17567. method whilst running, and if this returns true it should return from
  17568. the run() method as soon as possible to avoid being forcibly killed.
  17569. @see threadShouldExit, startThread
  17570. */
  17571. virtual void run() = 0;
  17572. // Thread control functions..
  17573. /** Starts the thread running.
  17574. This will start the thread's run() method.
  17575. (if it's already started, startThread() won't do anything).
  17576. @see stopThread
  17577. */
  17578. void startThread();
  17579. /** Starts the thread with a given priority.
  17580. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  17581. If the thread is already running, its priority will be changed.
  17582. @see startThread, setPriority
  17583. */
  17584. void startThread (int priority);
  17585. /** Attempts to stop the thread running.
  17586. This method will cause the threadShouldExit() method to return true
  17587. and call notify() in case the thread is currently waiting.
  17588. Hopefully the thread will then respond to this by exiting cleanly, and
  17589. the stopThread method will wait for a given time-period for this to
  17590. happen.
  17591. If the thread is stuck and fails to respond after the time-out, it gets
  17592. forcibly killed, which is a very bad thing to happen, as it could still
  17593. be holding locks, etc. which are needed by other parts of your program.
  17594. @param timeOutMilliseconds The number of milliseconds to wait for the
  17595. thread to finish before killing it by force. A negative
  17596. value in here will wait forever.
  17597. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  17598. */
  17599. void stopThread (int timeOutMilliseconds);
  17600. /** Returns true if the thread is currently active */
  17601. bool isThreadRunning() const;
  17602. /** Sets a flag to tell the thread it should stop.
  17603. Calling this means that the threadShouldExit() method will then return true.
  17604. The thread should be regularly checking this to see whether it should exit.
  17605. If your thread makes use of wait(), you might want to call notify() after calling
  17606. this method, to interrupt any waits that might be in progress, and allow it
  17607. to reach a point where it can exit.
  17608. @see threadShouldExit
  17609. @see waitForThreadToExit
  17610. */
  17611. void signalThreadShouldExit();
  17612. /** Checks whether the thread has been told to stop running.
  17613. Threads need to check this regularly, and if it returns true, they should
  17614. return from their run() method at the first possible opportunity.
  17615. @see signalThreadShouldExit
  17616. */
  17617. inline bool threadShouldExit() const { return threadShouldExit_; }
  17618. /** Waits for the thread to stop.
  17619. This will waits until isThreadRunning() is false or until a timeout expires.
  17620. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  17621. is less than zero, it will wait forever.
  17622. @returns true if the thread exits, or false if the timeout expires first.
  17623. */
  17624. bool waitForThreadToExit (int timeOutMilliseconds) const;
  17625. /** Changes the thread's priority.
  17626. May return false if for some reason the priority can't be changed.
  17627. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  17628. of 5 is normal.
  17629. */
  17630. bool setPriority (int priority);
  17631. /** Changes the priority of the caller thread.
  17632. Similar to setPriority(), but this static method acts on the caller thread.
  17633. May return false if for some reason the priority can't be changed.
  17634. @see setPriority
  17635. */
  17636. static bool setCurrentThreadPriority (int priority);
  17637. /** Sets the affinity mask for the thread.
  17638. This will only have an effect next time the thread is started - i.e. if the
  17639. thread is already running when called, it'll have no effect.
  17640. @see setCurrentThreadAffinityMask
  17641. */
  17642. void setAffinityMask (uint32 affinityMask);
  17643. /** Changes the affinity mask for the caller thread.
  17644. This will change the affinity mask for the thread that calls this static method.
  17645. @see setAffinityMask
  17646. */
  17647. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  17648. // this can be called from any thread that needs to pause..
  17649. static void JUCE_CALLTYPE sleep (int milliseconds);
  17650. /** Yields the calling thread's current time-slot. */
  17651. static void JUCE_CALLTYPE yield();
  17652. /** Makes the thread wait for a notification.
  17653. This puts the thread to sleep until either the timeout period expires, or
  17654. another thread calls the notify() method to wake it up.
  17655. A negative time-out value means that the method will wait indefinitely.
  17656. @returns true if the event has been signalled, false if the timeout expires.
  17657. */
  17658. bool wait (int timeOutMilliseconds) const;
  17659. /** Wakes up the thread.
  17660. If the thread has called the wait() method, this will wake it up.
  17661. @see wait
  17662. */
  17663. void notify() const;
  17664. /** A value type used for thread IDs.
  17665. @see getCurrentThreadId(), getThreadId()
  17666. */
  17667. typedef void* ThreadID;
  17668. /** Returns an id that identifies the caller thread.
  17669. To find the ID of a particular thread object, use getThreadId().
  17670. @returns a unique identifier that identifies the calling thread.
  17671. @see getThreadId
  17672. */
  17673. static ThreadID getCurrentThreadId();
  17674. /** Finds the thread object that is currently running.
  17675. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  17676. object associated with them, so this will return 0.
  17677. */
  17678. static Thread* getCurrentThread();
  17679. /** Returns the ID of this thread.
  17680. That means the ID of this thread object - not of the thread that's calling the method.
  17681. This can change when the thread is started and stopped, and will be invalid if the
  17682. thread's not actually running.
  17683. @see getCurrentThreadId
  17684. */
  17685. ThreadID getThreadId() const noexcept { return threadId_; }
  17686. /** Returns the name of the thread.
  17687. This is the name that gets set in the constructor.
  17688. */
  17689. const String& getThreadName() const { return threadName_; }
  17690. /** Changes the name of the caller thread.
  17691. Different OSes may place different length or content limits on this name.
  17692. */
  17693. static void setCurrentThreadName (const String& newThreadName);
  17694. /** Returns the number of currently-running threads.
  17695. @returns the number of Thread objects known to be currently running.
  17696. @see stopAllThreads
  17697. */
  17698. static int getNumRunningThreads();
  17699. /** Tries to stop all currently-running threads.
  17700. This will attempt to stop all the threads known to be running at the moment.
  17701. */
  17702. static void stopAllThreads (int timeoutInMillisecs);
  17703. private:
  17704. const String threadName_;
  17705. void* volatile threadHandle_;
  17706. ThreadID threadId_;
  17707. CriticalSection startStopLock;
  17708. WaitableEvent startSuspensionEvent_, defaultEvent_;
  17709. int threadPriority_;
  17710. uint32 affinityMask_;
  17711. bool volatile threadShouldExit_;
  17712. #ifndef DOXYGEN
  17713. friend class MessageManager;
  17714. friend void JUCE_API juce_threadEntryPoint (void*);
  17715. #endif
  17716. void launchThread();
  17717. void closeThreadHandle();
  17718. void killThread();
  17719. void threadEntryPoint();
  17720. static bool setThreadPriority (void* handle, int priority);
  17721. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread);
  17722. };
  17723. #endif // __JUCE_THREAD_JUCEHEADER__
  17724. /*** End of inlined file: juce_Thread.h ***/
  17725. /**
  17726. A critical section that allows multiple simultaneous readers.
  17727. Features of this type of lock are:
  17728. - Multiple readers can hold the lock at the same time, but only one writer
  17729. can hold it at once.
  17730. - Writers trying to gain the lock will be blocked until all readers and writers
  17731. have released it
  17732. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  17733. blocked until the writer has obtained and released it
  17734. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  17735. there are no other readers
  17736. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  17737. - Recursive locking is supported.
  17738. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  17739. */
  17740. class JUCE_API ReadWriteLock
  17741. {
  17742. public:
  17743. /**
  17744. Creates a ReadWriteLock object.
  17745. */
  17746. ReadWriteLock() noexcept;
  17747. /** Destructor.
  17748. If the object is deleted whilst locked, any subsequent behaviour
  17749. is unpredictable.
  17750. */
  17751. ~ReadWriteLock() noexcept;
  17752. /** Locks this object for reading.
  17753. Multiple threads can simulaneously lock the object for reading, but if another
  17754. thread has it locked for writing, then this will block until it releases the
  17755. lock.
  17756. @see exitRead, ScopedReadLock
  17757. */
  17758. void enterRead() const noexcept;
  17759. /** Releases the read-lock.
  17760. If the caller thread hasn't got the lock, this can have unpredictable results.
  17761. If the enterRead() method has been called multiple times by the thread, each
  17762. call must be matched by a call to exitRead() before other threads will be allowed
  17763. to take over the lock.
  17764. @see enterRead, ScopedReadLock
  17765. */
  17766. void exitRead() const noexcept;
  17767. /** Locks this object for writing.
  17768. This will block until any other threads that have it locked for reading or
  17769. writing have released their lock.
  17770. @see exitWrite, ScopedWriteLock
  17771. */
  17772. void enterWrite() const noexcept;
  17773. /** Tries to lock this object for writing.
  17774. This is like enterWrite(), but doesn't block - it returns true if it manages
  17775. to obtain the lock.
  17776. @see enterWrite
  17777. */
  17778. bool tryEnterWrite() const noexcept;
  17779. /** Releases the write-lock.
  17780. If the caller thread hasn't got the lock, this can have unpredictable results.
  17781. If the enterWrite() method has been called multiple times by the thread, each
  17782. call must be matched by a call to exit() before other threads will be allowed
  17783. to take over the lock.
  17784. @see enterWrite, ScopedWriteLock
  17785. */
  17786. void exitWrite() const noexcept;
  17787. private:
  17788. SpinLock accessLock;
  17789. WaitableEvent waitEvent;
  17790. mutable int numWaitingWriters, numWriters;
  17791. mutable Thread::ThreadID writerThreadId;
  17792. mutable Array <Thread::ThreadID> readerThreads;
  17793. JUCE_DECLARE_NON_COPYABLE (ReadWriteLock);
  17794. };
  17795. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  17796. /*** End of inlined file: juce_ReadWriteLock.h ***/
  17797. #endif
  17798. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  17799. #endif
  17800. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17801. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  17802. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17803. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17804. /**
  17805. Automatically locks and unlocks a ReadWriteLock object.
  17806. Use one of these as a local variable to control access to a ReadWriteLock.
  17807. e.g. @code
  17808. ReadWriteLock myLock;
  17809. for (;;)
  17810. {
  17811. const ScopedReadLock myScopedLock (myLock);
  17812. // myLock is now locked
  17813. ...do some stuff...
  17814. // myLock gets unlocked here.
  17815. }
  17816. @endcode
  17817. @see ReadWriteLock, ScopedWriteLock
  17818. */
  17819. class JUCE_API ScopedReadLock
  17820. {
  17821. public:
  17822. /** Creates a ScopedReadLock.
  17823. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  17824. when the ScopedReadLock object is deleted, the ReadWriteLock will
  17825. be unlocked.
  17826. Make sure this object is created and deleted by the same thread,
  17827. otherwise there are no guarantees what will happen! Best just to use it
  17828. as a local stack object, rather than creating one with the new() operator.
  17829. */
  17830. inline explicit ScopedReadLock (const ReadWriteLock& lock) noexcept : lock_ (lock) { lock.enterRead(); }
  17831. /** Destructor.
  17832. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  17833. Make sure this object is created and deleted by the same thread,
  17834. otherwise there are no guarantees what will happen!
  17835. */
  17836. inline ~ScopedReadLock() noexcept { lock_.exitRead(); }
  17837. private:
  17838. const ReadWriteLock& lock_;
  17839. JUCE_DECLARE_NON_COPYABLE (ScopedReadLock);
  17840. };
  17841. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17842. /*** End of inlined file: juce_ScopedReadLock.h ***/
  17843. #endif
  17844. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17845. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  17846. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17847. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17848. /**
  17849. Automatically locks and unlocks a ReadWriteLock object.
  17850. Use one of these as a local variable to control access to a ReadWriteLock.
  17851. e.g. @code
  17852. ReadWriteLock myLock;
  17853. for (;;)
  17854. {
  17855. const ScopedWriteLock myScopedLock (myLock);
  17856. // myLock is now locked
  17857. ...do some stuff...
  17858. // myLock gets unlocked here.
  17859. }
  17860. @endcode
  17861. @see ReadWriteLock, ScopedReadLock
  17862. */
  17863. class JUCE_API ScopedWriteLock
  17864. {
  17865. public:
  17866. /** Creates a ScopedWriteLock.
  17867. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  17868. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  17869. be unlocked.
  17870. Make sure this object is created and deleted by the same thread,
  17871. otherwise there are no guarantees what will happen! Best just to use it
  17872. as a local stack object, rather than creating one with the new() operator.
  17873. */
  17874. inline explicit ScopedWriteLock (const ReadWriteLock& lock) noexcept : lock_ (lock) { lock.enterWrite(); }
  17875. /** Destructor.
  17876. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  17877. Make sure this object is created and deleted by the same thread,
  17878. otherwise there are no guarantees what will happen!
  17879. */
  17880. inline ~ScopedWriteLock() noexcept { lock_.exitWrite(); }
  17881. private:
  17882. const ReadWriteLock& lock_;
  17883. JUCE_DECLARE_NON_COPYABLE (ScopedWriteLock);
  17884. };
  17885. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17886. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  17887. #endif
  17888. #ifndef __JUCE_SPINLOCK_JUCEHEADER__
  17889. #endif
  17890. #ifndef __JUCE_THREAD_JUCEHEADER__
  17891. #endif
  17892. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  17893. /*** Start of inlined file: juce_ThreadPool.h ***/
  17894. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  17895. #define __JUCE_THREADPOOL_JUCEHEADER__
  17896. class ThreadPool;
  17897. class ThreadPoolThread;
  17898. /**
  17899. A task that is executed by a ThreadPool object.
  17900. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  17901. its threads.
  17902. The runJob() method needs to be implemented to do the task, and if the code that
  17903. does the work takes a significant time to run, it must keep checking the shouldExit()
  17904. method to see if something is trying to interrupt the job. If shouldExit() returns
  17905. true, the runJob() method must return immediately.
  17906. @see ThreadPool, Thread
  17907. */
  17908. class JUCE_API ThreadPoolJob
  17909. {
  17910. public:
  17911. /** Creates a thread pool job object.
  17912. After creating your job, add it to a thread pool with ThreadPool::addJob().
  17913. */
  17914. explicit ThreadPoolJob (const String& name);
  17915. /** Destructor. */
  17916. virtual ~ThreadPoolJob();
  17917. /** Returns the name of this job.
  17918. @see setJobName
  17919. */
  17920. String getJobName() const;
  17921. /** Changes the job's name.
  17922. @see getJobName
  17923. */
  17924. void setJobName (const String& newName);
  17925. /** These are the values that can be returned by the runJob() method.
  17926. */
  17927. enum JobStatus
  17928. {
  17929. jobHasFinished = 0, /**< indicates that the job has finished and can be
  17930. removed from the pool. */
  17931. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  17932. should be automatically deleted by the pool. */
  17933. jobNeedsRunningAgain /**< indicates that the job would like to be called
  17934. again when a thread is free. */
  17935. };
  17936. /** Peforms the actual work that this job needs to do.
  17937. Your subclass must implement this method, in which is does its work.
  17938. If the code in this method takes a significant time to run, it must repeatedly check
  17939. the shouldExit() method to see if something is trying to interrupt the job.
  17940. If shouldExit() ever returns true, the runJob() method must return immediately.
  17941. If this method returns jobHasFinished, then the job will be removed from the pool
  17942. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  17943. pool and will get a chance to run again as soon as a thread is free.
  17944. @see shouldExit()
  17945. */
  17946. virtual JobStatus runJob() = 0;
  17947. /** Returns true if this job is currently running its runJob() method. */
  17948. bool isRunning() const { return isActive; }
  17949. /** Returns true if something is trying to interrupt this job and make it stop.
  17950. Your runJob() method must call this whenever it gets a chance, and if it ever
  17951. returns true, the runJob() method must return immediately.
  17952. @see signalJobShouldExit()
  17953. */
  17954. bool shouldExit() const { return shouldStop; }
  17955. /** Calling this will cause the shouldExit() method to return true, and the job
  17956. should (if it's been implemented correctly) stop as soon as possible.
  17957. @see shouldExit()
  17958. */
  17959. void signalJobShouldExit();
  17960. private:
  17961. friend class ThreadPool;
  17962. friend class ThreadPoolThread;
  17963. String jobName;
  17964. ThreadPool* pool;
  17965. bool shouldStop, isActive, shouldBeDeleted;
  17966. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob);
  17967. };
  17968. /**
  17969. A set of threads that will run a list of jobs.
  17970. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  17971. will be called by the next pooled thread that becomes free.
  17972. @see ThreadPoolJob, Thread
  17973. */
  17974. class JUCE_API ThreadPool
  17975. {
  17976. public:
  17977. /** Creates a thread pool.
  17978. Once you've created a pool, you can give it some things to do with the addJob()
  17979. method.
  17980. @param numberOfThreads the maximum number of actual threads to run.
  17981. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  17982. until there are some jobs to run. If false, then
  17983. all the threads will be fired-up immediately so that
  17984. they're ready for action
  17985. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  17986. inactive for this length of time, they will automatically
  17987. be stopped until more jobs come along and they're needed
  17988. */
  17989. ThreadPool (int numberOfThreads,
  17990. bool startThreadsOnlyWhenNeeded = true,
  17991. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  17992. /** Destructor.
  17993. This will attempt to remove all the jobs before deleting, but if you want to
  17994. specify a timeout, you should call removeAllJobs() explicitly before deleting
  17995. the pool.
  17996. */
  17997. ~ThreadPool();
  17998. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  17999. for some kind of operation.
  18000. @see ThreadPool::removeAllJobs
  18001. */
  18002. class JUCE_API JobSelector
  18003. {
  18004. public:
  18005. virtual ~JobSelector() {}
  18006. /** Should return true if the specified thread matches your criteria for whatever
  18007. operation that this object is being used for.
  18008. Any implementation of this method must be extremely fast and thread-safe!
  18009. */
  18010. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  18011. };
  18012. /** Adds a job to the queue.
  18013. Once a job has been added, then the next time a thread is free, it will run
  18014. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  18015. runJob() method, the pool will either remove the job from the pool or add it to
  18016. the back of the queue to be run again.
  18017. */
  18018. void addJob (ThreadPoolJob* job);
  18019. /** Tries to remove a job from the pool.
  18020. If the job isn't yet running, this will simply remove it. If it is running, it
  18021. will wait for it to finish.
  18022. If the timeout period expires before the job finishes running, then the job will be
  18023. left in the pool and this will return false. It returns true if the job is sucessfully
  18024. stopped and removed.
  18025. @param job the job to remove
  18026. @param interruptIfRunning if true, then if the job is currently busy, its
  18027. ThreadPoolJob::signalJobShouldExit() method will be called to try
  18028. to interrupt it. If false, then if the job will be allowed to run
  18029. until it stops normally (or the timeout expires)
  18030. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  18031. before giving up and returning false
  18032. */
  18033. bool removeJob (ThreadPoolJob* job,
  18034. bool interruptIfRunning,
  18035. int timeOutMilliseconds);
  18036. /** Tries to remove all jobs from the pool.
  18037. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  18038. methods called to try to interrupt them
  18039. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  18040. before giving up and returning false
  18041. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  18042. they will simply be removed from the pool. Jobs that are already running when
  18043. this method is called can choose whether they should be deleted by
  18044. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  18045. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  18046. jobs should be removed. If it is zero, all jobs are removed
  18047. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  18048. expires while waiting for one or more jobs to stop
  18049. */
  18050. bool removeAllJobs (bool interruptRunningJobs,
  18051. int timeOutMilliseconds,
  18052. bool deleteInactiveJobs = false,
  18053. JobSelector* selectedJobsToRemove = 0);
  18054. /** Returns the number of jobs currently running or queued.
  18055. */
  18056. int getNumJobs() const;
  18057. /** Returns one of the jobs in the queue.
  18058. Note that this can be a very volatile list as jobs might be continuously getting shifted
  18059. around in the list, and this method may return 0 if the index is currently out-of-range.
  18060. */
  18061. ThreadPoolJob* getJob (int index) const;
  18062. /** Returns true if the given job is currently queued or running.
  18063. @see isJobRunning()
  18064. */
  18065. bool contains (const ThreadPoolJob* job) const;
  18066. /** Returns true if the given job is currently being run by a thread.
  18067. */
  18068. bool isJobRunning (const ThreadPoolJob* job) const;
  18069. /** Waits until a job has finished running and has been removed from the pool.
  18070. This will wait until the job is no longer in the pool - i.e. until its
  18071. runJob() method returns ThreadPoolJob::jobHasFinished.
  18072. If the timeout period expires before the job finishes, this will return false;
  18073. it returns true if the job has finished successfully.
  18074. */
  18075. bool waitForJobToFinish (const ThreadPoolJob* job,
  18076. int timeOutMilliseconds) const;
  18077. /** Returns a list of the names of all the jobs currently running or queued.
  18078. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  18079. */
  18080. StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  18081. /** Changes the priority of all the threads.
  18082. This will call Thread::setPriority() for each thread in the pool.
  18083. May return false if for some reason the priority can't be changed.
  18084. */
  18085. bool setThreadPriorities (int newPriority);
  18086. private:
  18087. const int threadStopTimeout;
  18088. int priority;
  18089. class ThreadPoolThread;
  18090. friend class OwnedArray <ThreadPoolThread>;
  18091. OwnedArray <ThreadPoolThread> threads;
  18092. Array <ThreadPoolJob*> jobs;
  18093. CriticalSection lock;
  18094. uint32 lastJobEndTime;
  18095. WaitableEvent jobFinishedSignal;
  18096. friend class ThreadPoolThread;
  18097. bool runNextJob();
  18098. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool);
  18099. };
  18100. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  18101. /*** End of inlined file: juce_ThreadPool.h ***/
  18102. #endif
  18103. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  18104. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  18105. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  18106. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  18107. class TimeSliceThread;
  18108. /**
  18109. Used by the TimeSliceThread class.
  18110. To register your class with a TimeSliceThread, derive from this class and
  18111. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  18112. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  18113. deleting your client!
  18114. @see TimeSliceThread
  18115. */
  18116. class JUCE_API TimeSliceClient
  18117. {
  18118. public:
  18119. /** Destructor. */
  18120. virtual ~TimeSliceClient() {}
  18121. /** Called back by a TimeSliceThread.
  18122. When you register this class with it, a TimeSliceThread will repeatedly call
  18123. this method.
  18124. The implementation of this method should use its time-slice to do something that's
  18125. quick - never block for longer than absolutely necessary.
  18126. @returns Your method should return the number of milliseconds which it would like to wait before being called
  18127. again. Returning 0 will make the thread call again as soon as possible (after possibly servicing
  18128. other busy clients). If you return a value below zero, your client will be removed from the list of clients,
  18129. and won't be called again. The value you specify isn't a guaranteee, and is only used as a hint by the
  18130. thread - the actual time before the next callback may be more or less than specified.
  18131. You can force the TimeSliceThread to wake up and poll again immediately by calling its notify() method.
  18132. */
  18133. virtual int useTimeSlice() = 0;
  18134. private:
  18135. friend class TimeSliceThread;
  18136. Time nextCallTime;
  18137. };
  18138. /**
  18139. A thread that keeps a list of clients, and calls each one in turn, giving them
  18140. all a chance to run some sort of short task.
  18141. @see TimeSliceClient, Thread
  18142. */
  18143. class JUCE_API TimeSliceThread : public Thread
  18144. {
  18145. public:
  18146. /**
  18147. Creates a TimeSliceThread.
  18148. When first created, the thread is not running. Use the startThread()
  18149. method to start it.
  18150. */
  18151. explicit TimeSliceThread (const String& threadName);
  18152. /** Destructor.
  18153. Deleting a Thread object that is running will only give the thread a
  18154. brief opportunity to stop itself cleanly, so it's recommended that you
  18155. should always call stopThread() with a decent timeout before deleting,
  18156. to avoid the thread being forcibly killed (which is a Bad Thing).
  18157. */
  18158. ~TimeSliceThread();
  18159. /** Adds a client to the list.
  18160. The client's callbacks will start after the number of milliseconds specified
  18161. by millisecondsBeforeStarting (and this may happen before this method has returned).
  18162. */
  18163. void addTimeSliceClient (TimeSliceClient* client, int millisecondsBeforeStarting = 0);
  18164. /** Removes a client from the list.
  18165. This method will make sure that all callbacks to the client have completely
  18166. finished before the method returns.
  18167. */
  18168. void removeTimeSliceClient (TimeSliceClient* client);
  18169. /** Returns the number of registered clients. */
  18170. int getNumClients() const;
  18171. /** Returns one of the registered clients. */
  18172. TimeSliceClient* getClient (int index) const;
  18173. #ifndef DOXYGEN
  18174. void run();
  18175. #endif
  18176. private:
  18177. CriticalSection callbackLock, listLock;
  18178. Array <TimeSliceClient*> clients;
  18179. TimeSliceClient* clientBeingCalled;
  18180. TimeSliceClient* getNextClient (int index) const;
  18181. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimeSliceThread);
  18182. };
  18183. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  18184. /*** End of inlined file: juce_TimeSliceThread.h ***/
  18185. #endif
  18186. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  18187. #endif
  18188. #endif
  18189. /*** End of inlined file: juce_core_includes.h ***/
  18190. // if you're compiling a command-line app, you might want to just include the core headers,
  18191. // so you can set this macro before including juce.h
  18192. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  18193. /*** Start of inlined file: juce_app_includes.h ***/
  18194. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  18195. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  18196. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  18197. /*** Start of inlined file: juce_Application.h ***/
  18198. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  18199. #define __JUCE_APPLICATION_JUCEHEADER__
  18200. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  18201. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18202. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18203. /*** Start of inlined file: juce_Component.h ***/
  18204. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  18205. #define __JUCE_COMPONENT_JUCEHEADER__
  18206. /*** Start of inlined file: juce_MouseCursor.h ***/
  18207. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  18208. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  18209. class Image;
  18210. class ComponentPeer;
  18211. class Component;
  18212. /**
  18213. Represents a mouse cursor image.
  18214. This object can either be used to represent one of the standard mouse
  18215. cursor shapes, or a custom one generated from an image.
  18216. */
  18217. class JUCE_API MouseCursor
  18218. {
  18219. public:
  18220. /** The set of available standard mouse cursors. */
  18221. enum StandardCursorType
  18222. {
  18223. NoCursor = 0, /**< An invisible cursor. */
  18224. NormalCursor, /**< The stardard arrow cursor. */
  18225. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  18226. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  18227. CrosshairCursor, /**< A pair of crosshairs. */
  18228. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  18229. that you're dragging a copy of something. */
  18230. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  18231. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  18232. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  18233. UpDownResizeCursor, /**< an arrow pointing up and down. */
  18234. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  18235. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  18236. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  18237. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  18238. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  18239. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  18240. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  18241. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  18242. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  18243. };
  18244. /** Creates the standard arrow cursor. */
  18245. MouseCursor();
  18246. /** Creates one of the standard mouse cursor */
  18247. MouseCursor (StandardCursorType type);
  18248. /** Creates a custom cursor from an image.
  18249. @param image the image to use for the cursor - if this is bigger than the
  18250. system can manage, it might get scaled down first, and might
  18251. also have to be turned to black-and-white if it can't do colour
  18252. cursors.
  18253. @param hotSpotX the x position of the cursor's hotspot within the image
  18254. @param hotSpotY the y position of the cursor's hotspot within the image
  18255. */
  18256. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  18257. /** Creates a copy of another cursor object. */
  18258. MouseCursor (const MouseCursor& other);
  18259. /** Copies this cursor from another object. */
  18260. MouseCursor& operator= (const MouseCursor& other);
  18261. /** Destructor. */
  18262. ~MouseCursor();
  18263. /** Checks whether two mouse cursors are the same.
  18264. For custom cursors, two cursors created from the same image won't be
  18265. recognised as the same, only MouseCursor objects that have been
  18266. copied from the same object.
  18267. */
  18268. bool operator== (const MouseCursor& other) const noexcept;
  18269. /** Checks whether two mouse cursors are the same.
  18270. For custom cursors, two cursors created from the same image won't be
  18271. recognised as the same, only MouseCursor objects that have been
  18272. copied from the same object.
  18273. */
  18274. bool operator!= (const MouseCursor& other) const noexcept;
  18275. /** Makes the system show its default 'busy' cursor.
  18276. This will turn the system cursor to an hourglass or spinning beachball
  18277. until the next time the mouse is moved, or hideWaitCursor() is called.
  18278. This is handy if the message loop is about to block for a couple of
  18279. seconds while busy and you want to give the user feedback about this.
  18280. @see MessageManager::setTimeBeforeShowingWaitCursor
  18281. */
  18282. static void showWaitCursor();
  18283. /** If showWaitCursor has been called, this will return the mouse to its
  18284. normal state.
  18285. This will look at what component is under the mouse, and update the
  18286. cursor to be the correct one for that component.
  18287. @see showWaitCursor
  18288. */
  18289. static void hideWaitCursor();
  18290. private:
  18291. class SharedCursorHandle;
  18292. friend class SharedCursorHandle;
  18293. SharedCursorHandle* cursorHandle;
  18294. friend class MouseInputSourceInternal;
  18295. void showInWindow (ComponentPeer* window) const;
  18296. void showInAllWindows() const;
  18297. void* getHandle() const noexcept;
  18298. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  18299. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  18300. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  18301. JUCE_LEAK_DETECTOR (MouseCursor);
  18302. };
  18303. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  18304. /*** End of inlined file: juce_MouseCursor.h ***/
  18305. /*** Start of inlined file: juce_MouseListener.h ***/
  18306. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  18307. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  18308. class MouseEvent;
  18309. /**
  18310. A MouseListener can be registered with a component to receive callbacks
  18311. about mouse events that happen to that component.
  18312. @see Component::addMouseListener, Component::removeMouseListener
  18313. */
  18314. class JUCE_API MouseListener
  18315. {
  18316. public:
  18317. /** Destructor. */
  18318. virtual ~MouseListener() {}
  18319. /** Called when the mouse moves inside a component.
  18320. If the mouse button isn't pressed and the mouse moves over a component,
  18321. this will be called to let the component react to this.
  18322. A component will always get a mouseEnter callback before a mouseMove.
  18323. @param e details about the position and status of the mouse event, including
  18324. the source component in which it occurred
  18325. @see mouseEnter, mouseExit, mouseDrag, contains
  18326. */
  18327. virtual void mouseMove (const MouseEvent& e);
  18328. /** Called when the mouse first enters a component.
  18329. If the mouse button isn't pressed and the mouse moves into a component,
  18330. this will be called to let the component react to this.
  18331. When the mouse button is pressed and held down while being moved in
  18332. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  18333. mouseDrag messages are sent to the component that the mouse was originally
  18334. clicked on, until the button is released.
  18335. @param e details about the position and status of the mouse event, including
  18336. the source component in which it occurred
  18337. @see mouseExit, mouseDrag, mouseMove, contains
  18338. */
  18339. virtual void mouseEnter (const MouseEvent& e);
  18340. /** Called when the mouse moves out of a component.
  18341. This will be called when the mouse moves off the edge of this
  18342. component.
  18343. If the mouse button was pressed, and it was then dragged off the
  18344. edge of the component and released, then this callback will happen
  18345. when the button is released, after the mouseUp callback.
  18346. @param e details about the position and status of the mouse event, including
  18347. the source component in which it occurred
  18348. @see mouseEnter, mouseDrag, mouseMove, contains
  18349. */
  18350. virtual void mouseExit (const MouseEvent& e);
  18351. /** Called when a mouse button is pressed.
  18352. The MouseEvent object passed in contains lots of methods for finding out
  18353. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  18354. were held down at the time.
  18355. Once a button is held down, the mouseDrag method will be called when the
  18356. mouse moves, until the button is released.
  18357. @param e details about the position and status of the mouse event, including
  18358. the source component in which it occurred
  18359. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  18360. */
  18361. virtual void mouseDown (const MouseEvent& e);
  18362. /** Called when the mouse is moved while a button is held down.
  18363. When a mouse button is pressed inside a component, that component
  18364. receives mouseDrag callbacks each time the mouse moves, even if the
  18365. mouse strays outside the component's bounds.
  18366. @param e details about the position and status of the mouse event, including
  18367. the source component in which it occurred
  18368. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  18369. */
  18370. virtual void mouseDrag (const MouseEvent& e);
  18371. /** Called when a mouse button is released.
  18372. A mouseUp callback is sent to the component in which a button was pressed
  18373. even if the mouse is actually over a different component when the
  18374. button is released.
  18375. The MouseEvent object passed in contains lots of methods for finding out
  18376. which buttons were down just before they were released.
  18377. @param e details about the position and status of the mouse event, including
  18378. the source component in which it occurred
  18379. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  18380. */
  18381. virtual void mouseUp (const MouseEvent& e);
  18382. /** Called when a mouse button has been double-clicked on a component.
  18383. The MouseEvent object passed in contains lots of methods for finding out
  18384. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  18385. were held down at the time.
  18386. @param e details about the position and status of the mouse event, including
  18387. the source component in which it occurred
  18388. @see mouseDown, mouseUp
  18389. */
  18390. virtual void mouseDoubleClick (const MouseEvent& e);
  18391. /** Called when the mouse-wheel is moved.
  18392. This callback is sent to the component that the mouse is over when the
  18393. wheel is moved.
  18394. If not overridden, the component will forward this message to its parent, so
  18395. that parent components can collect mouse-wheel messages that happen to
  18396. child components which aren't interested in them.
  18397. @param e details about the position and status of the mouse event, including
  18398. the source component in which it occurred
  18399. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  18400. value means the wheel has been pushed to the right, negative means it
  18401. was pushed to the left
  18402. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  18403. value means the wheel has been pushed upwards, negative means it
  18404. was pushed downwards
  18405. */
  18406. virtual void mouseWheelMove (const MouseEvent& e,
  18407. float wheelIncrementX,
  18408. float wheelIncrementY);
  18409. };
  18410. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  18411. /*** End of inlined file: juce_MouseListener.h ***/
  18412. /*** Start of inlined file: juce_MouseEvent.h ***/
  18413. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  18414. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  18415. class Component;
  18416. class MouseInputSource;
  18417. /*** Start of inlined file: juce_ModifierKeys.h ***/
  18418. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  18419. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  18420. /**
  18421. Represents the state of the mouse buttons and modifier keys.
  18422. This is used both by mouse events and by KeyPress objects to describe
  18423. the state of keys such as shift, control, alt, etc.
  18424. @see KeyPress, MouseEvent::mods
  18425. */
  18426. class JUCE_API ModifierKeys
  18427. {
  18428. public:
  18429. /** Creates a ModifierKeys object from a raw set of flags.
  18430. @param flags to represent the keys that are down
  18431. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  18432. rightButtonModifier, commandModifier, popupMenuClickModifier
  18433. */
  18434. ModifierKeys (int flags = 0) noexcept;
  18435. /** Creates a copy of another object. */
  18436. ModifierKeys (const ModifierKeys& other) noexcept;
  18437. /** Copies this object from another one. */
  18438. ModifierKeys& operator= (const ModifierKeys& other) noexcept;
  18439. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  18440. This is a platform-agnostic way of checking for the operating system's
  18441. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  18442. Windows/Linux, it's actually checking for the CTRL key.
  18443. */
  18444. inline bool isCommandDown() const noexcept { return (flags & commandModifier) != 0; }
  18445. /** Checks whether the user is trying to launch a pop-up menu.
  18446. This checks for platform-specific modifiers that might indicate that the user
  18447. is following the operating system's normal method of showing a pop-up menu.
  18448. So on Windows/Linux, this method is really testing for a right-click.
  18449. On the Mac, it tests for either the CTRL key being down, or a right-click.
  18450. */
  18451. inline bool isPopupMenu() const noexcept { return (flags & popupMenuClickModifier) != 0; }
  18452. /** Checks whether the flag is set for the left mouse-button. */
  18453. inline bool isLeftButtonDown() const noexcept { return (flags & leftButtonModifier) != 0; }
  18454. /** Checks whether the flag is set for the right mouse-button.
  18455. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  18456. this is platform-independent (and makes your code more explanatory too).
  18457. */
  18458. inline bool isRightButtonDown() const noexcept { return (flags & rightButtonModifier) != 0; }
  18459. inline bool isMiddleButtonDown() const noexcept { return (flags & middleButtonModifier) != 0; }
  18460. /** Tests for any of the mouse-button flags. */
  18461. inline bool isAnyMouseButtonDown() const noexcept { return (flags & allMouseButtonModifiers) != 0; }
  18462. /** Tests for any of the modifier key flags. */
  18463. inline bool isAnyModifierKeyDown() const noexcept { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  18464. /** Checks whether the shift key's flag is set. */
  18465. inline bool isShiftDown() const noexcept { return (flags & shiftModifier) != 0; }
  18466. /** Checks whether the CTRL key's flag is set.
  18467. Remember that it's better to use the platform-agnostic routines to test for command-key and
  18468. popup-menu modifiers.
  18469. @see isCommandDown, isPopupMenu
  18470. */
  18471. inline bool isCtrlDown() const noexcept { return (flags & ctrlModifier) != 0; }
  18472. /** Checks whether the shift key's flag is set. */
  18473. inline bool isAltDown() const noexcept { return (flags & altModifier) != 0; }
  18474. /** Flags that represent the different keys. */
  18475. enum Flags
  18476. {
  18477. /** Shift key flag. */
  18478. shiftModifier = 1,
  18479. /** CTRL key flag. */
  18480. ctrlModifier = 2,
  18481. /** ALT key flag. */
  18482. altModifier = 4,
  18483. /** Left mouse button flag. */
  18484. leftButtonModifier = 16,
  18485. /** Right mouse button flag. */
  18486. rightButtonModifier = 32,
  18487. /** Middle mouse button flag. */
  18488. middleButtonModifier = 64,
  18489. #if JUCE_MAC
  18490. /** Command key flag - on windows this is the same as the CTRL key flag. */
  18491. commandModifier = 8,
  18492. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  18493. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  18494. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  18495. #else
  18496. /** Command key flag - on windows this is the same as the CTRL key flag. */
  18497. commandModifier = ctrlModifier,
  18498. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  18499. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  18500. popupMenuClickModifier = rightButtonModifier,
  18501. #endif
  18502. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  18503. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  18504. /** Represents a combination of all the mouse buttons at once. */
  18505. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  18506. };
  18507. /** Returns a copy of only the mouse-button flags */
  18508. const ModifierKeys withOnlyMouseButtons() const noexcept { return ModifierKeys (flags & allMouseButtonModifiers); }
  18509. /** Returns a copy of only the non-mouse flags */
  18510. const ModifierKeys withoutMouseButtons() const noexcept { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  18511. bool operator== (const ModifierKeys& other) const noexcept { return flags == other.flags; }
  18512. bool operator!= (const ModifierKeys& other) const noexcept { return flags != other.flags; }
  18513. /** Returns the raw flags for direct testing. */
  18514. inline int getRawFlags() const noexcept { return flags; }
  18515. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const noexcept { return ModifierKeys (flags & ~rawFlagsToClear); }
  18516. inline const ModifierKeys withFlags (int rawFlagsToSet) const noexcept { return ModifierKeys (flags | rawFlagsToSet); }
  18517. /** Tests a combination of flags and returns true if any of them are set. */
  18518. inline bool testFlags (const int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  18519. /** Returns the total number of mouse buttons that are down. */
  18520. int getNumMouseButtonsDown() const noexcept;
  18521. /** Creates a ModifierKeys object to represent the last-known state of the
  18522. keyboard and mouse buttons.
  18523. @see getCurrentModifiersRealtime
  18524. */
  18525. static const ModifierKeys getCurrentModifiers() noexcept;
  18526. /** Creates a ModifierKeys object to represent the current state of the
  18527. keyboard and mouse buttons.
  18528. This isn't often needed and isn't recommended, but will actively check all the
  18529. mouse and key states rather than just returning their last-known state like
  18530. getCurrentModifiers() does.
  18531. This is only needed in special circumstances for up-to-date modifier information
  18532. at times when the app's event loop isn't running normally.
  18533. Another reason to avoid this method is that it's not stateless, and calling it may
  18534. update the value returned by getCurrentModifiers(), which could cause subtle changes
  18535. in the behaviour of some components.
  18536. */
  18537. static const ModifierKeys getCurrentModifiersRealtime() noexcept;
  18538. private:
  18539. int flags;
  18540. static ModifierKeys currentModifiers;
  18541. friend class ComponentPeer;
  18542. friend class MouseInputSource;
  18543. friend class MouseInputSourceInternal;
  18544. static void updateCurrentModifiers() noexcept;
  18545. };
  18546. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  18547. /*** End of inlined file: juce_ModifierKeys.h ***/
  18548. /*** Start of inlined file: juce_Point.h ***/
  18549. #ifndef __JUCE_POINT_JUCEHEADER__
  18550. #define __JUCE_POINT_JUCEHEADER__
  18551. /*** Start of inlined file: juce_AffineTransform.h ***/
  18552. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18553. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18554. /**
  18555. Represents a 2D affine-transformation matrix.
  18556. An affine transformation is a transformation such as a rotation, scale, shear,
  18557. resize or translation.
  18558. These are used for various 2D transformation tasks, e.g. with Path objects.
  18559. @see Path, Point, Line
  18560. */
  18561. class JUCE_API AffineTransform
  18562. {
  18563. public:
  18564. /** Creates an identity transform. */
  18565. AffineTransform() noexcept;
  18566. /** Creates a copy of another transform. */
  18567. AffineTransform (const AffineTransform& other) noexcept;
  18568. /** Creates a transform from a set of raw matrix values.
  18569. The resulting matrix is:
  18570. (mat00 mat01 mat02)
  18571. (mat10 mat11 mat12)
  18572. ( 0 0 1 )
  18573. */
  18574. AffineTransform (float mat00, float mat01, float mat02,
  18575. float mat10, float mat11, float mat12) noexcept;
  18576. /** Copies from another AffineTransform object */
  18577. AffineTransform& operator= (const AffineTransform& other) noexcept;
  18578. /** Compares two transforms. */
  18579. bool operator== (const AffineTransform& other) const noexcept;
  18580. /** Compares two transforms. */
  18581. bool operator!= (const AffineTransform& other) const noexcept;
  18582. /** A ready-to-use identity transform, which you can use to append other
  18583. transformations to.
  18584. e.g. @code
  18585. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  18586. .scaled (2.0f);
  18587. @endcode
  18588. */
  18589. static const AffineTransform identity;
  18590. /** Transforms a 2D co-ordinate using this matrix. */
  18591. template <typename ValueType>
  18592. void transformPoint (ValueType& x, ValueType& y) const noexcept
  18593. {
  18594. const ValueType oldX = x;
  18595. x = static_cast <ValueType> (mat00 * oldX + mat01 * y + mat02);
  18596. y = static_cast <ValueType> (mat10 * oldX + mat11 * y + mat12);
  18597. }
  18598. /** Transforms two 2D co-ordinates using this matrix.
  18599. This is just a shortcut for calling transformPoint() on each of these pairs of
  18600. coordinates in turn. (And putting all the calculations into one function hopefully
  18601. also gives the compiler a bit more scope for pipelining it).
  18602. */
  18603. template <typename ValueType>
  18604. void transformPoints (ValueType& x1, ValueType& y1,
  18605. ValueType& x2, ValueType& y2) const noexcept
  18606. {
  18607. const ValueType oldX1 = x1, oldX2 = x2;
  18608. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  18609. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  18610. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  18611. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  18612. }
  18613. /** Transforms three 2D co-ordinates using this matrix.
  18614. This is just a shortcut for calling transformPoint() on each of these pairs of
  18615. coordinates in turn. (And putting all the calculations into one function hopefully
  18616. also gives the compiler a bit more scope for pipelining it).
  18617. */
  18618. template <typename ValueType>
  18619. void transformPoints (ValueType& x1, ValueType& y1,
  18620. ValueType& x2, ValueType& y2,
  18621. ValueType& x3, ValueType& y3) const noexcept
  18622. {
  18623. const ValueType oldX1 = x1, oldX2 = x2, oldX3 = x3;
  18624. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  18625. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  18626. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  18627. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  18628. x3 = static_cast <ValueType> (mat00 * oldX3 + mat01 * y3 + mat02);
  18629. y3 = static_cast <ValueType> (mat10 * oldX3 + mat11 * y3 + mat12);
  18630. }
  18631. /** Returns a new transform which is the same as this one followed by a translation. */
  18632. AffineTransform translated (float deltaX,
  18633. float deltaY) const noexcept;
  18634. /** Returns a new transform which is a translation. */
  18635. static AffineTransform translation (float deltaX,
  18636. float deltaY) noexcept;
  18637. /** Returns a transform which is the same as this one followed by a rotation.
  18638. The rotation is specified by a number of radians to rotate clockwise, centred around
  18639. the origin (0, 0).
  18640. */
  18641. AffineTransform rotated (float angleInRadians) const noexcept;
  18642. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  18643. The rotation is specified by a number of radians to rotate clockwise, centred around
  18644. the co-ordinates passed in.
  18645. */
  18646. AffineTransform rotated (float angleInRadians,
  18647. float pivotX,
  18648. float pivotY) const noexcept;
  18649. /** Returns a new transform which is a rotation about (0, 0). */
  18650. static AffineTransform rotation (float angleInRadians) noexcept;
  18651. /** Returns a new transform which is a rotation about a given point. */
  18652. static AffineTransform rotation (float angleInRadians,
  18653. float pivotX,
  18654. float pivotY) noexcept;
  18655. /** Returns a transform which is the same as this one followed by a re-scaling.
  18656. The scaling is centred around the origin (0, 0).
  18657. */
  18658. AffineTransform scaled (float factorX,
  18659. float factorY) const noexcept;
  18660. /** Returns a transform which is the same as this one followed by a re-scaling.
  18661. The scaling is centred around the origin provided.
  18662. */
  18663. AffineTransform scaled (float factorX, float factorY,
  18664. float pivotX, float pivotY) const noexcept;
  18665. /** Returns a new transform which is a re-scale about the origin. */
  18666. static AffineTransform scale (float factorX,
  18667. float factorY) noexcept;
  18668. /** Returns a new transform which is a re-scale centred around the point provided. */
  18669. static AffineTransform scale (float factorX, float factorY,
  18670. float pivotX, float pivotY) noexcept;
  18671. /** Returns a transform which is the same as this one followed by a shear.
  18672. The shear is centred around the origin (0, 0).
  18673. */
  18674. AffineTransform sheared (float shearX, float shearY) const noexcept;
  18675. /** Returns a shear transform, centred around the origin (0, 0). */
  18676. static AffineTransform shear (float shearX, float shearY) noexcept;
  18677. /** Returns a matrix which is the inverse operation of this one.
  18678. Some matrices don't have an inverse - in this case, the method will just return
  18679. an identity transform.
  18680. */
  18681. AffineTransform inverted() const noexcept;
  18682. /** Returns the transform that will map three known points onto three coordinates
  18683. that are supplied.
  18684. This returns the transform that will transform (0, 0) into (x00, y00),
  18685. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  18686. */
  18687. static AffineTransform fromTargetPoints (float x00, float y00,
  18688. float x10, float y10,
  18689. float x01, float y01) noexcept;
  18690. /** Returns the transform that will map three specified points onto three target points.
  18691. */
  18692. static AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  18693. float sourceX2, float sourceY2, float targetX2, float targetY2,
  18694. float sourceX3, float sourceY3, float targetX3, float targetY3) noexcept;
  18695. /** Returns the result of concatenating another transformation after this one. */
  18696. AffineTransform followedBy (const AffineTransform& other) const noexcept;
  18697. /** Returns true if this transform has no effect on points. */
  18698. bool isIdentity() const noexcept;
  18699. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  18700. bool isSingularity() const noexcept;
  18701. /** Returns true if the transform only translates, and doesn't scale or rotate the
  18702. points. */
  18703. bool isOnlyTranslation() const noexcept;
  18704. /** If this transform is only a translation, this returns the X offset.
  18705. @see isOnlyTranslation
  18706. */
  18707. float getTranslationX() const noexcept { return mat02; }
  18708. /** If this transform is only a translation, this returns the X offset.
  18709. @see isOnlyTranslation
  18710. */
  18711. float getTranslationY() const noexcept { return mat12; }
  18712. /** Returns the approximate scale factor by which lengths will be transformed.
  18713. Obviously a length may be scaled by entirely different amounts depending on its
  18714. direction, so this is only appropriate as a rough guide.
  18715. */
  18716. float getScaleFactor() const noexcept;
  18717. /* The transform matrix is:
  18718. (mat00 mat01 mat02)
  18719. (mat10 mat11 mat12)
  18720. ( 0 0 1 )
  18721. */
  18722. float mat00, mat01, mat02;
  18723. float mat10, mat11, mat12;
  18724. private:
  18725. JUCE_LEAK_DETECTOR (AffineTransform);
  18726. };
  18727. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18728. /*** End of inlined file: juce_AffineTransform.h ***/
  18729. /**
  18730. A pair of (x, y) co-ordinates.
  18731. The ValueType template should be a primitive type such as int, float, double,
  18732. rather than a class.
  18733. @see Line, Path, AffineTransform
  18734. */
  18735. template <typename ValueType>
  18736. class Point
  18737. {
  18738. public:
  18739. /** Creates a point with co-ordinates (0, 0). */
  18740. Point() noexcept : x(), y() {}
  18741. /** Creates a copy of another point. */
  18742. Point (const Point& other) noexcept : x (other.x), y (other.y) {}
  18743. /** Creates a point from an (x, y) position. */
  18744. Point (const ValueType initialX, const ValueType initialY) noexcept : x (initialX), y (initialY) {}
  18745. /** Destructor. */
  18746. ~Point() noexcept {}
  18747. /** Copies this point from another one. */
  18748. Point& operator= (const Point& other) noexcept { x = other.x; y = other.y; return *this; }
  18749. inline bool operator== (const Point& other) const noexcept { return x == other.x && y == other.y; }
  18750. inline bool operator!= (const Point& other) const noexcept { return x != other.x || y != other.y; }
  18751. /** Returns true if the point is (0, 0). */
  18752. bool isOrigin() const noexcept { return x == ValueType() && y == ValueType(); }
  18753. /** Returns the point's x co-ordinate. */
  18754. inline ValueType getX() const noexcept { return x; }
  18755. /** Returns the point's y co-ordinate. */
  18756. inline ValueType getY() const noexcept { return y; }
  18757. /** Sets the point's x co-ordinate. */
  18758. inline void setX (const ValueType newX) noexcept { x = newX; }
  18759. /** Sets the point's y co-ordinate. */
  18760. inline void setY (const ValueType newY) noexcept { y = newY; }
  18761. /** Returns a point which has the same Y position as this one, but a new X. */
  18762. Point withX (const ValueType newX) const noexcept { return Point (newX, y); }
  18763. /** Returns a point which has the same X position as this one, but a new Y. */
  18764. Point withY (const ValueType newY) const noexcept { return Point (x, newY); }
  18765. /** Changes the point's x and y co-ordinates. */
  18766. void setXY (const ValueType newX, const ValueType newY) noexcept { x = newX; y = newY; }
  18767. /** Adds a pair of co-ordinates to this value. */
  18768. void addXY (const ValueType xToAdd, const ValueType yToAdd) noexcept { x += xToAdd; y += yToAdd; }
  18769. /** Returns a point with a given offset from this one. */
  18770. Point translated (const ValueType xDelta, const ValueType yDelta) const noexcept { return Point (x + xDelta, y + yDelta); }
  18771. /** Adds two points together. */
  18772. Point operator+ (const Point& other) const noexcept { return Point (x + other.x, y + other.y); }
  18773. /** Adds another point's co-ordinates to this one. */
  18774. Point& operator+= (const Point& other) noexcept { x += other.x; y += other.y; return *this; }
  18775. /** Subtracts one points from another. */
  18776. Point operator- (const Point& other) const noexcept { return Point (x - other.x, y - other.y); }
  18777. /** Subtracts another point's co-ordinates to this one. */
  18778. Point& operator-= (const Point& other) noexcept { x -= other.x; y -= other.y; return *this; }
  18779. /** Returns a point whose coordinates are multiplied by a given value. */
  18780. Point operator* (const ValueType multiplier) const noexcept { return Point (x * multiplier, y * multiplier); }
  18781. /** Multiplies the point's co-ordinates by a value. */
  18782. Point& operator*= (const ValueType multiplier) noexcept { x *= multiplier; y *= multiplier; return *this; }
  18783. /** Returns a point whose coordinates are divided by a given value. */
  18784. Point operator/ (const ValueType divisor) const noexcept { return Point (x / divisor, y / divisor); }
  18785. /** Divides the point's co-ordinates by a value. */
  18786. Point& operator/= (const ValueType divisor) noexcept { x /= divisor; y /= divisor; return *this; }
  18787. /** Returns the inverse of this point. */
  18788. Point operator-() const noexcept { return Point (-x, -y); }
  18789. /** Returns the straight-line distance between this point and another one. */
  18790. ValueType getDistanceFromOrigin() const noexcept { return juce_hypot (x, y); }
  18791. /** Returns the straight-line distance between this point and another one. */
  18792. ValueType getDistanceFrom (const Point& other) const noexcept { return juce_hypot (x - other.x, y - other.y); }
  18793. /** Returns the angle from this point to another one.
  18794. The return value is the number of radians clockwise from the 3 o'clock direction,
  18795. where this point is the centre and the other point is on the circumference.
  18796. */
  18797. ValueType getAngleToPoint (const Point& other) const noexcept { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  18798. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  18799. @param radius the radius of the circle.
  18800. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  18801. */
  18802. Point getPointOnCircumference (const float radius, const float angle) const noexcept { return Point<float> (x + radius * std::sin (angle),
  18803. y - radius * std::cos (angle)); }
  18804. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  18805. @param radiusX the horizontal radius of the circle.
  18806. @param radiusY the vertical radius of the circle.
  18807. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  18808. */
  18809. Point getPointOnCircumference (const float radiusX, const float radiusY, const float angle) const noexcept { return Point<float> (x + radiusX * std::sin (angle),
  18810. y - radiusY * std::cos (angle)); }
  18811. /** Uses a transform to change the point's co-ordinates.
  18812. This will only compile if ValueType = float!
  18813. @see AffineTransform::transformPoint
  18814. */
  18815. void applyTransform (const AffineTransform& transform) noexcept { transform.transformPoint (x, y); }
  18816. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  18817. Point transformedBy (const AffineTransform& transform) const noexcept { return Point (transform.mat00 * x + transform.mat01 * y + transform.mat02,
  18818. transform.mat10 * x + transform.mat11 * y + transform.mat12); }
  18819. /** Casts this point to a Point<int> object. */
  18820. Point<int> toInt() const noexcept { return Point<int> (static_cast <int> (x), static_cast<int> (y)); }
  18821. /** Casts this point to a Point<float> object. */
  18822. Point<float> toFloat() const noexcept { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  18823. /** Casts this point to a Point<double> object. */
  18824. Point<double> toDouble() const noexcept { return Point<double> (static_cast <double> (x), static_cast<double> (y)); }
  18825. /** Returns the point as a string in the form "x, y". */
  18826. String toString() const { return String (x) + ", " + String (y); }
  18827. private:
  18828. ValueType x, y;
  18829. };
  18830. #endif // __JUCE_POINT_JUCEHEADER__
  18831. /*** End of inlined file: juce_Point.h ***/
  18832. /**
  18833. Contains position and status information about a mouse event.
  18834. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  18835. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  18836. */
  18837. class JUCE_API MouseEvent
  18838. {
  18839. public:
  18840. /** Creates a MouseEvent.
  18841. Normally an application will never need to use this.
  18842. @param source the source that's invoking the event
  18843. @param position the position of the mouse, relative to the component that is passed-in
  18844. @param modifiers the key modifiers at the time of the event
  18845. @param eventComponent the component that the mouse event applies to
  18846. @param originator the component that originally received the event
  18847. @param eventTime the time the event happened
  18848. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  18849. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  18850. the same as the current mouse-x position.
  18851. @param mouseDownTime the time at which the corresponding mouse-down event happened
  18852. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  18853. the same as the current mouse-event time.
  18854. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  18855. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  18856. */
  18857. MouseEvent (MouseInputSource& source,
  18858. const Point<int>& position,
  18859. const ModifierKeys& modifiers,
  18860. Component* eventComponent,
  18861. Component* originator,
  18862. const Time& eventTime,
  18863. const Point<int> mouseDownPos,
  18864. const Time& mouseDownTime,
  18865. int numberOfClicks,
  18866. bool mouseWasDragged) noexcept;
  18867. /** Destructor. */
  18868. ~MouseEvent() noexcept;
  18869. /** The x-position of the mouse when the event occurred.
  18870. This value is relative to the top-left of the component to which the
  18871. event applies (as indicated by the MouseEvent::eventComponent field).
  18872. */
  18873. const int x;
  18874. /** The y-position of the mouse when the event occurred.
  18875. This value is relative to the top-left of the component to which the
  18876. event applies (as indicated by the MouseEvent::eventComponent field).
  18877. */
  18878. const int y;
  18879. /** The key modifiers associated with the event.
  18880. This will let you find out which mouse buttons were down, as well as which
  18881. modifier keys were held down.
  18882. When used for mouse-up events, this will indicate the state of the mouse buttons
  18883. just before they were released, so that you can tell which button they let go of.
  18884. */
  18885. const ModifierKeys mods;
  18886. /** The component that this event applies to.
  18887. This is usually the component that the mouse was over at the time, but for mouse-drag
  18888. events the mouse could actually be over a different component and the events are
  18889. still sent to the component that the button was originally pressed on.
  18890. The x and y member variables are relative to this component's position.
  18891. If you use getEventRelativeTo() to retarget this object to be relative to a different
  18892. component, this pointer will be updated, but originalComponent remains unchanged.
  18893. @see originalComponent
  18894. */
  18895. Component* const eventComponent;
  18896. /** The component that the event first occurred on.
  18897. If you use getEventRelativeTo() to retarget this object to be relative to a different
  18898. component, this value remains unchanged to indicate the first component that received it.
  18899. @see eventComponent
  18900. */
  18901. Component* const originalComponent;
  18902. /** The time that this mouse-event occurred.
  18903. */
  18904. const Time eventTime;
  18905. /** The source device that generated this event.
  18906. */
  18907. MouseInputSource& source;
  18908. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  18909. The co-ordinate is relative to the component specified in MouseEvent::component.
  18910. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18911. */
  18912. int getMouseDownX() const noexcept;
  18913. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  18914. The co-ordinate is relative to the component specified in MouseEvent::component.
  18915. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18916. */
  18917. int getMouseDownY() const noexcept;
  18918. /** Returns the co-ordinates of the last place that a mouse was pressed.
  18919. The co-ordinates are relative to the component specified in MouseEvent::component.
  18920. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18921. */
  18922. const Point<int> getMouseDownPosition() const noexcept;
  18923. /** Returns the straight-line distance between where the mouse is now and where it
  18924. was the last time the button was pressed.
  18925. This is quite handy for things like deciding whether the user has moved far enough
  18926. for it to be considered a drag operation.
  18927. @see getDistanceFromDragStartX
  18928. */
  18929. int getDistanceFromDragStart() const noexcept;
  18930. /** Returns the difference between the mouse's current x postion and where it was
  18931. when the button was last pressed.
  18932. @see getDistanceFromDragStart
  18933. */
  18934. int getDistanceFromDragStartX() const noexcept;
  18935. /** Returns the difference between the mouse's current y postion and where it was
  18936. when the button was last pressed.
  18937. @see getDistanceFromDragStart
  18938. */
  18939. int getDistanceFromDragStartY() const noexcept;
  18940. /** Returns the difference between the mouse's current postion and where it was
  18941. when the button was last pressed.
  18942. @see getDistanceFromDragStart
  18943. */
  18944. const Point<int> getOffsetFromDragStart() const noexcept;
  18945. /** Returns true if the mouse has just been clicked.
  18946. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  18947. the user has dragged the mouse more than a few pixels from the place where the
  18948. mouse-down occurred.
  18949. Once they have dragged it far enough for this method to return false, it will continue
  18950. to return false until the mouse-up, even if they move the mouse back to the same
  18951. position where they originally pressed it. This means that it's very handy for
  18952. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  18953. callback to ignore any small movements they might make while clicking.
  18954. @returns true if the mouse wasn't dragged by more than a few pixels between
  18955. the last time the button was pressed and released.
  18956. */
  18957. bool mouseWasClicked() const noexcept;
  18958. /** For a click event, the number of times the mouse was clicked in succession.
  18959. So for example a double-click event will return 2, a triple-click 3, etc.
  18960. */
  18961. int getNumberOfClicks() const noexcept { return numberOfClicks; }
  18962. /** Returns the time that the mouse button has been held down for.
  18963. If called from a mouseDrag or mouseUp callback, this will return the
  18964. number of milliseconds since the corresponding mouseDown event occurred.
  18965. If called in other contexts, e.g. a mouseMove, then the returned value
  18966. may be 0 or an undefined value.
  18967. */
  18968. int getLengthOfMousePress() const noexcept;
  18969. /** The position of the mouse when the event occurred.
  18970. This position is relative to the top-left of the component to which the
  18971. event applies (as indicated by the MouseEvent::eventComponent field).
  18972. */
  18973. const Point<int> getPosition() const noexcept;
  18974. /** Returns the mouse x position of this event, in global screen co-ordinates.
  18975. The co-ordinates are relative to the top-left of the main monitor.
  18976. @see getScreenPosition
  18977. */
  18978. int getScreenX() const;
  18979. /** Returns the mouse y position of this event, in global screen co-ordinates.
  18980. The co-ordinates are relative to the top-left of the main monitor.
  18981. @see getScreenPosition
  18982. */
  18983. int getScreenY() const;
  18984. /** Returns the mouse position of this event, in global screen co-ordinates.
  18985. The co-ordinates are relative to the top-left of the main monitor.
  18986. @see getMouseDownScreenPosition
  18987. */
  18988. const Point<int> getScreenPosition() const;
  18989. /** Returns the x co-ordinate at which the mouse button was last pressed.
  18990. The co-ordinates are relative to the top-left of the main monitor.
  18991. @see getMouseDownScreenPosition
  18992. */
  18993. int getMouseDownScreenX() const;
  18994. /** Returns the y co-ordinate at which the mouse button was last pressed.
  18995. The co-ordinates are relative to the top-left of the main monitor.
  18996. @see getMouseDownScreenPosition
  18997. */
  18998. int getMouseDownScreenY() const;
  18999. /** Returns the co-ordinates at which the mouse button was last pressed.
  19000. The co-ordinates are relative to the top-left of the main monitor.
  19001. @see getScreenPosition
  19002. */
  19003. const Point<int> getMouseDownScreenPosition() const;
  19004. /** Creates a version of this event that is relative to a different component.
  19005. The x and y positions of the event that is returned will have been
  19006. adjusted to be relative to the new component.
  19007. */
  19008. MouseEvent getEventRelativeTo (Component* otherComponent) const noexcept;
  19009. /** Creates a copy of this event with a different position.
  19010. All other members of the event object are the same, but the x and y are
  19011. replaced with these new values.
  19012. */
  19013. MouseEvent withNewPosition (const Point<int>& newPosition) const noexcept;
  19014. /** Changes the application-wide setting for the double-click time limit.
  19015. This is the maximum length of time between mouse-clicks for it to be
  19016. considered a double-click. It's used by the Component class.
  19017. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  19018. */
  19019. static void setDoubleClickTimeout (int timeOutMilliseconds) noexcept;
  19020. /** Returns the application-wide setting for the double-click time limit.
  19021. This is the maximum length of time between mouse-clicks for it to be
  19022. considered a double-click. It's used by the Component class.
  19023. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  19024. */
  19025. static int getDoubleClickTimeout() noexcept;
  19026. private:
  19027. const Point<int> mouseDownPos;
  19028. const Time mouseDownTime;
  19029. const int numberOfClicks;
  19030. const bool wasMovedSinceMouseDown;
  19031. static int doubleClickTimeOutMs;
  19032. MouseEvent& operator= (const MouseEvent&);
  19033. };
  19034. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  19035. /*** End of inlined file: juce_MouseEvent.h ***/
  19036. /*** Start of inlined file: juce_ComponentListener.h ***/
  19037. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  19038. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  19039. class Component;
  19040. /**
  19041. Gets informed about changes to a component's hierarchy or position.
  19042. To monitor a component for changes, register a subclass of ComponentListener
  19043. with the component using Component::addComponentListener().
  19044. Be sure to deregister listeners before you delete them!
  19045. @see Component::addComponentListener, Component::removeComponentListener
  19046. */
  19047. class JUCE_API ComponentListener
  19048. {
  19049. public:
  19050. /** Destructor. */
  19051. virtual ~ComponentListener() {}
  19052. /** Called when the component's position or size changes.
  19053. @param component the component that was moved or resized
  19054. @param wasMoved true if the component's top-left corner has just moved
  19055. @param wasResized true if the component's width or height has just changed
  19056. @see Component::setBounds, Component::resized, Component::moved
  19057. */
  19058. virtual void componentMovedOrResized (Component& component,
  19059. bool wasMoved,
  19060. bool wasResized);
  19061. /** Called when the component is brought to the top of the z-order.
  19062. @param component the component that was moved
  19063. @see Component::toFront, Component::broughtToFront
  19064. */
  19065. virtual void componentBroughtToFront (Component& component);
  19066. /** Called when the component is made visible or invisible.
  19067. @param component the component that changed
  19068. @see Component::setVisible
  19069. */
  19070. virtual void componentVisibilityChanged (Component& component);
  19071. /** Called when the component has children added or removed.
  19072. @param component the component whose children were changed
  19073. @see Component::childrenChanged, Component::addChildComponent,
  19074. Component::removeChildComponent
  19075. */
  19076. virtual void componentChildrenChanged (Component& component);
  19077. /** Called to indicate that the component's parents have changed.
  19078. When a component is added or removed from its parent, all of its children
  19079. will produce this notification (recursively - so all children of its
  19080. children will also be called as well).
  19081. @param component the component that this listener is registered with
  19082. @see Component::parentHierarchyChanged
  19083. */
  19084. virtual void componentParentHierarchyChanged (Component& component);
  19085. /** Called when the component's name is changed.
  19086. @see Component::setName, Component::getName
  19087. */
  19088. virtual void componentNameChanged (Component& component);
  19089. /** Called when the component is in the process of being deleted.
  19090. This callback is made from inside the destructor, so be very, very cautious
  19091. about what you do in here.
  19092. In particular, bear in mind that it's the Component base class's destructor that calls
  19093. this - so if the object that's being deleted is a subclass of Component, then the
  19094. subclass layers of the object will already have been destructed when it gets to this
  19095. point!
  19096. */
  19097. virtual void componentBeingDeleted (Component& component);
  19098. };
  19099. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  19100. /*** End of inlined file: juce_ComponentListener.h ***/
  19101. /*** Start of inlined file: juce_KeyListener.h ***/
  19102. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  19103. #define __JUCE_KEYLISTENER_JUCEHEADER__
  19104. /*** Start of inlined file: juce_KeyPress.h ***/
  19105. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  19106. #define __JUCE_KEYPRESS_JUCEHEADER__
  19107. /**
  19108. Represents a key press, including any modifier keys that are needed.
  19109. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  19110. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  19111. */
  19112. class JUCE_API KeyPress
  19113. {
  19114. public:
  19115. /** Creates an (invalid) KeyPress.
  19116. @see isValid
  19117. */
  19118. KeyPress() noexcept;
  19119. /** Creates a KeyPress for a key and some modifiers.
  19120. e.g.
  19121. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  19122. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  19123. @param keyCode a code that represents the key - this value must be
  19124. one of special constants listed in this class, or an
  19125. 8-bit character code such as a letter (case is ignored),
  19126. digit or a simple key like "," or ".". Note that this
  19127. isn't the same as the textCharacter parameter, so for example
  19128. a keyCode of 'a' and a shift-key modifier should have a
  19129. textCharacter value of 'A'.
  19130. @param modifiers the modifiers to associate with the keystroke
  19131. @param textCharacter the character that would be printed if someone typed
  19132. this keypress into a text editor. This value may be
  19133. null if the keypress is a non-printing character
  19134. @see getKeyCode, isKeyCode, getModifiers
  19135. */
  19136. KeyPress (int keyCode,
  19137. const ModifierKeys& modifiers,
  19138. juce_wchar textCharacter) noexcept;
  19139. /** Creates a keypress with a keyCode but no modifiers or text character.
  19140. */
  19141. KeyPress (int keyCode) noexcept;
  19142. /** Creates a copy of another KeyPress. */
  19143. KeyPress (const KeyPress& other) noexcept;
  19144. /** Copies this KeyPress from another one. */
  19145. KeyPress& operator= (const KeyPress& other) noexcept;
  19146. /** Compares two KeyPress objects. */
  19147. bool operator== (const KeyPress& other) const noexcept;
  19148. /** Compares two KeyPress objects. */
  19149. bool operator!= (const KeyPress& other) const noexcept;
  19150. /** Returns true if this is a valid KeyPress.
  19151. A null keypress can be created by the default constructor, in case it's
  19152. needed.
  19153. */
  19154. bool isValid() const noexcept { return keyCode != 0; }
  19155. /** Returns the key code itself.
  19156. This will either be one of the special constants defined in this class,
  19157. or an 8-bit character code.
  19158. */
  19159. int getKeyCode() const noexcept { return keyCode; }
  19160. /** Returns the key modifiers.
  19161. @see ModifierKeys
  19162. */
  19163. const ModifierKeys getModifiers() const noexcept { return mods; }
  19164. /** Returns the character that is associated with this keypress.
  19165. This is the character that you'd expect to see printed if you press this
  19166. keypress in a text editor or similar component.
  19167. */
  19168. juce_wchar getTextCharacter() const noexcept { return textCharacter; }
  19169. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  19170. the modifiers.
  19171. The values for key codes can either be one of the special constants defined in
  19172. this class, or an 8-bit character code.
  19173. @see getKeyCode
  19174. */
  19175. bool isKeyCode (int keyCodeToCompare) const noexcept { return keyCode == keyCodeToCompare; }
  19176. /** Converts a textual key description to a KeyPress.
  19177. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  19178. This isn't designed to cope with any kind of input, but should be given the
  19179. strings that are created by the getTextDescription() method.
  19180. If the string can't be parsed, the object returned will be invalid.
  19181. @see getTextDescription
  19182. */
  19183. static const KeyPress createFromDescription (const String& textVersion);
  19184. /** Creates a textual description of the key combination.
  19185. e.g. "CTRL + C" or "DELETE".
  19186. To store a keypress in a file, use this method, along with createFromDescription()
  19187. to retrieve it later.
  19188. */
  19189. String getTextDescription() const;
  19190. /** Creates a textual description of the key combination, using unicode icon symbols if possible.
  19191. On OSX, this uses the Apple symbols for command, option, shift, etc, instead of the textual
  19192. modifier key descriptions that are returned by getTextDescription()
  19193. */
  19194. String getTextDescriptionWithIcons() const;
  19195. /** Checks whether the user is currently holding down the keys that make up this
  19196. KeyPress.
  19197. Note that this will return false if any extra modifier keys are
  19198. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  19199. then it will be false.
  19200. */
  19201. bool isCurrentlyDown() const;
  19202. /** Checks whether a particular key is held down, irrespective of modifiers.
  19203. The values for key codes can either be one of the special constants defined in
  19204. this class, or an 8-bit character code.
  19205. */
  19206. static bool isKeyCurrentlyDown (int keyCode);
  19207. // Key codes
  19208. //
  19209. // Note that the actual values of these are platform-specific and may change
  19210. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  19211. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  19212. //
  19213. static const int spaceKey; /**< key-code for the space bar */
  19214. static const int escapeKey; /**< key-code for the escape key */
  19215. static const int returnKey; /**< key-code for the return key*/
  19216. static const int tabKey; /**< key-code for the tab key*/
  19217. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  19218. static const int backspaceKey; /**< key-code for the backspace key */
  19219. static const int insertKey; /**< key-code for the insert key */
  19220. static const int upKey; /**< key-code for the cursor-up key */
  19221. static const int downKey; /**< key-code for the cursor-down key */
  19222. static const int leftKey; /**< key-code for the cursor-left key */
  19223. static const int rightKey; /**< key-code for the cursor-right key */
  19224. static const int pageUpKey; /**< key-code for the page-up key */
  19225. static const int pageDownKey; /**< key-code for the page-down key */
  19226. static const int homeKey; /**< key-code for the home key */
  19227. static const int endKey; /**< key-code for the end key */
  19228. static const int F1Key; /**< key-code for the F1 key */
  19229. static const int F2Key; /**< key-code for the F2 key */
  19230. static const int F3Key; /**< key-code for the F3 key */
  19231. static const int F4Key; /**< key-code for the F4 key */
  19232. static const int F5Key; /**< key-code for the F5 key */
  19233. static const int F6Key; /**< key-code for the F6 key */
  19234. static const int F7Key; /**< key-code for the F7 key */
  19235. static const int F8Key; /**< key-code for the F8 key */
  19236. static const int F9Key; /**< key-code for the F9 key */
  19237. static const int F10Key; /**< key-code for the F10 key */
  19238. static const int F11Key; /**< key-code for the F11 key */
  19239. static const int F12Key; /**< key-code for the F12 key */
  19240. static const int F13Key; /**< key-code for the F13 key */
  19241. static const int F14Key; /**< key-code for the F14 key */
  19242. static const int F15Key; /**< key-code for the F15 key */
  19243. static const int F16Key; /**< key-code for the F16 key */
  19244. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  19245. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  19246. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  19247. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  19248. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  19249. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  19250. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  19251. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  19252. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  19253. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  19254. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  19255. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  19256. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  19257. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  19258. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  19259. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  19260. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  19261. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  19262. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  19263. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  19264. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  19265. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  19266. private:
  19267. int keyCode;
  19268. ModifierKeys mods;
  19269. juce_wchar textCharacter;
  19270. JUCE_LEAK_DETECTOR (KeyPress);
  19271. };
  19272. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  19273. /*** End of inlined file: juce_KeyPress.h ***/
  19274. class Component;
  19275. /**
  19276. Receives callbacks when keys are pressed.
  19277. You can add a key listener to a component to be informed when that component
  19278. gets key events. See the Component::addListener method for more details.
  19279. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  19280. */
  19281. class JUCE_API KeyListener
  19282. {
  19283. public:
  19284. /** Destructor. */
  19285. virtual ~KeyListener() {}
  19286. /** Called to indicate that a key has been pressed.
  19287. If your implementation returns true, then the key event is considered to have
  19288. been consumed, and will not be passed on to any other components. If it returns
  19289. false, then the key will be passed to other components that might want to use it.
  19290. @param key the keystroke, including modifier keys
  19291. @param originatingComponent the component that received the key event
  19292. @see keyStateChanged, Component::keyPressed
  19293. */
  19294. virtual bool keyPressed (const KeyPress& key,
  19295. Component* originatingComponent) = 0;
  19296. /** Called when any key is pressed or released.
  19297. When this is called, classes that might be interested in
  19298. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  19299. check whether their key has changed.
  19300. If your implementation returns true, then the key event is considered to have
  19301. been consumed, and will not be passed on to any other components. If it returns
  19302. false, then the key will be passed to other components that might want to use it.
  19303. @param originatingComponent the component that received the key event
  19304. @param isKeyDown true if a key is being pressed, false if one is being released
  19305. @see KeyPress, Component::keyStateChanged
  19306. */
  19307. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  19308. };
  19309. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  19310. /*** End of inlined file: juce_KeyListener.h ***/
  19311. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  19312. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  19313. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  19314. class Component;
  19315. /**
  19316. Controls the order in which focus moves between components.
  19317. The default algorithm used by this class to work out the order of traversal
  19318. is as follows:
  19319. - if two components both have an explicit focus order specified, then the
  19320. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  19321. method).
  19322. - any component with an explicit focus order greater than 0 comes before ones
  19323. that don't have an order specified.
  19324. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  19325. order.
  19326. If you need traversal in a more customised way, you can create a subclass
  19327. of KeyboardFocusTraverser that uses your own algorithm, and use
  19328. Component::createFocusTraverser() to create it.
  19329. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  19330. */
  19331. class JUCE_API KeyboardFocusTraverser
  19332. {
  19333. public:
  19334. KeyboardFocusTraverser();
  19335. /** Destructor. */
  19336. virtual ~KeyboardFocusTraverser();
  19337. /** Returns the component that should be given focus after the specified one
  19338. when moving "forwards".
  19339. The default implementation will return the next component which is to the
  19340. right of or below this one.
  19341. This may return 0 if there's no suitable candidate.
  19342. */
  19343. virtual Component* getNextComponent (Component* current);
  19344. /** Returns the component that should be given focus after the specified one
  19345. when moving "backwards".
  19346. The default implementation will return the next component which is to the
  19347. left of or above this one.
  19348. This may return 0 if there's no suitable candidate.
  19349. */
  19350. virtual Component* getPreviousComponent (Component* current);
  19351. /** Returns the component that should receive focus be default within the given
  19352. parent component.
  19353. The default implementation will just return the foremost child component that
  19354. wants focus.
  19355. This may return 0 if there's no suitable candidate.
  19356. */
  19357. virtual Component* getDefaultComponent (Component* parentComponent);
  19358. };
  19359. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  19360. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  19361. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  19362. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  19363. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  19364. /*** Start of inlined file: juce_Graphics.h ***/
  19365. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  19366. #define __JUCE_GRAPHICS_JUCEHEADER__
  19367. /*** Start of inlined file: juce_Font.h ***/
  19368. #ifndef __JUCE_FONT_JUCEHEADER__
  19369. #define __JUCE_FONT_JUCEHEADER__
  19370. /*** Start of inlined file: juce_Typeface.h ***/
  19371. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  19372. #define __JUCE_TYPEFACE_JUCEHEADER__
  19373. class Path;
  19374. class Font;
  19375. class EdgeTable;
  19376. class AffineTransform;
  19377. /**
  19378. A typeface represents a size-independent font.
  19379. This base class is abstract, but calling createSystemTypefaceFor() will return
  19380. a platform-specific subclass that can be used.
  19381. The CustomTypeface subclass allow you to build your own typeface, and to
  19382. load and save it in the Juce typeface format.
  19383. Normally you should never need to deal directly with Typeface objects - the Font
  19384. class does everything you typically need for rendering text.
  19385. @see CustomTypeface, Font
  19386. */
  19387. class JUCE_API Typeface : public SingleThreadedReferenceCountedObject
  19388. {
  19389. public:
  19390. /** A handy typedef for a pointer to a typeface. */
  19391. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  19392. /** Returns the name of the typeface.
  19393. @see Font::getTypefaceName
  19394. */
  19395. const String& getName() const noexcept { return name; }
  19396. /** Creates a new system typeface. */
  19397. static Ptr createSystemTypefaceFor (const Font& font);
  19398. /** Destructor. */
  19399. virtual ~Typeface();
  19400. /** Returns true if this typeface can be used to render the specified font.
  19401. When called, the font will already have been checked to make sure that its name and
  19402. style flags match the typeface.
  19403. */
  19404. virtual bool isSuitableForFont (const Font&) const { return true; }
  19405. /** Returns the ascent of the font, as a proportion of its height.
  19406. The height is considered to always be normalised as 1.0, so this will be a
  19407. value less that 1.0, indicating the proportion of the font that lies above
  19408. its baseline.
  19409. */
  19410. virtual float getAscent() const = 0;
  19411. /** Returns the descent of the font, as a proportion of its height.
  19412. The height is considered to always be normalised as 1.0, so this will be a
  19413. value less that 1.0, indicating the proportion of the font that lies below
  19414. its baseline.
  19415. */
  19416. virtual float getDescent() const = 0;
  19417. /** Measures the width of a line of text.
  19418. The distance returned is based on the font having an normalised height of 1.0.
  19419. You should never need to call this directly! Use Font::getStringWidth() instead!
  19420. */
  19421. virtual float getStringWidth (const String& text) = 0;
  19422. /** Converts a line of text into its glyph numbers and their positions.
  19423. The distances returned are based on the font having an normalised height of 1.0.
  19424. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  19425. */
  19426. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  19427. /** Returns the outline for a glyph.
  19428. The path returned will be normalised to a font height of 1.0.
  19429. */
  19430. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  19431. /** Returns a new EdgeTable that contains the path for the givem glyph, with the specified transform applied. */
  19432. virtual EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform);
  19433. /** Returns true if the typeface uses hinting. */
  19434. virtual bool isHinted() const { return false; }
  19435. /** Changes the number of fonts that are cached in memory. */
  19436. static void setTypefaceCacheSize (int numFontsToCache);
  19437. protected:
  19438. String name;
  19439. explicit Typeface (const String& name) noexcept;
  19440. static Ptr getFallbackTypeface();
  19441. private:
  19442. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Typeface);
  19443. };
  19444. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  19445. /*** End of inlined file: juce_Typeface.h ***/
  19446. class LowLevelGraphicsContext;
  19447. /**
  19448. Represents a particular font, including its size, style, etc.
  19449. Apart from the typeface to be used, a Font object also dictates whether
  19450. the font is bold, italic, underlined, how big it is, and its kerning and
  19451. horizontal scale factor.
  19452. @see Typeface
  19453. */
  19454. class JUCE_API Font
  19455. {
  19456. public:
  19457. /** A combination of these values is used by the constructor to specify the
  19458. style of font to use.
  19459. */
  19460. enum FontStyleFlags
  19461. {
  19462. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  19463. bold = 1, /**< boldens the font. @see setStyleFlags */
  19464. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  19465. underlined = 4 /**< underlines the font. @see setStyleFlags */
  19466. };
  19467. /** Creates a sans-serif font in a given size.
  19468. @param fontHeight the height in pixels (can be fractional)
  19469. @param styleFlags the style to use - this can be a combination of the
  19470. Font::bold, Font::italic and Font::underlined, or
  19471. just Font::plain for the normal style.
  19472. @see FontStyleFlags, getDefaultSansSerifFontName
  19473. */
  19474. Font (float fontHeight, int styleFlags = plain);
  19475. /** Creates a font with a given typeface and parameters.
  19476. @param typefaceName the name of the typeface to use
  19477. @param fontHeight the height in pixels (can be fractional)
  19478. @param styleFlags the style to use - this can be a combination of the
  19479. Font::bold, Font::italic and Font::underlined, or
  19480. just Font::plain for the normal style.
  19481. @see FontStyleFlags, getDefaultSansSerifFontName
  19482. */
  19483. Font (const String& typefaceName, float fontHeight, int styleFlags);
  19484. /** Creates a copy of another Font object. */
  19485. Font (const Font& other) noexcept;
  19486. /** Creates a font for a typeface. */
  19487. Font (const Typeface::Ptr& typeface);
  19488. /** Creates a basic sans-serif font at a default height.
  19489. You should use one of the other constructors for creating a font that you're planning
  19490. on drawing with - this constructor is here to help initialise objects before changing
  19491. the font's settings later.
  19492. */
  19493. Font();
  19494. /** Copies this font from another one. */
  19495. Font& operator= (const Font& other) noexcept;
  19496. bool operator== (const Font& other) const noexcept;
  19497. bool operator!= (const Font& other) const noexcept;
  19498. /** Destructor. */
  19499. ~Font() noexcept;
  19500. /** Changes the name of the typeface family.
  19501. e.g. "Arial", "Courier", etc.
  19502. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  19503. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  19504. but are generic names that are used to represent the various default fonts.
  19505. If you need to know the exact typeface name being used, you can call
  19506. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  19507. If a suitable font isn't found on the machine, it'll just use a default instead.
  19508. */
  19509. void setTypefaceName (const String& faceName);
  19510. /** Returns the name of the typeface family that this font uses.
  19511. e.g. "Arial", "Courier", etc.
  19512. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  19513. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  19514. but are generic names that are used to represent the various default fonts.
  19515. If you need to know the exact typeface name being used, you can call
  19516. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  19517. */
  19518. const String& getTypefaceName() const noexcept { return font->typefaceName; }
  19519. /** Returns a typeface name that represents the default sans-serif font.
  19520. This is also the typeface that will be used when a font is created without
  19521. specifying any typeface details.
  19522. Note that this method just returns a generic placeholder string that means "the default
  19523. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  19524. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  19525. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  19526. */
  19527. static const String& getDefaultSansSerifFontName();
  19528. /** Returns a typeface name that represents the default sans-serif font.
  19529. Note that this method just returns a generic placeholder string that means "the default
  19530. serif font" - it's not the actual name of this font. To get the actual name, use
  19531. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  19532. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  19533. */
  19534. static const String& getDefaultSerifFontName();
  19535. /** Returns a typeface name that represents the default sans-serif font.
  19536. Note that this method just returns a generic placeholder string that means "the default
  19537. monospaced font" - it's not the actual name of this font. To get the actual name, use
  19538. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  19539. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  19540. */
  19541. static const String& getDefaultMonospacedFontName();
  19542. /** Returns the typeface names of the default fonts on the current platform. */
  19543. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback);
  19544. /** Returns the total height of this font.
  19545. This is the maximum height, from the top of the ascent to the bottom of the
  19546. descenders.
  19547. @see setHeight, setHeightWithoutChangingWidth, getAscent
  19548. */
  19549. float getHeight() const noexcept { return font->height; }
  19550. /** Changes the font's height.
  19551. @see getHeight, setHeightWithoutChangingWidth
  19552. */
  19553. void setHeight (float newHeight);
  19554. /** Changes the font's height without changing its width.
  19555. This alters the horizontal scale to compensate for the change in height.
  19556. */
  19557. void setHeightWithoutChangingWidth (float newHeight);
  19558. /** Returns the height of the font above its baseline.
  19559. This is the maximum height from the baseline to the top.
  19560. @see getHeight, getDescent
  19561. */
  19562. float getAscent() const;
  19563. /** Returns the amount that the font descends below its baseline.
  19564. This is calculated as (getHeight() - getAscent()).
  19565. @see getAscent, getHeight
  19566. */
  19567. float getDescent() const;
  19568. /** Returns the font's style flags.
  19569. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  19570. enum, to describe whether the font is bold, italic, etc.
  19571. @see FontStyleFlags
  19572. */
  19573. int getStyleFlags() const noexcept { return font->styleFlags; }
  19574. /** Changes the font's style.
  19575. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  19576. enum, to set the font's properties
  19577. @see FontStyleFlags
  19578. */
  19579. void setStyleFlags (int newFlags);
  19580. /** Makes the font bold or non-bold. */
  19581. void setBold (bool shouldBeBold);
  19582. /** Returns a copy of this font with the bold attribute set. */
  19583. Font boldened() const;
  19584. /** Returns true if the font is bold. */
  19585. bool isBold() const noexcept;
  19586. /** Makes the font italic or non-italic. */
  19587. void setItalic (bool shouldBeItalic);
  19588. /** Returns a copy of this font with the italic attribute set. */
  19589. Font italicised() const;
  19590. /** Returns true if the font is italic. */
  19591. bool isItalic() const noexcept;
  19592. /** Makes the font underlined or non-underlined. */
  19593. void setUnderline (bool shouldBeUnderlined);
  19594. /** Returns true if the font is underlined. */
  19595. bool isUnderlined() const noexcept;
  19596. /** Changes the font's horizontal scale factor.
  19597. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  19598. narrower, greater than 1.0 will be stretched out.
  19599. */
  19600. void setHorizontalScale (float scaleFactor);
  19601. /** Returns the font's horizontal scale.
  19602. A value of 1.0 is the normal scale, less than this will be narrower, greater
  19603. than 1.0 will be stretched out.
  19604. @see setHorizontalScale
  19605. */
  19606. float getHorizontalScale() const noexcept { return font->horizontalScale; }
  19607. /** Changes the font's kerning.
  19608. @param extraKerning a multiple of the font's height that will be added
  19609. to space between the characters. So a value of zero is
  19610. normal spacing, positive values spread the letters out,
  19611. negative values make them closer together.
  19612. */
  19613. void setExtraKerningFactor (float extraKerning);
  19614. /** Returns the font's kerning.
  19615. This is the extra space added between adjacent characters, as a proportion
  19616. of the font's height.
  19617. A value of zero is normal spacing, positive values will spread the letters
  19618. out more, and negative values make them closer together.
  19619. */
  19620. float getExtraKerningFactor() const noexcept { return font->kerning; }
  19621. /** Changes all the font's characteristics with one call. */
  19622. void setSizeAndStyle (float newHeight,
  19623. int newStyleFlags,
  19624. float newHorizontalScale,
  19625. float newKerningAmount);
  19626. /** Returns the total width of a string as it would be drawn using this font.
  19627. For a more accurate floating-point result, use getStringWidthFloat().
  19628. */
  19629. int getStringWidth (const String& text) const;
  19630. /** Returns the total width of a string as it would be drawn using this font.
  19631. @see getStringWidth
  19632. */
  19633. float getStringWidthFloat (const String& text) const;
  19634. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  19635. An extra x offset is added at the end of the run, to indicate where the right hand
  19636. edge of the last character is.
  19637. */
  19638. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const;
  19639. /** Returns the typeface used by this font.
  19640. Note that the object returned may go out of scope if this font is deleted
  19641. or has its style changed.
  19642. */
  19643. Typeface* getTypeface() const;
  19644. /** Creates an array of Font objects to represent all the fonts on the system.
  19645. If you just need the names of the typefaces, you can also use
  19646. findAllTypefaceNames() instead.
  19647. @param results the array to which new Font objects will be added.
  19648. */
  19649. static void findFonts (Array<Font>& results);
  19650. /** Returns a list of all the available typeface names.
  19651. The names returned can be passed into setTypefaceName().
  19652. You can use this instead of findFonts() if you only need their names, and not
  19653. font objects.
  19654. */
  19655. static StringArray findAllTypefaceNames();
  19656. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  19657. in the requested typeface.
  19658. */
  19659. static const String& getFallbackFontName();
  19660. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  19661. available in whatever font you're trying to use.
  19662. */
  19663. static void setFallbackFontName (const String& name);
  19664. /** Creates a string to describe this font.
  19665. The string will contain information to describe the font's typeface, size, and
  19666. style. To recreate the font from this string, use fromString().
  19667. */
  19668. String toString() const;
  19669. /** Recreates a font from its stringified encoding.
  19670. This method takes a string that was created by toString(), and recreates the
  19671. original font.
  19672. */
  19673. static Font fromString (const String& fontDescription);
  19674. private:
  19675. friend class FontGlyphAlphaMap;
  19676. friend class TypefaceCache;
  19677. class SharedFontInternal : public SingleThreadedReferenceCountedObject
  19678. {
  19679. public:
  19680. SharedFontInternal (float height, int styleFlags) noexcept;
  19681. SharedFontInternal (const String& typefaceName, float height, int styleFlags) noexcept;
  19682. SharedFontInternal (const Typeface::Ptr& typeface) noexcept;
  19683. SharedFontInternal (const SharedFontInternal& other) noexcept;
  19684. bool operator== (const SharedFontInternal&) const noexcept;
  19685. String typefaceName;
  19686. float height, horizontalScale, kerning, ascent;
  19687. int styleFlags;
  19688. Typeface::Ptr typeface;
  19689. };
  19690. ReferenceCountedObjectPtr <SharedFontInternal> font;
  19691. void dupeInternalIfShared();
  19692. JUCE_LEAK_DETECTOR (Font);
  19693. };
  19694. #endif // __JUCE_FONT_JUCEHEADER__
  19695. /*** End of inlined file: juce_Font.h ***/
  19696. /*** Start of inlined file: juce_Rectangle.h ***/
  19697. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  19698. #define __JUCE_RECTANGLE_JUCEHEADER__
  19699. class RectangleList;
  19700. /**
  19701. Manages a rectangle and allows geometric operations to be performed on it.
  19702. @see RectangleList, Path, Line, Point
  19703. */
  19704. template <typename ValueType>
  19705. class Rectangle
  19706. {
  19707. public:
  19708. /** Creates a rectangle of zero size.
  19709. The default co-ordinates will be (0, 0, 0, 0).
  19710. */
  19711. Rectangle() noexcept
  19712. : x(), y(), w(), h()
  19713. {
  19714. }
  19715. /** Creates a copy of another rectangle. */
  19716. Rectangle (const Rectangle& other) noexcept
  19717. : x (other.x), y (other.y),
  19718. w (other.w), h (other.h)
  19719. {
  19720. }
  19721. /** Creates a rectangle with a given position and size. */
  19722. Rectangle (const ValueType initialX, const ValueType initialY,
  19723. const ValueType width, const ValueType height) noexcept
  19724. : x (initialX), y (initialY),
  19725. w (width), h (height)
  19726. {
  19727. }
  19728. /** Creates a rectangle with a given size, and a position of (0, 0). */
  19729. Rectangle (const ValueType width, const ValueType height) noexcept
  19730. : x(), y(), w (width), h (height)
  19731. {
  19732. }
  19733. /** Creates a Rectangle from the positions of two opposite corners. */
  19734. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) noexcept
  19735. : x (jmin (corner1.getX(), corner2.getX())),
  19736. y (jmin (corner1.getY(), corner2.getY())),
  19737. w (corner1.getX() - corner2.getX()),
  19738. h (corner1.getY() - corner2.getY())
  19739. {
  19740. if (w < ValueType()) w = -w;
  19741. if (h < ValueType()) h = -h;
  19742. }
  19743. /** Creates a Rectangle from a set of left, right, top, bottom coordinates.
  19744. The right and bottom values must be larger than the left and top ones, or the resulting
  19745. rectangle will have a negative size.
  19746. */
  19747. static Rectangle leftTopRightBottom (const ValueType left, const ValueType top,
  19748. const ValueType right, const ValueType bottom) noexcept
  19749. {
  19750. return Rectangle (left, top, right - left, bottom - top);
  19751. }
  19752. Rectangle& operator= (const Rectangle& other) noexcept
  19753. {
  19754. x = other.x; y = other.y;
  19755. w = other.w; h = other.h;
  19756. return *this;
  19757. }
  19758. /** Destructor. */
  19759. ~Rectangle() noexcept {}
  19760. /** Returns true if the rectangle's width and height are both zero or less */
  19761. bool isEmpty() const noexcept { return w <= ValueType() || h <= ValueType(); }
  19762. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  19763. inline ValueType getX() const noexcept { return x; }
  19764. /** Returns the y co-ordinate of the rectangle's top edge. */
  19765. inline ValueType getY() const noexcept { return y; }
  19766. /** Returns the width of the rectangle. */
  19767. inline ValueType getWidth() const noexcept { return w; }
  19768. /** Returns the height of the rectangle. */
  19769. inline ValueType getHeight() const noexcept { return h; }
  19770. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  19771. inline ValueType getRight() const noexcept { return x + w; }
  19772. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  19773. inline ValueType getBottom() const noexcept { return y + h; }
  19774. /** Returns the x co-ordinate of the rectangle's centre. */
  19775. ValueType getCentreX() const noexcept { return x + w / (ValueType) 2; }
  19776. /** Returns the y co-ordinate of the rectangle's centre. */
  19777. ValueType getCentreY() const noexcept { return y + h / (ValueType) 2; }
  19778. /** Returns the centre point of the rectangle. */
  19779. Point<ValueType> getCentre() const noexcept { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  19780. /** Returns the aspect ratio of the rectangle's width / height.
  19781. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  19782. it returns height / width. */
  19783. ValueType getAspectRatio (const bool widthOverHeight = true) const noexcept { return widthOverHeight ? w / h : h / w; }
  19784. /** Returns the rectangle's top-left position as a Point. */
  19785. Point<ValueType> getPosition() const noexcept { return Point<ValueType> (x, y); }
  19786. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  19787. void setPosition (const Point<ValueType>& newPos) noexcept { x = newPos.getX(); y = newPos.getY(); }
  19788. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  19789. void setPosition (const ValueType newX, const ValueType newY) noexcept { x = newX; y = newY; }
  19790. /** Returns a rectangle with the same size as this one, but a new position. */
  19791. Rectangle withPosition (const ValueType newX, const ValueType newY) const noexcept { return Rectangle (newX, newY, w, h); }
  19792. /** Returns a rectangle with the same size as this one, but a new position. */
  19793. Rectangle withPosition (const Point<ValueType>& newPos) const noexcept { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  19794. /** Returns the rectangle's top-left position as a Point. */
  19795. Point<ValueType> getTopLeft() const noexcept { return getPosition(); }
  19796. /** Returns the rectangle's top-right position as a Point. */
  19797. Point<ValueType> getTopRight() const noexcept { return Point<ValueType> (x + w, y); }
  19798. /** Returns the rectangle's bottom-left position as a Point. */
  19799. Point<ValueType> getBottomLeft() const noexcept { return Point<ValueType> (x, y + h); }
  19800. /** Returns the rectangle's bottom-right position as a Point. */
  19801. Point<ValueType> getBottomRight() const noexcept { return Point<ValueType> (x + w, y + h); }
  19802. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  19803. void setSize (const ValueType newWidth, const ValueType newHeight) noexcept { w = newWidth; h = newHeight; }
  19804. /** Returns a rectangle with the same position as this one, but a new size. */
  19805. Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const noexcept { return Rectangle (x, y, newWidth, newHeight); }
  19806. /** Changes all the rectangle's co-ordinates. */
  19807. void setBounds (const ValueType newX, const ValueType newY,
  19808. const ValueType newWidth, const ValueType newHeight) noexcept
  19809. {
  19810. x = newX; y = newY; w = newWidth; h = newHeight;
  19811. }
  19812. /** Changes the rectangle's X coordinate */
  19813. void setX (const ValueType newX) noexcept { x = newX; }
  19814. /** Changes the rectangle's Y coordinate */
  19815. void setY (const ValueType newY) noexcept { y = newY; }
  19816. /** Changes the rectangle's width */
  19817. void setWidth (const ValueType newWidth) noexcept { w = newWidth; }
  19818. /** Changes the rectangle's height */
  19819. void setHeight (const ValueType newHeight) noexcept { h = newHeight; }
  19820. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  19821. Rectangle withX (const ValueType newX) const noexcept { return Rectangle (newX, y, w, h); }
  19822. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  19823. Rectangle withY (const ValueType newY) const noexcept { return Rectangle (x, newY, w, h); }
  19824. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  19825. Rectangle withWidth (const ValueType newWidth) const noexcept { return Rectangle (x, y, newWidth, h); }
  19826. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  19827. Rectangle withHeight (const ValueType newHeight) const noexcept { return Rectangle (x, y, w, newHeight); }
  19828. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  19829. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  19830. @see withLeft
  19831. */
  19832. void setLeft (const ValueType newLeft) noexcept
  19833. {
  19834. w = jmax (ValueType(), x + w - newLeft);
  19835. x = newLeft;
  19836. }
  19837. /** Returns a new rectangle with a different x position, but the same right-hand edge as this one.
  19838. If the new x is beyond the right of the current right-hand edge, the width will be set to zero.
  19839. @see setLeft
  19840. */
  19841. Rectangle withLeft (const ValueType newLeft) const noexcept { return Rectangle (newLeft, y, jmax (ValueType(), x + w - newLeft), h); }
  19842. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  19843. If the y is moved to be below the current bottom edge, the height will be set to zero.
  19844. @see withTop
  19845. */
  19846. void setTop (const ValueType newTop) noexcept
  19847. {
  19848. h = jmax (ValueType(), y + h - newTop);
  19849. y = newTop;
  19850. }
  19851. /** Returns a new rectangle with a different y position, but the same bottom edge as this one.
  19852. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  19853. @see setTop
  19854. */
  19855. Rectangle withTop (const ValueType newTop) const noexcept { return Rectangle (x, newTop, w, jmax (ValueType(), y + h - newTop)); }
  19856. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  19857. If the new right is below the current X value, the X will be pushed down to match it.
  19858. @see getRight, withRight
  19859. */
  19860. void setRight (const ValueType newRight) noexcept
  19861. {
  19862. x = jmin (x, newRight);
  19863. w = newRight - x;
  19864. }
  19865. /** Returns a new rectangle with a different right-hand edge position, but the same left-hand edge as this one.
  19866. If the new right edge is below the current left-hand edge, the width will be set to zero.
  19867. @see setRight
  19868. */
  19869. Rectangle withRight (const ValueType newRight) const noexcept { return Rectangle (jmin (x, newRight), y, jmax (ValueType(), newRight - x), h); }
  19870. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  19871. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  19872. @see getBottom, withBottom
  19873. */
  19874. void setBottom (const ValueType newBottom) noexcept
  19875. {
  19876. y = jmin (y, newBottom);
  19877. h = newBottom - y;
  19878. }
  19879. /** Returns a new rectangle with a different bottom edge position, but the same top edge as this one.
  19880. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  19881. @see setBottom
  19882. */
  19883. Rectangle withBottom (const ValueType newBottom) const noexcept { return Rectangle (x, jmin (y, newBottom), w, jmax (ValueType(), newBottom - y)); }
  19884. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  19885. void translate (const ValueType deltaX,
  19886. const ValueType deltaY) noexcept
  19887. {
  19888. x += deltaX;
  19889. y += deltaY;
  19890. }
  19891. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19892. Rectangle translated (const ValueType deltaX,
  19893. const ValueType deltaY) const noexcept
  19894. {
  19895. return Rectangle (x + deltaX, y + deltaY, w, h);
  19896. }
  19897. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19898. Rectangle operator+ (const Point<ValueType>& deltaPosition) const noexcept
  19899. {
  19900. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  19901. }
  19902. /** Moves this rectangle by a given amount. */
  19903. Rectangle& operator+= (const Point<ValueType>& deltaPosition) noexcept
  19904. {
  19905. x += deltaPosition.getX(); y += deltaPosition.getY();
  19906. return *this;
  19907. }
  19908. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19909. Rectangle operator- (const Point<ValueType>& deltaPosition) const noexcept
  19910. {
  19911. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  19912. }
  19913. /** Moves this rectangle by a given amount. */
  19914. Rectangle& operator-= (const Point<ValueType>& deltaPosition) noexcept
  19915. {
  19916. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  19917. return *this;
  19918. }
  19919. /** Expands the rectangle by a given amount.
  19920. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  19921. @see expanded, reduce, reduced
  19922. */
  19923. void expand (const ValueType deltaX,
  19924. const ValueType deltaY) noexcept
  19925. {
  19926. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  19927. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  19928. setBounds (x - deltaX, y - deltaY, nw, nh);
  19929. }
  19930. /** Returns a rectangle that is larger than this one by a given amount.
  19931. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  19932. @see expand, reduce, reduced
  19933. */
  19934. Rectangle expanded (const ValueType deltaX,
  19935. const ValueType deltaY) const noexcept
  19936. {
  19937. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  19938. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  19939. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  19940. }
  19941. /** Shrinks the rectangle by a given amount.
  19942. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19943. @see reduced, expand, expanded
  19944. */
  19945. void reduce (const ValueType deltaX,
  19946. const ValueType deltaY) noexcept
  19947. {
  19948. expand (-deltaX, -deltaY);
  19949. }
  19950. /** Returns a rectangle that is smaller than this one by a given amount.
  19951. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19952. @see reduce, expand, expanded
  19953. */
  19954. Rectangle reduced (const ValueType deltaX,
  19955. const ValueType deltaY) const noexcept
  19956. {
  19957. return expanded (-deltaX, -deltaY);
  19958. }
  19959. /** Removes a strip from the top of this rectangle, reducing this rectangle
  19960. by the specified amount and returning the section that was removed.
  19961. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19962. return (100, 100, 300, 50) and leave this rectangle as (100, 150, 300, 250).
  19963. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19964. that value.
  19965. */
  19966. Rectangle removeFromTop (const ValueType amountToRemove) noexcept
  19967. {
  19968. const Rectangle r (x, y, w, jmin (amountToRemove, h));
  19969. y += r.h; h -= r.h;
  19970. return r;
  19971. }
  19972. /** Removes a strip from the left-hand edge of this rectangle, reducing this rectangle
  19973. by the specified amount and returning the section that was removed.
  19974. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19975. return (100, 100, 50, 300) and leave this rectangle as (150, 100, 250, 300).
  19976. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19977. that value.
  19978. */
  19979. Rectangle removeFromLeft (const ValueType amountToRemove) noexcept
  19980. {
  19981. const Rectangle r (x, y, jmin (amountToRemove, w), h);
  19982. x += r.w; w -= r.w;
  19983. return r;
  19984. }
  19985. /** Removes a strip from the right-hand edge of this rectangle, reducing this rectangle
  19986. by the specified amount and returning the section that was removed.
  19987. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19988. return (250, 100, 50, 300) and leave this rectangle as (100, 100, 250, 300).
  19989. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19990. that value.
  19991. */
  19992. Rectangle removeFromRight (ValueType amountToRemove) noexcept
  19993. {
  19994. amountToRemove = jmin (amountToRemove, w);
  19995. const Rectangle r (x + w - amountToRemove, y, amountToRemove, h);
  19996. w -= amountToRemove;
  19997. return r;
  19998. }
  19999. /** Removes a strip from the bottom of this rectangle, reducing this rectangle
  20000. by the specified amount and returning the section that was removed.
  20001. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  20002. return (100, 250, 300, 50) and leave this rectangle as (100, 100, 300, 250).
  20003. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  20004. that value.
  20005. */
  20006. Rectangle removeFromBottom (ValueType amountToRemove) noexcept
  20007. {
  20008. amountToRemove = jmin (amountToRemove, h);
  20009. const Rectangle r (x, y + h - amountToRemove, w, amountToRemove);
  20010. h -= amountToRemove;
  20011. return r;
  20012. }
  20013. /** Returns true if the two rectangles are identical. */
  20014. bool operator== (const Rectangle& other) const noexcept
  20015. {
  20016. return x == other.x && y == other.y
  20017. && w == other.w && h == other.h;
  20018. }
  20019. /** Returns true if the two rectangles are not identical. */
  20020. bool operator!= (const Rectangle& other) const noexcept
  20021. {
  20022. return x != other.x || y != other.y
  20023. || w != other.w || h != other.h;
  20024. }
  20025. /** Returns true if this co-ordinate is inside the rectangle. */
  20026. bool contains (const ValueType xCoord, const ValueType yCoord) const noexcept
  20027. {
  20028. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  20029. }
  20030. /** Returns true if this co-ordinate is inside the rectangle. */
  20031. bool contains (const Point<ValueType>& point) const noexcept
  20032. {
  20033. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  20034. }
  20035. /** Returns true if this other rectangle is completely inside this one. */
  20036. bool contains (const Rectangle& other) const noexcept
  20037. {
  20038. return x <= other.x && y <= other.y
  20039. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  20040. }
  20041. /** Returns the nearest point to the specified point that lies within this rectangle. */
  20042. Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const noexcept
  20043. {
  20044. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  20045. jlimit (y, y + h, point.getY()));
  20046. }
  20047. /** Returns true if any part of another rectangle overlaps this one. */
  20048. bool intersects (const Rectangle& other) const noexcept
  20049. {
  20050. return x + w > other.x
  20051. && y + h > other.y
  20052. && x < other.x + other.w
  20053. && y < other.y + other.h
  20054. && w > ValueType() && h > ValueType();
  20055. }
  20056. /** Returns the region that is the overlap between this and another rectangle.
  20057. If the two rectangles don't overlap, the rectangle returned will be empty.
  20058. */
  20059. Rectangle getIntersection (const Rectangle& other) const noexcept
  20060. {
  20061. const ValueType nx = jmax (x, other.x);
  20062. const ValueType ny = jmax (y, other.y);
  20063. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  20064. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  20065. if (nw >= ValueType() && nh >= ValueType())
  20066. return Rectangle (nx, ny, nw, nh);
  20067. return Rectangle();
  20068. }
  20069. /** Clips a rectangle so that it lies only within this one.
  20070. This is a non-static version of intersectRectangles().
  20071. Returns false if the two regions didn't overlap.
  20072. */
  20073. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const noexcept
  20074. {
  20075. const int maxX = jmax (otherX, x);
  20076. otherW = jmin (otherX + otherW, x + w) - maxX;
  20077. if (otherW > ValueType())
  20078. {
  20079. const int maxY = jmax (otherY, y);
  20080. otherH = jmin (otherY + otherH, y + h) - maxY;
  20081. if (otherH > ValueType())
  20082. {
  20083. otherX = maxX; otherY = maxY;
  20084. return true;
  20085. }
  20086. }
  20087. return false;
  20088. }
  20089. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  20090. If either this or the other rectangle are empty, they will not be counted as
  20091. part of the resulting region.
  20092. */
  20093. Rectangle getUnion (const Rectangle& other) const noexcept
  20094. {
  20095. if (other.isEmpty()) return *this;
  20096. if (isEmpty()) return other;
  20097. const ValueType newX = jmin (x, other.x);
  20098. const ValueType newY = jmin (y, other.y);
  20099. return Rectangle (newX, newY,
  20100. jmax (x + w, other.x + other.w) - newX,
  20101. jmax (y + h, other.y + other.h) - newY);
  20102. }
  20103. /** If this rectangle merged with another one results in a simple rectangle, this
  20104. will set this rectangle to the result, and return true.
  20105. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  20106. or if they form a complex region.
  20107. */
  20108. bool enlargeIfAdjacent (const Rectangle& other) noexcept
  20109. {
  20110. if (x == other.x && getRight() == other.getRight()
  20111. && (other.getBottom() >= y && other.y <= getBottom()))
  20112. {
  20113. const ValueType newY = jmin (y, other.y);
  20114. h = jmax (getBottom(), other.getBottom()) - newY;
  20115. y = newY;
  20116. return true;
  20117. }
  20118. else if (y == other.y && getBottom() == other.getBottom()
  20119. && (other.getRight() >= x && other.x <= getRight()))
  20120. {
  20121. const ValueType newX = jmin (x, other.x);
  20122. w = jmax (getRight(), other.getRight()) - newX;
  20123. x = newX;
  20124. return true;
  20125. }
  20126. return false;
  20127. }
  20128. /** If after removing another rectangle from this one the result is a simple rectangle,
  20129. this will set this object's bounds to be the result, and return true.
  20130. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  20131. or if removing the other one would form a complex region.
  20132. */
  20133. bool reduceIfPartlyContainedIn (const Rectangle& other) noexcept
  20134. {
  20135. int inside = 0;
  20136. const int otherR = other.getRight();
  20137. if (x >= other.x && x < otherR) inside = 1;
  20138. const int otherB = other.getBottom();
  20139. if (y >= other.y && y < otherB) inside |= 2;
  20140. const int r = x + w;
  20141. if (r >= other.x && r < otherR) inside |= 4;
  20142. const int b = y + h;
  20143. if (b >= other.y && b < otherB) inside |= 8;
  20144. switch (inside)
  20145. {
  20146. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  20147. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  20148. case 2 + 4 + 8: w = other.x - x; return true;
  20149. case 1 + 4 + 8: h = other.y - y; return true;
  20150. }
  20151. return false;
  20152. }
  20153. /** Returns the smallest rectangle that can contain the shape created by applying
  20154. a transform to this rectangle.
  20155. This should only be used on floating point rectangles.
  20156. */
  20157. Rectangle transformed (const AffineTransform& transform) const noexcept
  20158. {
  20159. float x1 = x, y1 = y;
  20160. float x2 = x + w, y2 = y;
  20161. float x3 = x, y3 = y + h;
  20162. float x4 = x2, y4 = y3;
  20163. transform.transformPoints (x1, y1, x2, y2);
  20164. transform.transformPoints (x3, y3, x4, y4);
  20165. const float rx = jmin (x1, x2, x3, x4);
  20166. const float ry = jmin (y1, y2, y3, y4);
  20167. return Rectangle (rx, ry,
  20168. jmax (x1, x2, x3, x4) - rx,
  20169. jmax (y1, y2, y3, y4) - ry);
  20170. }
  20171. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  20172. This is only relevent for floating-point rectangles, of course.
  20173. @see toFloat()
  20174. */
  20175. const Rectangle<int> getSmallestIntegerContainer() const noexcept
  20176. {
  20177. const int x1 = (int) std::floor (static_cast<float> (x));
  20178. const int y1 = (int) std::floor (static_cast<float> (y));
  20179. const int x2 = (int) std::ceil (static_cast<float> (x + w));
  20180. const int y2 = (int) std::ceil (static_cast<float> (y + h));
  20181. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  20182. }
  20183. /** Returns the smallest Rectangle that can contain a set of points. */
  20184. static Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) noexcept
  20185. {
  20186. if (numPoints == 0)
  20187. return Rectangle();
  20188. ValueType minX (points[0].getX());
  20189. ValueType maxX (minX);
  20190. ValueType minY (points[0].getY());
  20191. ValueType maxY (minY);
  20192. for (int i = 1; i < numPoints; ++i)
  20193. {
  20194. minX = jmin (minX, points[i].getX());
  20195. maxX = jmax (maxX, points[i].getX());
  20196. minY = jmin (minY, points[i].getY());
  20197. maxY = jmax (maxY, points[i].getY());
  20198. }
  20199. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  20200. }
  20201. /** Casts this rectangle to a Rectangle<float>.
  20202. Obviously this is mainly useful for rectangles that use integer types.
  20203. @see getSmallestIntegerContainer
  20204. */
  20205. const Rectangle<float> toFloat() const noexcept
  20206. {
  20207. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  20208. static_cast<float> (w), static_cast<float> (h));
  20209. }
  20210. /** Static utility to intersect two sets of rectangular co-ordinates.
  20211. Returns false if the two regions didn't overlap.
  20212. @see intersectRectangle
  20213. */
  20214. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  20215. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) noexcept
  20216. {
  20217. const ValueType x = jmax (x1, x2);
  20218. w1 = jmin (x1 + w1, x2 + w2) - x;
  20219. if (w1 > ValueType())
  20220. {
  20221. const ValueType y = jmax (y1, y2);
  20222. h1 = jmin (y1 + h1, y2 + h2) - y;
  20223. if (h1 > ValueType())
  20224. {
  20225. x1 = x; y1 = y;
  20226. return true;
  20227. }
  20228. }
  20229. return false;
  20230. }
  20231. /** Creates a string describing this rectangle.
  20232. The string will be of the form "x y width height", e.g. "100 100 400 200".
  20233. Coupled with the fromString() method, this is very handy for things like
  20234. storing rectangles (particularly component positions) in XML attributes.
  20235. @see fromString
  20236. */
  20237. String toString() const
  20238. {
  20239. String s;
  20240. s.preallocateBytes (32);
  20241. s << x << ' ' << y << ' ' << w << ' ' << h;
  20242. return s;
  20243. }
  20244. /** Parses a string containing a rectangle's details.
  20245. The string should contain 4 integer tokens, in the form "x y width height". They
  20246. can be comma or whitespace separated.
  20247. This method is intended to go with the toString() method, to form an easy way
  20248. of saving/loading rectangles as strings.
  20249. @see toString
  20250. */
  20251. static Rectangle fromString (const String& stringVersion)
  20252. {
  20253. StringArray toks;
  20254. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  20255. return Rectangle (toks[0].trim().getIntValue(),
  20256. toks[1].trim().getIntValue(),
  20257. toks[2].trim().getIntValue(),
  20258. toks[3].trim().getIntValue());
  20259. }
  20260. private:
  20261. friend class RectangleList;
  20262. ValueType x, y, w, h;
  20263. };
  20264. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  20265. /*** End of inlined file: juce_Rectangle.h ***/
  20266. /*** Start of inlined file: juce_PathStrokeType.h ***/
  20267. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20268. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20269. /*** Start of inlined file: juce_Path.h ***/
  20270. #ifndef __JUCE_PATH_JUCEHEADER__
  20271. #define __JUCE_PATH_JUCEHEADER__
  20272. /*** Start of inlined file: juce_Line.h ***/
  20273. #ifndef __JUCE_LINE_JUCEHEADER__
  20274. #define __JUCE_LINE_JUCEHEADER__
  20275. /**
  20276. Represents a line.
  20277. This class contains a bunch of useful methods for various geometric
  20278. tasks.
  20279. The ValueType template parameter should be a primitive type - float or double
  20280. are what it's designed for. Integer types will work in a basic way, but some methods
  20281. that perform mathematical operations may not compile, or they may not produce
  20282. sensible results.
  20283. @see Point, Rectangle, Path, Graphics::drawLine
  20284. */
  20285. template <typename ValueType>
  20286. class Line
  20287. {
  20288. public:
  20289. /** Creates a line, using (0, 0) as its start and end points. */
  20290. Line() noexcept {}
  20291. /** Creates a copy of another line. */
  20292. Line (const Line& other) noexcept
  20293. : start (other.start),
  20294. end (other.end)
  20295. {
  20296. }
  20297. /** Creates a line based on the co-ordinates of its start and end points. */
  20298. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) noexcept
  20299. : start (startX, startY),
  20300. end (endX, endY)
  20301. {
  20302. }
  20303. /** Creates a line from its start and end points. */
  20304. Line (const Point<ValueType>& startPoint,
  20305. const Point<ValueType>& endPoint) noexcept
  20306. : start (startPoint),
  20307. end (endPoint)
  20308. {
  20309. }
  20310. /** Copies a line from another one. */
  20311. Line& operator= (const Line& other) noexcept
  20312. {
  20313. start = other.start;
  20314. end = other.end;
  20315. return *this;
  20316. }
  20317. /** Destructor. */
  20318. ~Line() noexcept {}
  20319. /** Returns the x co-ordinate of the line's start point. */
  20320. inline ValueType getStartX() const noexcept { return start.getX(); }
  20321. /** Returns the y co-ordinate of the line's start point. */
  20322. inline ValueType getStartY() const noexcept { return start.getY(); }
  20323. /** Returns the x co-ordinate of the line's end point. */
  20324. inline ValueType getEndX() const noexcept { return end.getX(); }
  20325. /** Returns the y co-ordinate of the line's end point. */
  20326. inline ValueType getEndY() const noexcept { return end.getY(); }
  20327. /** Returns the line's start point. */
  20328. inline const Point<ValueType>& getStart() const noexcept { return start; }
  20329. /** Returns the line's end point. */
  20330. inline const Point<ValueType>& getEnd() const noexcept { return end; }
  20331. /** Changes this line's start point */
  20332. void setStart (ValueType newStartX, ValueType newStartY) noexcept { start.setXY (newStartX, newStartY); }
  20333. /** Changes this line's end point */
  20334. void setEnd (ValueType newEndX, ValueType newEndY) noexcept { end.setXY (newEndX, newEndY); }
  20335. /** Changes this line's start point */
  20336. void setStart (const Point<ValueType>& newStart) noexcept { start = newStart; }
  20337. /** Changes this line's end point */
  20338. void setEnd (const Point<ValueType>& newEnd) noexcept { end = newEnd; }
  20339. /** Returns a line that is the same as this one, but with the start and end reversed, */
  20340. const Line reversed() const noexcept { return Line (end, start); }
  20341. /** Applies an affine transform to the line's start and end points. */
  20342. void applyTransform (const AffineTransform& transform) noexcept
  20343. {
  20344. start.applyTransform (transform);
  20345. end.applyTransform (transform);
  20346. }
  20347. /** Returns the length of the line. */
  20348. ValueType getLength() const noexcept { return start.getDistanceFrom (end); }
  20349. /** Returns true if the line's start and end x co-ordinates are the same. */
  20350. bool isVertical() const noexcept { return start.getX() == end.getX(); }
  20351. /** Returns true if the line's start and end y co-ordinates are the same. */
  20352. bool isHorizontal() const noexcept { return start.getY() == end.getY(); }
  20353. /** Returns the line's angle.
  20354. This value is the number of radians clockwise from the 3 o'clock direction,
  20355. where the line's start point is considered to be at the centre.
  20356. */
  20357. ValueType getAngle() const noexcept { return start.getAngleToPoint (end); }
  20358. /** Compares two lines. */
  20359. bool operator== (const Line& other) const noexcept { return start == other.start && end == other.end; }
  20360. /** Compares two lines. */
  20361. bool operator!= (const Line& other) const noexcept { return start != other.start || end != other.end; }
  20362. /** Finds the intersection between two lines.
  20363. @param line the other line
  20364. @param intersection the position of the point where the lines meet (or
  20365. where they would meet if they were infinitely long)
  20366. the intersection (if the lines intersect). If the lines
  20367. are parallel, this will just be set to the position
  20368. of one of the line's endpoints.
  20369. @returns true if the line segments intersect; false if they dont. Even if they
  20370. don't intersect, the intersection co-ordinates returned will still
  20371. be valid
  20372. */
  20373. bool intersects (const Line& line, Point<ValueType>& intersection) const noexcept
  20374. {
  20375. return findIntersection (start, end, line.start, line.end, intersection);
  20376. }
  20377. /** Finds the intersection between two lines.
  20378. @param line the line to intersect with
  20379. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  20380. */
  20381. Point<ValueType> getIntersection (const Line& line) const noexcept
  20382. {
  20383. Point<ValueType> p;
  20384. findIntersection (start, end, line.start, line.end, p);
  20385. return p;
  20386. }
  20387. /** Returns the location of the point which is a given distance along this line.
  20388. @param distanceFromStart the distance to move along the line from its
  20389. start point. This value can be negative or longer
  20390. than the line itself
  20391. @see getPointAlongLineProportionally
  20392. */
  20393. Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const noexcept
  20394. {
  20395. return start + (end - start) * (distanceFromStart / getLength());
  20396. }
  20397. /** Returns a point which is a certain distance along and to the side of this line.
  20398. This effectively moves a given distance along the line, then another distance
  20399. perpendicularly to this, and returns the resulting position.
  20400. @param distanceFromStart the distance to move along the line from its
  20401. start point. This value can be negative or longer
  20402. than the line itself
  20403. @param perpendicularDistance how far to move sideways from the line. If you're
  20404. looking along the line from its start towards its
  20405. end, then a positive value here will move to the
  20406. right, negative value move to the left.
  20407. */
  20408. Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  20409. ValueType perpendicularDistance) const noexcept
  20410. {
  20411. const Point<ValueType> delta (end - start);
  20412. const double length = juce_hypot ((double) delta.getX(),
  20413. (double) delta.getY());
  20414. if (length <= 0)
  20415. return start;
  20416. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  20417. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  20418. }
  20419. /** Returns the location of the point which is a given distance along this line
  20420. proportional to the line's length.
  20421. @param proportionOfLength the distance to move along the line from its
  20422. start point, in multiples of the line's length.
  20423. So a value of 0.0 will return the line's start point
  20424. and a value of 1.0 will return its end point. (This value
  20425. can be negative or greater than 1.0).
  20426. @see getPointAlongLine
  20427. */
  20428. Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const noexcept
  20429. {
  20430. return start + (end - start) * proportionOfLength;
  20431. }
  20432. /** Returns the smallest distance between this line segment and a given point.
  20433. So if the point is close to the line, this will return the perpendicular
  20434. distance from the line; if the point is a long way beyond one of the line's
  20435. end-point's, it'll return the straight-line distance to the nearest end-point.
  20436. pointOnLine receives the position of the point that is found.
  20437. @returns the point's distance from the line
  20438. @see getPositionAlongLineOfNearestPoint
  20439. */
  20440. ValueType getDistanceFromPoint (const Point<ValueType>& targetPoint,
  20441. Point<ValueType>& pointOnLine) const noexcept
  20442. {
  20443. const Point<ValueType> delta (end - start);
  20444. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  20445. if (length > 0)
  20446. {
  20447. const double prop = ((targetPoint.getX() - start.getX()) * delta.getX()
  20448. + (targetPoint.getY() - start.getY()) * delta.getY()) / length;
  20449. if (prop >= 0 && prop <= 1.0)
  20450. {
  20451. pointOnLine = start + delta * (ValueType) prop;
  20452. return targetPoint.getDistanceFrom (pointOnLine);
  20453. }
  20454. }
  20455. const float fromStart = targetPoint.getDistanceFrom (start);
  20456. const float fromEnd = targetPoint.getDistanceFrom (end);
  20457. if (fromStart < fromEnd)
  20458. {
  20459. pointOnLine = start;
  20460. return fromStart;
  20461. }
  20462. else
  20463. {
  20464. pointOnLine = end;
  20465. return fromEnd;
  20466. }
  20467. }
  20468. /** Finds the point on this line which is nearest to a given point, and
  20469. returns its position as a proportional position along the line.
  20470. @returns a value 0 to 1.0 which is the distance along this line from the
  20471. line's start to the point which is nearest to the point passed-in. To
  20472. turn this number into a position, use getPointAlongLineProportionally().
  20473. @see getDistanceFromPoint, getPointAlongLineProportionally
  20474. */
  20475. ValueType findNearestProportionalPositionTo (const Point<ValueType>& point) const noexcept
  20476. {
  20477. const Point<ValueType> delta (end - start);
  20478. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  20479. return length <= 0 ? 0
  20480. : jlimit ((ValueType) 0, (ValueType) 1,
  20481. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  20482. + (point.getY() - start.getY()) * delta.getY()) / length));
  20483. }
  20484. /** Finds the point on this line which is nearest to a given point.
  20485. @see getDistanceFromPoint, findNearestProportionalPositionTo
  20486. */
  20487. Point<ValueType> findNearestPointTo (const Point<ValueType>& point) const noexcept
  20488. {
  20489. return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
  20490. }
  20491. /** Returns true if the given point lies above this line.
  20492. The return value is true if the point's y coordinate is less than the y
  20493. coordinate of this line at the given x (assuming the line extends infinitely
  20494. in both directions).
  20495. */
  20496. bool isPointAbove (const Point<ValueType>& point) const noexcept
  20497. {
  20498. return start.getX() != end.getX()
  20499. && point.getY() < ((end.getY() - start.getY())
  20500. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  20501. }
  20502. /** Returns a shortened copy of this line.
  20503. This will chop off part of the start of this line by a certain amount, (leaving the
  20504. end-point the same), and return the new line.
  20505. */
  20506. Line withShortenedStart (ValueType distanceToShortenBy) const noexcept
  20507. {
  20508. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  20509. }
  20510. /** Returns a shortened copy of this line.
  20511. This will chop off part of the end of this line by a certain amount, (leaving the
  20512. start-point the same), and return the new line.
  20513. */
  20514. Line withShortenedEnd (ValueType distanceToShortenBy) const noexcept
  20515. {
  20516. const ValueType length = getLength();
  20517. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  20518. }
  20519. private:
  20520. Point<ValueType> start, end;
  20521. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  20522. const Point<ValueType>& p3, const Point<ValueType>& p4,
  20523. Point<ValueType>& intersection) noexcept
  20524. {
  20525. if (p2 == p3)
  20526. {
  20527. intersection = p2;
  20528. return true;
  20529. }
  20530. const Point<ValueType> d1 (p2 - p1);
  20531. const Point<ValueType> d2 (p4 - p3);
  20532. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  20533. if (divisor == 0)
  20534. {
  20535. if (! (d1.isOrigin() || d2.isOrigin()))
  20536. {
  20537. if (d1.getY() == 0 && d2.getY() != 0)
  20538. {
  20539. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  20540. intersection = p1.withX (p3.getX() + along * d2.getX());
  20541. return along >= 0 && along <= (ValueType) 1;
  20542. }
  20543. else if (d2.getY() == 0 && d1.getY() != 0)
  20544. {
  20545. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  20546. intersection = p3.withX (p1.getX() + along * d1.getX());
  20547. return along >= 0 && along <= (ValueType) 1;
  20548. }
  20549. else if (d1.getX() == 0 && d2.getX() != 0)
  20550. {
  20551. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  20552. intersection = p1.withY (p3.getY() + along * d2.getY());
  20553. return along >= 0 && along <= (ValueType) 1;
  20554. }
  20555. else if (d2.getX() == 0 && d1.getX() != 0)
  20556. {
  20557. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  20558. intersection = p3.withY (p1.getY() + along * d1.getY());
  20559. return along >= 0 && along <= (ValueType) 1;
  20560. }
  20561. }
  20562. intersection = (p2 + p3) / (ValueType) 2;
  20563. return false;
  20564. }
  20565. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  20566. intersection = p1 + d1 * along1;
  20567. if (along1 < 0 || along1 > (ValueType) 1)
  20568. return false;
  20569. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  20570. return along2 >= 0 && along2 <= (ValueType) 1;
  20571. }
  20572. };
  20573. #endif // __JUCE_LINE_JUCEHEADER__
  20574. /*** End of inlined file: juce_Line.h ***/
  20575. /*** Start of inlined file: juce_Justification.h ***/
  20576. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  20577. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  20578. /**
  20579. Represents a type of justification to be used when positioning graphical items.
  20580. e.g. it indicates whether something should be placed top-left, top-right,
  20581. centred, etc.
  20582. It is used in various places wherever this kind of information is needed.
  20583. */
  20584. class JUCE_API Justification
  20585. {
  20586. public:
  20587. /** Creates a Justification object using a combination of flags. */
  20588. inline Justification (int flags_) noexcept : flags (flags_) {}
  20589. /** Creates a copy of another Justification object. */
  20590. Justification (const Justification& other) noexcept;
  20591. /** Copies another Justification object. */
  20592. Justification& operator= (const Justification& other) noexcept;
  20593. bool operator== (const Justification& other) const noexcept { return flags == other.flags; }
  20594. bool operator!= (const Justification& other) const noexcept { return flags != other.flags; }
  20595. /** Returns the raw flags that are set for this Justification object. */
  20596. inline int getFlags() const noexcept { return flags; }
  20597. /** Tests a set of flags for this object.
  20598. @returns true if any of the flags passed in are set on this object.
  20599. */
  20600. inline bool testFlags (int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  20601. /** Returns just the flags from this object that deal with vertical layout. */
  20602. int getOnlyVerticalFlags() const noexcept;
  20603. /** Returns just the flags from this object that deal with horizontal layout. */
  20604. int getOnlyHorizontalFlags() const noexcept;
  20605. /** Adjusts the position of a rectangle to fit it into a space.
  20606. The (x, y) position of the rectangle will be updated to position it inside the
  20607. given space according to the justification flags.
  20608. */
  20609. template <typename ValueType>
  20610. void applyToRectangle (ValueType& x, ValueType& y, ValueType w, ValueType h,
  20611. ValueType spaceX, ValueType spaceY, ValueType spaceW, ValueType spaceH) const noexcept
  20612. {
  20613. x = spaceX;
  20614. if ((flags & horizontallyCentred) != 0) x += (spaceW - w) / (ValueType) 2;
  20615. else if ((flags & right) != 0) x += spaceW - w;
  20616. y = spaceY;
  20617. if ((flags & verticallyCentred) != 0) y += (spaceH - h) / (ValueType) 2;
  20618. else if ((flags & bottom) != 0) y += spaceH - h;
  20619. }
  20620. /** Returns the new position of a rectangle that has been justified to fit within a given space.
  20621. */
  20622. template <typename ValueType>
  20623. const Rectangle<ValueType> appliedToRectangle (const Rectangle<ValueType>& areaToAdjust,
  20624. const Rectangle<ValueType>& targetSpace) const noexcept
  20625. {
  20626. ValueType x = areaToAdjust.getX(), y = areaToAdjust.getY();
  20627. applyToRectangle (x, y, areaToAdjust.getWidth(), areaToAdjust.getHeight(),
  20628. targetSpace.getX(), targetSpace.getY(), targetSpace.getWidth(), targetSpace.getHeight());
  20629. return areaToAdjust.withPosition (x, y);
  20630. }
  20631. /** Flag values that can be combined and used in the constructor. */
  20632. enum
  20633. {
  20634. /** Indicates that the item should be aligned against the left edge of the available space. */
  20635. left = 1,
  20636. /** Indicates that the item should be aligned against the right edge of the available space. */
  20637. right = 2,
  20638. /** Indicates that the item should be placed in the centre between the left and right
  20639. sides of the available space. */
  20640. horizontallyCentred = 4,
  20641. /** Indicates that the item should be aligned against the top edge of the available space. */
  20642. top = 8,
  20643. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  20644. bottom = 16,
  20645. /** Indicates that the item should be placed in the centre between the top and bottom
  20646. sides of the available space. */
  20647. verticallyCentred = 32,
  20648. /** Indicates that lines of text should be spread out to fill the maximum width
  20649. available, so that both margins are aligned vertically.
  20650. */
  20651. horizontallyJustified = 64,
  20652. /** Indicates that the item should be centred vertically and horizontally.
  20653. This is equivalent to (horizontallyCentred | verticallyCentred)
  20654. */
  20655. centred = 36,
  20656. /** Indicates that the item should be centred vertically but placed on the left hand side.
  20657. This is equivalent to (left | verticallyCentred)
  20658. */
  20659. centredLeft = 33,
  20660. /** Indicates that the item should be centred vertically but placed on the right hand side.
  20661. This is equivalent to (right | verticallyCentred)
  20662. */
  20663. centredRight = 34,
  20664. /** Indicates that the item should be centred horizontally and placed at the top.
  20665. This is equivalent to (horizontallyCentred | top)
  20666. */
  20667. centredTop = 12,
  20668. /** Indicates that the item should be centred horizontally and placed at the bottom.
  20669. This is equivalent to (horizontallyCentred | bottom)
  20670. */
  20671. centredBottom = 20,
  20672. /** Indicates that the item should be placed in the top-left corner.
  20673. This is equivalent to (left | top)
  20674. */
  20675. topLeft = 9,
  20676. /** Indicates that the item should be placed in the top-right corner.
  20677. This is equivalent to (right | top)
  20678. */
  20679. topRight = 10,
  20680. /** Indicates that the item should be placed in the bottom-left corner.
  20681. This is equivalent to (left | bottom)
  20682. */
  20683. bottomLeft = 17,
  20684. /** Indicates that the item should be placed in the bottom-left corner.
  20685. This is equivalent to (right | bottom)
  20686. */
  20687. bottomRight = 18
  20688. };
  20689. private:
  20690. int flags;
  20691. };
  20692. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  20693. /*** End of inlined file: juce_Justification.h ***/
  20694. class Image;
  20695. class InputStream;
  20696. class OutputStream;
  20697. /**
  20698. A path is a sequence of lines and curves that may either form a closed shape
  20699. or be open-ended.
  20700. To use a path, you can create an empty one, then add lines and curves to it
  20701. to create shapes, then it can be rendered by a Graphics context or used
  20702. for geometric operations.
  20703. e.g. @code
  20704. Path myPath;
  20705. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  20706. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  20707. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  20708. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  20709. // add an ellipse as well, which will form a second sub-path within the path..
  20710. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  20711. // double the width of the whole thing..
  20712. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  20713. // and draw it to a graphics context with a 5-pixel thick outline.
  20714. g.strokePath (myPath, PathStrokeType (5.0f));
  20715. @endcode
  20716. A path object can actually contain multiple sub-paths, which may themselves
  20717. be open or closed.
  20718. @see PathFlatteningIterator, PathStrokeType, Graphics
  20719. */
  20720. class JUCE_API Path
  20721. {
  20722. public:
  20723. /** Creates an empty path. */
  20724. Path();
  20725. /** Creates a copy of another path. */
  20726. Path (const Path& other);
  20727. /** Destructor. */
  20728. ~Path();
  20729. /** Copies this path from another one. */
  20730. Path& operator= (const Path& other);
  20731. bool operator== (const Path& other) const noexcept;
  20732. bool operator!= (const Path& other) const noexcept;
  20733. /** Returns true if the path doesn't contain any lines or curves. */
  20734. bool isEmpty() const noexcept;
  20735. /** Returns the smallest rectangle that contains all points within the path.
  20736. */
  20737. Rectangle<float> getBounds() const noexcept;
  20738. /** Returns the smallest rectangle that contains all points within the path
  20739. after it's been transformed with the given tranasform matrix.
  20740. */
  20741. Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const noexcept;
  20742. /** Checks whether a point lies within the path.
  20743. This is only relevent for closed paths (see closeSubPath()), and
  20744. may produce false results if used on a path which has open sub-paths.
  20745. The path's winding rule is taken into account by this method.
  20746. The tolerance parameter is the maximum error allowed when flattening the path,
  20747. so this method could return a false positive when your point is up to this distance
  20748. outside the path's boundary.
  20749. @see closeSubPath, setUsingNonZeroWinding
  20750. */
  20751. bool contains (float x, float y,
  20752. float tolerance = 1.0f) const;
  20753. /** Checks whether a point lies within the path.
  20754. This is only relevent for closed paths (see closeSubPath()), and
  20755. may produce false results if used on a path which has open sub-paths.
  20756. The path's winding rule is taken into account by this method.
  20757. The tolerance parameter is the maximum error allowed when flattening the path,
  20758. so this method could return a false positive when your point is up to this distance
  20759. outside the path's boundary.
  20760. @see closeSubPath, setUsingNonZeroWinding
  20761. */
  20762. bool contains (const Point<float>& point,
  20763. float tolerance = 1.0f) const;
  20764. /** Checks whether a line crosses the path.
  20765. This will return positive if the line crosses any of the paths constituent
  20766. lines or curves. It doesn't take into account whether the line is inside
  20767. or outside the path, or whether the path is open or closed.
  20768. The tolerance parameter is the maximum error allowed when flattening the path,
  20769. so this method could return a false positive when your point is up to this distance
  20770. outside the path's boundary.
  20771. */
  20772. bool intersectsLine (const Line<float>& line,
  20773. float tolerance = 1.0f);
  20774. /** Cuts off parts of a line to keep the parts that are either inside or
  20775. outside this path.
  20776. Note that this isn't smart enough to cope with situations where the
  20777. line would need to be cut into multiple pieces to correctly clip against
  20778. a re-entrant shape.
  20779. @param line the line to clip
  20780. @param keepSectionOutsidePath if true, it's the section outside the path
  20781. that will be kept; if false its the section inside
  20782. the path
  20783. */
  20784. Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  20785. /** Returns the length of the path.
  20786. @see getPointAlongPath
  20787. */
  20788. float getLength (const AffineTransform& transform = AffineTransform::identity) const;
  20789. /** Returns a point that is the specified distance along the path.
  20790. If the distance is greater than the total length of the path, this will return the
  20791. end point.
  20792. @see getLength
  20793. */
  20794. Point<float> getPointAlongPath (float distanceFromStart,
  20795. const AffineTransform& transform = AffineTransform::identity) const;
  20796. /** Finds the point along the path which is nearest to a given position.
  20797. This sets pointOnPath to the nearest point, and returns the distance of this point from the start
  20798. of the path.
  20799. */
  20800. float getNearestPoint (const Point<float>& targetPoint,
  20801. Point<float>& pointOnPath,
  20802. const AffineTransform& transform = AffineTransform::identity) const;
  20803. /** Removes all lines and curves, resetting the path completely. */
  20804. void clear() noexcept;
  20805. /** Begins a new subpath with a given starting position.
  20806. This will move the path's current position to the co-ordinates passed in and
  20807. make it ready to draw lines or curves starting from this position.
  20808. After adding whatever lines and curves are needed, you can either
  20809. close the current sub-path using closeSubPath() or call startNewSubPath()
  20810. to move to a new sub-path, leaving the old one open-ended.
  20811. @see lineTo, quadraticTo, cubicTo, closeSubPath
  20812. */
  20813. void startNewSubPath (float startX, float startY);
  20814. /** Begins a new subpath with a given starting position.
  20815. This will move the path's current position to the co-ordinates passed in and
  20816. make it ready to draw lines or curves starting from this position.
  20817. After adding whatever lines and curves are needed, you can either
  20818. close the current sub-path using closeSubPath() or call startNewSubPath()
  20819. to move to a new sub-path, leaving the old one open-ended.
  20820. @see lineTo, quadraticTo, cubicTo, closeSubPath
  20821. */
  20822. void startNewSubPath (const Point<float>& start);
  20823. /** Closes a the current sub-path with a line back to its start-point.
  20824. When creating a closed shape such as a triangle, don't use 3 lineTo()
  20825. calls - instead use two lineTo() calls, followed by a closeSubPath()
  20826. to join the final point back to the start.
  20827. This ensures that closes shapes are recognised as such, and this is
  20828. important for tasks like drawing strokes, which needs to know whether to
  20829. draw end-caps or not.
  20830. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  20831. */
  20832. void closeSubPath();
  20833. /** Adds a line from the shape's last position to a new end-point.
  20834. This will connect the end-point of the last line or curve that was added
  20835. to a new point, using a straight line.
  20836. See the class description for an example of how to add lines and curves to a path.
  20837. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  20838. */
  20839. void lineTo (float endX, float endY);
  20840. /** Adds a line from the shape's last position to a new end-point.
  20841. This will connect the end-point of the last line or curve that was added
  20842. to a new point, using a straight line.
  20843. See the class description for an example of how to add lines and curves to a path.
  20844. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  20845. */
  20846. void lineTo (const Point<float>& end);
  20847. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  20848. This will connect the end-point of the last line or curve that was added
  20849. to a new point, using a quadratic spline with one control-point.
  20850. See the class description for an example of how to add lines and curves to a path.
  20851. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  20852. */
  20853. void quadraticTo (float controlPointX,
  20854. float controlPointY,
  20855. float endPointX,
  20856. float endPointY);
  20857. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  20858. This will connect the end-point of the last line or curve that was added
  20859. to a new point, using a quadratic spline with one control-point.
  20860. See the class description for an example of how to add lines and curves to a path.
  20861. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  20862. */
  20863. void quadraticTo (const Point<float>& controlPoint,
  20864. const Point<float>& endPoint);
  20865. /** Adds a cubic bezier curve from the shape's last position to a new position.
  20866. This will connect the end-point of the last line or curve that was added
  20867. to a new point, using a cubic spline with two control-points.
  20868. See the class description for an example of how to add lines and curves to a path.
  20869. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  20870. */
  20871. void cubicTo (float controlPoint1X,
  20872. float controlPoint1Y,
  20873. float controlPoint2X,
  20874. float controlPoint2Y,
  20875. float endPointX,
  20876. float endPointY);
  20877. /** Adds a cubic bezier curve from the shape's last position to a new position.
  20878. This will connect the end-point of the last line or curve that was added
  20879. to a new point, using a cubic spline with two control-points.
  20880. See the class description for an example of how to add lines and curves to a path.
  20881. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  20882. */
  20883. void cubicTo (const Point<float>& controlPoint1,
  20884. const Point<float>& controlPoint2,
  20885. const Point<float>& endPoint);
  20886. /** Returns the last point that was added to the path by one of the drawing methods.
  20887. */
  20888. Point<float> getCurrentPosition() const;
  20889. /** Adds a rectangle to the path.
  20890. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20891. @see addRoundedRectangle, addTriangle
  20892. */
  20893. void addRectangle (float x, float y, float width, float height);
  20894. /** Adds a rectangle to the path.
  20895. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20896. @see addRoundedRectangle, addTriangle
  20897. */
  20898. template <typename ValueType>
  20899. void addRectangle (const Rectangle<ValueType>& rectangle)
  20900. {
  20901. addRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  20902. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()));
  20903. }
  20904. /** Adds a rectangle with rounded corners to the path.
  20905. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20906. @see addRectangle, addTriangle
  20907. */
  20908. void addRoundedRectangle (float x, float y, float width, float height,
  20909. float cornerSize);
  20910. /** Adds a rectangle with rounded corners to the path.
  20911. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20912. @see addRectangle, addTriangle
  20913. */
  20914. void addRoundedRectangle (float x, float y, float width, float height,
  20915. float cornerSizeX,
  20916. float cornerSizeY);
  20917. /** Adds a rectangle with rounded corners to the path.
  20918. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20919. @see addRectangle, addTriangle
  20920. */
  20921. template <typename ValueType>
  20922. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSizeX, float cornerSizeY)
  20923. {
  20924. addRoundedRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  20925. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()),
  20926. cornerSizeX, cornerSizeY);
  20927. }
  20928. /** Adds a rectangle with rounded corners to the path.
  20929. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20930. @see addRectangle, addTriangle
  20931. */
  20932. template <typename ValueType>
  20933. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSize)
  20934. {
  20935. addRoundedRectangle (rectangle, cornerSize, cornerSize);
  20936. }
  20937. /** Adds a triangle to the path.
  20938. The triangle is added as a new closed sub-path. (Any currently open paths will be left open).
  20939. Note that whether the vertices are specified in clockwise or anticlockwise
  20940. order will affect how the triangle is filled when it overlaps other
  20941. shapes (the winding order setting will affect this of course).
  20942. */
  20943. void addTriangle (float x1, float y1,
  20944. float x2, float y2,
  20945. float x3, float y3);
  20946. /** Adds a quadrilateral to the path.
  20947. The quad is added as a new closed sub-path. (Any currently open paths will be left open).
  20948. Note that whether the vertices are specified in clockwise or anticlockwise
  20949. order will affect how the quad is filled when it overlaps other
  20950. shapes (the winding order setting will affect this of course).
  20951. */
  20952. void addQuadrilateral (float x1, float y1,
  20953. float x2, float y2,
  20954. float x3, float y3,
  20955. float x4, float y4);
  20956. /** Adds an ellipse to the path.
  20957. The shape is added as a new sub-path. (Any currently open paths will be left open).
  20958. @see addArc
  20959. */
  20960. void addEllipse (float x, float y, float width, float height);
  20961. /** Adds an elliptical arc to the current path.
  20962. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20963. or anti-clockwise according to whether the end angle is greater than the start. This means
  20964. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20965. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  20966. @param y the top edge of the rectangle in which the elliptical outline fits
  20967. @param width the width of the rectangle in which the elliptical outline fits
  20968. @param height the height of the rectangle in which the elliptical outline fits
  20969. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20970. top-centre of the ellipse)
  20971. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20972. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  20973. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  20974. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  20975. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  20976. it will be added to the current sub-path, continuing from the current postition
  20977. @see addCentredArc, arcTo, addPieSegment, addEllipse
  20978. */
  20979. void addArc (float x, float y, float width, float height,
  20980. float fromRadians,
  20981. float toRadians,
  20982. bool startAsNewSubPath = false);
  20983. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  20984. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20985. or anti-clockwise according to whether the end angle is greater than the start. This means
  20986. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20987. @param centreX the centre x of the ellipse
  20988. @param centreY the centre y of the ellipse
  20989. @param radiusX the horizontal radius of the ellipse
  20990. @param radiusY the vertical radius of the ellipse
  20991. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  20992. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20993. top-centre of the ellipse)
  20994. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20995. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  20996. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  20997. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  20998. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  20999. it will be added to the current sub-path, continuing from the current postition
  21000. @see addArc, arcTo
  21001. */
  21002. void addCentredArc (float centreX, float centreY,
  21003. float radiusX, float radiusY,
  21004. float rotationOfEllipse,
  21005. float fromRadians,
  21006. float toRadians,
  21007. bool startAsNewSubPath = false);
  21008. /** Adds a "pie-chart" shape to the path.
  21009. The shape is added as a new sub-path. (Any currently open paths will be
  21010. left open).
  21011. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  21012. or anti-clockwise according to whether the end angle is greater than the start. This means
  21013. that sometimes you may need to use values greater than 2*Pi for the end angle.
  21014. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  21015. @param y the top edge of the rectangle in which the elliptical outline fits
  21016. @param width the width of the rectangle in which the elliptical outline fits
  21017. @param height the height of the rectangle in which the elliptical outline fits
  21018. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  21019. top-centre of the ellipse)
  21020. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  21021. top-centre of the ellipse)
  21022. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  21023. ellipse at its centre, where this value indicates the inner ellipse's size with
  21024. respect to the outer one.
  21025. @see addArc
  21026. */
  21027. void addPieSegment (float x, float y,
  21028. float width, float height,
  21029. float fromRadians,
  21030. float toRadians,
  21031. float innerCircleProportionalSize);
  21032. /** Adds a line with a specified thickness.
  21033. The line is added as a new closed sub-path. (Any currently open paths will be
  21034. left open).
  21035. @see addArrow
  21036. */
  21037. void addLineSegment (const Line<float>& line, float lineThickness);
  21038. /** Adds a line with an arrowhead on the end.
  21039. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  21040. @see PathStrokeType::createStrokeWithArrowheads
  21041. */
  21042. void addArrow (const Line<float>& line,
  21043. float lineThickness,
  21044. float arrowheadWidth,
  21045. float arrowheadLength);
  21046. /** Adds a polygon shape to the path.
  21047. @see addStar
  21048. */
  21049. void addPolygon (const Point<float>& centre,
  21050. int numberOfSides,
  21051. float radius,
  21052. float startAngle = 0.0f);
  21053. /** Adds a star shape to the path.
  21054. @see addPolygon
  21055. */
  21056. void addStar (const Point<float>& centre,
  21057. int numberOfPoints,
  21058. float innerRadius,
  21059. float outerRadius,
  21060. float startAngle = 0.0f);
  21061. /** Adds a speech-bubble shape to the path.
  21062. @param bodyX the left of the main body area of the bubble
  21063. @param bodyY the top of the main body area of the bubble
  21064. @param bodyW the width of the main body area of the bubble
  21065. @param bodyH the height of the main body area of the bubble
  21066. @param cornerSize the amount by which to round off the corners of the main body rectangle
  21067. @param arrowTipX the x position that the tip of the arrow should connect to
  21068. @param arrowTipY the y position that the tip of the arrow should connect to
  21069. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  21070. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  21071. arrow's base should be - this is a proportional distance between 0 and 1.0
  21072. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  21073. */
  21074. void addBubble (float bodyX, float bodyY,
  21075. float bodyW, float bodyH,
  21076. float cornerSize,
  21077. float arrowTipX,
  21078. float arrowTipY,
  21079. int whichSide,
  21080. float arrowPositionAlongEdgeProportional,
  21081. float arrowWidth);
  21082. /** Adds another path to this one.
  21083. The new path is added as a new sub-path. (Any currently open paths in this
  21084. path will be left open).
  21085. @param pathToAppend the path to add
  21086. */
  21087. void addPath (const Path& pathToAppend);
  21088. /** Adds another path to this one, transforming it on the way in.
  21089. The new path is added as a new sub-path, its points being transformed by the given
  21090. matrix before being added.
  21091. @param pathToAppend the path to add
  21092. @param transformToApply an optional transform to apply to the incoming vertices
  21093. */
  21094. void addPath (const Path& pathToAppend,
  21095. const AffineTransform& transformToApply);
  21096. /** Swaps the contents of this path with another one.
  21097. The internal data of the two paths is swapped over, so this is much faster than
  21098. copying it to a temp variable and back.
  21099. */
  21100. void swapWithPath (Path& other) noexcept;
  21101. /** Applies a 2D transform to all the vertices in the path.
  21102. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  21103. */
  21104. void applyTransform (const AffineTransform& transform) noexcept;
  21105. /** Rescales this path to make it fit neatly into a given space.
  21106. This is effectively a quick way of calling
  21107. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  21108. @param x the x position of the rectangle to fit the path inside
  21109. @param y the y position of the rectangle to fit the path inside
  21110. @param width the width of the rectangle to fit the path inside
  21111. @param height the height of the rectangle to fit the path inside
  21112. @param preserveProportions if true, it will fit the path into the space without altering its
  21113. horizontal/vertical scale ratio; if false, it will distort the
  21114. path to fill the specified ratio both horizontally and vertically
  21115. @see applyTransform, getTransformToScaleToFit
  21116. */
  21117. void scaleToFit (float x, float y, float width, float height,
  21118. bool preserveProportions) noexcept;
  21119. /** Returns a transform that can be used to rescale the path to fit into a given space.
  21120. @param x the x position of the rectangle to fit the path inside
  21121. @param y the y position of the rectangle to fit the path inside
  21122. @param width the width of the rectangle to fit the path inside
  21123. @param height the height of the rectangle to fit the path inside
  21124. @param preserveProportions if true, it will fit the path into the space without altering its
  21125. horizontal/vertical scale ratio; if false, it will distort the
  21126. path to fill the specified ratio both horizontally and vertically
  21127. @param justificationType if the proportions are preseved, the resultant path may be smaller
  21128. than the available rectangle, so this describes how it should be
  21129. positioned within the space.
  21130. @returns an appropriate transformation
  21131. @see applyTransform, scaleToFit
  21132. */
  21133. AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  21134. bool preserveProportions,
  21135. const Justification& justificationType = Justification::centred) const;
  21136. /** Creates a version of this path where all sharp corners have been replaced by curves.
  21137. Wherever two lines meet at an angle, this will replace the corner with a curve
  21138. of the given radius.
  21139. */
  21140. Path createPathWithRoundedCorners (float cornerRadius) const;
  21141. /** Changes the winding-rule to be used when filling the path.
  21142. If set to true (which is the default), then the path uses a non-zero-winding rule
  21143. to determine which points are inside the path. If set to false, it uses an
  21144. alternate-winding rule.
  21145. The winding-rule comes into play when areas of the shape overlap other
  21146. areas, and determines whether the overlapping regions are considered to be
  21147. inside or outside.
  21148. Changing this value just sets a flag - it doesn't affect the contents of the
  21149. path.
  21150. @see isUsingNonZeroWinding
  21151. */
  21152. void setUsingNonZeroWinding (bool isNonZeroWinding) noexcept;
  21153. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  21154. The default for a new path is true.
  21155. @see setUsingNonZeroWinding
  21156. */
  21157. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  21158. /** Iterates the lines and curves that a path contains.
  21159. @see Path, PathFlatteningIterator
  21160. */
  21161. class JUCE_API Iterator
  21162. {
  21163. public:
  21164. Iterator (const Path& path);
  21165. ~Iterator();
  21166. /** Moves onto the next element in the path.
  21167. If this returns false, there are no more elements. If it returns true,
  21168. the elementType variable will be set to the type of the current element,
  21169. and some of the x and y variables will be filled in with values.
  21170. */
  21171. bool next();
  21172. enum PathElementType
  21173. {
  21174. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  21175. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  21176. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  21177. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  21178. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  21179. };
  21180. PathElementType elementType;
  21181. float x1, y1, x2, y2, x3, y3;
  21182. private:
  21183. const Path& path;
  21184. size_t index;
  21185. JUCE_DECLARE_NON_COPYABLE (Iterator);
  21186. };
  21187. /** Loads a stored path from a data stream.
  21188. The data in the stream must have been written using writePathToStream().
  21189. Note that this will append the stored path to whatever is currently in
  21190. this path, so you might need to call clear() beforehand.
  21191. @see loadPathFromData, writePathToStream
  21192. */
  21193. void loadPathFromStream (InputStream& source);
  21194. /** Loads a stored path from a block of data.
  21195. This is similar to loadPathFromStream(), but just reads from a block
  21196. of data. Useful if you're including stored shapes in your code as a
  21197. block of static data.
  21198. @see loadPathFromStream, writePathToStream
  21199. */
  21200. void loadPathFromData (const void* data, int numberOfBytes);
  21201. /** Stores the path by writing it out to a stream.
  21202. After writing out a path, you can reload it using loadPathFromStream().
  21203. @see loadPathFromStream, loadPathFromData
  21204. */
  21205. void writePathToStream (OutputStream& destination) const;
  21206. /** Creates a string containing a textual representation of this path.
  21207. @see restoreFromString
  21208. */
  21209. String toString() const;
  21210. /** Restores this path from a string that was created with the toString() method.
  21211. @see toString()
  21212. */
  21213. void restoreFromString (const String& stringVersion);
  21214. private:
  21215. friend class PathFlatteningIterator;
  21216. friend class Path::Iterator;
  21217. ArrayAllocationBase <float, DummyCriticalSection> data;
  21218. size_t numElements;
  21219. float pathXMin, pathXMax, pathYMin, pathYMax;
  21220. bool useNonZeroWinding;
  21221. static const float lineMarker;
  21222. static const float moveMarker;
  21223. static const float quadMarker;
  21224. static const float cubicMarker;
  21225. static const float closeSubPathMarker;
  21226. JUCE_LEAK_DETECTOR (Path);
  21227. };
  21228. #endif // __JUCE_PATH_JUCEHEADER__
  21229. /*** End of inlined file: juce_Path.h ***/
  21230. /**
  21231. Describes a type of stroke used to render a solid outline along a path.
  21232. A PathStrokeType object can be used directly to create the shape of an outline
  21233. around a path, and is used by Graphics::strokePath to specify the type of
  21234. stroke to draw.
  21235. @see Path, Graphics::strokePath
  21236. */
  21237. class JUCE_API PathStrokeType
  21238. {
  21239. public:
  21240. /** The type of shape to use for the corners between two adjacent line segments. */
  21241. enum JointStyle
  21242. {
  21243. mitered, /**< Indicates that corners should be drawn with sharp joints.
  21244. Note that for angles that curve back on themselves, drawing a
  21245. mitre could require extending the point too far away from the
  21246. path, so a mitre limit is imposed and any corners that exceed it
  21247. are drawn as bevelled instead. */
  21248. curved, /**< Indicates that corners should be drawn as rounded-off. */
  21249. beveled /**< Indicates that corners should be drawn with a line flattening their
  21250. outside edge. */
  21251. };
  21252. /** The type shape to use for the ends of lines. */
  21253. enum EndCapStyle
  21254. {
  21255. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  21256. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  21257. the thickness of the stroke. */
  21258. rounded /**< Ends of lines are rounded-off with a circular shape. */
  21259. };
  21260. /** Creates a stroke type.
  21261. @param strokeThickness the width of the line to use
  21262. @param jointStyle the type of joints to use for corners
  21263. @param endStyle the type of end-caps to use for the ends of open paths.
  21264. */
  21265. PathStrokeType (float strokeThickness,
  21266. JointStyle jointStyle = mitered,
  21267. EndCapStyle endStyle = butt) noexcept;
  21268. /** Createes a copy of another stroke type. */
  21269. PathStrokeType (const PathStrokeType& other) noexcept;
  21270. /** Copies another stroke onto this one. */
  21271. PathStrokeType& operator= (const PathStrokeType& other) noexcept;
  21272. /** Destructor. */
  21273. ~PathStrokeType() noexcept;
  21274. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  21275. @param destPath the resultant stroked outline shape will be copied into this path.
  21276. Note that it's ok for the source and destination Paths to be
  21277. the same object, so you can easily turn a path into a stroked version
  21278. of itself.
  21279. @param sourcePath the path to use as the source
  21280. @param transform an optional transform to apply to the points from the source path
  21281. as they are being used
  21282. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21283. a higher resolution, which improves the quality if you'll later want
  21284. to enlarge the stroked path. So for example, if you're planning on drawing
  21285. the stroke at 3x the size that you're creating it, you should set this to 3.
  21286. @see createDashedStroke
  21287. */
  21288. void createStrokedPath (Path& destPath,
  21289. const Path& sourcePath,
  21290. const AffineTransform& transform = AffineTransform::identity,
  21291. float extraAccuracy = 1.0f) const;
  21292. /** Applies this stroke type to a path, creating a dashed line.
  21293. This is similar to createStrokedPath, but uses the array passed in to
  21294. break the stroke up into a series of dashes.
  21295. @param destPath the resultant stroked outline shape will be copied into this path.
  21296. Note that it's ok for the source and destination Paths to be
  21297. the same object, so you can easily turn a path into a stroked version
  21298. of itself.
  21299. @param sourcePath the path to use as the source
  21300. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  21301. a line of length 2, then skip a length of 3, then add a line of length 4,
  21302. skip 5, and keep repeating this pattern.
  21303. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  21304. an even number, otherwise the pattern will get out of step as it
  21305. repeats.
  21306. @param transform an optional transform to apply to the points from the source path
  21307. as they are being used
  21308. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21309. a higher resolution, which improves the quality if you'll later want
  21310. to enlarge the stroked path. So for example, if you're planning on drawing
  21311. the stroke at 3x the size that you're creating it, you should set this to 3.
  21312. */
  21313. void createDashedStroke (Path& destPath,
  21314. const Path& sourcePath,
  21315. const float* dashLengths,
  21316. int numDashLengths,
  21317. const AffineTransform& transform = AffineTransform::identity,
  21318. float extraAccuracy = 1.0f) const;
  21319. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  21320. @param destPath the resultant stroked outline shape will be copied into this path.
  21321. Note that it's ok for the source and destination Paths to be
  21322. the same object, so you can easily turn a path into a stroked version
  21323. of itself.
  21324. @param sourcePath the path to use as the source
  21325. @param arrowheadStartWidth the width of the arrowhead at the start of the path
  21326. @param arrowheadStartLength the length of the arrowhead at the start of the path
  21327. @param arrowheadEndWidth the width of the arrowhead at the end of the path
  21328. @param arrowheadEndLength the length of the arrowhead at the end of the path
  21329. @param transform an optional transform to apply to the points from the source path
  21330. as they are being used
  21331. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  21332. a higher resolution, which improves the quality if you'll later want
  21333. to enlarge the stroked path. So for example, if you're planning on drawing
  21334. the stroke at 3x the size that you're creating it, you should set this to 3.
  21335. @see createDashedStroke
  21336. */
  21337. void createStrokeWithArrowheads (Path& destPath,
  21338. const Path& sourcePath,
  21339. float arrowheadStartWidth, float arrowheadStartLength,
  21340. float arrowheadEndWidth, float arrowheadEndLength,
  21341. const AffineTransform& transform = AffineTransform::identity,
  21342. float extraAccuracy = 1.0f) const;
  21343. /** Returns the stroke thickness. */
  21344. float getStrokeThickness() const noexcept { return thickness; }
  21345. /** Sets the stroke thickness. */
  21346. void setStrokeThickness (float newThickness) noexcept { thickness = newThickness; }
  21347. /** Returns the joint style. */
  21348. JointStyle getJointStyle() const noexcept { return jointStyle; }
  21349. /** Sets the joint style. */
  21350. void setJointStyle (JointStyle newStyle) noexcept { jointStyle = newStyle; }
  21351. /** Returns the end-cap style. */
  21352. EndCapStyle getEndStyle() const noexcept { return endStyle; }
  21353. /** Sets the end-cap style. */
  21354. void setEndStyle (EndCapStyle newStyle) noexcept { endStyle = newStyle; }
  21355. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  21356. bool operator== (const PathStrokeType& other) const noexcept;
  21357. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  21358. bool operator!= (const PathStrokeType& other) const noexcept;
  21359. private:
  21360. float thickness;
  21361. JointStyle jointStyle;
  21362. EndCapStyle endStyle;
  21363. JUCE_LEAK_DETECTOR (PathStrokeType);
  21364. };
  21365. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  21366. /*** End of inlined file: juce_PathStrokeType.h ***/
  21367. /*** Start of inlined file: juce_Colours.h ***/
  21368. #ifndef __JUCE_COLOURS_JUCEHEADER__
  21369. #define __JUCE_COLOURS_JUCEHEADER__
  21370. /*** Start of inlined file: juce_Colour.h ***/
  21371. #ifndef __JUCE_COLOUR_JUCEHEADER__
  21372. #define __JUCE_COLOUR_JUCEHEADER__
  21373. /*** Start of inlined file: juce_PixelFormats.h ***/
  21374. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  21375. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  21376. #ifndef DOXYGEN
  21377. #if JUCE_MSVC
  21378. #pragma pack (push, 1)
  21379. #define PACKED
  21380. #elif JUCE_GCC
  21381. #define PACKED __attribute__((packed))
  21382. #else
  21383. #define PACKED
  21384. #endif
  21385. #endif
  21386. class PixelRGB;
  21387. class PixelAlpha;
  21388. /**
  21389. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  21390. operations with it.
  21391. This is used internally by the imaging classes.
  21392. @see PixelRGB
  21393. */
  21394. class JUCE_API PixelARGB
  21395. {
  21396. public:
  21397. /** Creates a pixel without defining its colour. */
  21398. PixelARGB() noexcept {}
  21399. ~PixelARGB() noexcept {}
  21400. /** Creates a pixel from a 32-bit argb value.
  21401. */
  21402. PixelARGB (const uint32 argb_) noexcept
  21403. : argb (argb_)
  21404. {
  21405. }
  21406. forcedinline uint32 getARGB() const noexcept { return argb; }
  21407. forcedinline uint32 getUnpremultipliedARGB() const noexcept { PixelARGB p (argb); p.unpremultiply(); return p.getARGB(); }
  21408. forcedinline uint32 getRB() const noexcept { return 0x00ff00ff & argb; }
  21409. forcedinline uint32 getAG() const noexcept { return 0x00ff00ff & (argb >> 8); }
  21410. forcedinline uint8 getAlpha() const noexcept { return components.a; }
  21411. forcedinline uint8 getRed() const noexcept { return components.r; }
  21412. forcedinline uint8 getGreen() const noexcept { return components.g; }
  21413. forcedinline uint8 getBlue() const noexcept { return components.b; }
  21414. /** Blends another pixel onto this one.
  21415. This takes into account the opacity of the pixel being overlaid, and blends
  21416. it accordingly.
  21417. */
  21418. forcedinline void blend (const PixelARGB& src) noexcept
  21419. {
  21420. uint32 sargb = src.getARGB();
  21421. const uint32 alpha = 0x100 - (sargb >> 24);
  21422. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21423. sargb += 0xff00ff00 & (getAG() * alpha);
  21424. argb = sargb;
  21425. }
  21426. /** Blends another pixel onto this one.
  21427. This takes into account the opacity of the pixel being overlaid, and blends
  21428. it accordingly.
  21429. */
  21430. forcedinline void blend (const PixelAlpha& src) noexcept;
  21431. /** Blends another pixel onto this one.
  21432. This takes into account the opacity of the pixel being overlaid, and blends
  21433. it accordingly.
  21434. */
  21435. forcedinline void blend (const PixelRGB& src) noexcept;
  21436. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21437. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21438. being used, so this can blend semi-transparently from a PixelRGB argument.
  21439. */
  21440. template <class Pixel>
  21441. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21442. {
  21443. ++extraAlpha;
  21444. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  21445. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  21446. const uint32 alpha = 0x100 - (sargb >> 24);
  21447. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21448. sargb += 0xff00ff00 & (getAG() * alpha);
  21449. argb = sargb;
  21450. }
  21451. /** Blends another pixel with this one, creating a colour that is somewhere
  21452. between the two, as specified by the amount.
  21453. */
  21454. template <class Pixel>
  21455. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21456. {
  21457. uint32 drb = getRB();
  21458. drb += (((src.getRB() - drb) * amount) >> 8);
  21459. drb &= 0x00ff00ff;
  21460. uint32 dag = getAG();
  21461. dag += (((src.getAG() - dag) * amount) >> 8);
  21462. dag &= 0x00ff00ff;
  21463. dag <<= 8;
  21464. dag |= drb;
  21465. argb = dag;
  21466. }
  21467. /** Copies another pixel colour over this one.
  21468. This doesn't blend it - this colour is simply replaced by the other one.
  21469. */
  21470. template <class Pixel>
  21471. forcedinline void set (const Pixel& src) noexcept
  21472. {
  21473. argb = src.getARGB();
  21474. }
  21475. /** Replaces the colour's alpha value with another one. */
  21476. forcedinline void setAlpha (const uint8 newAlpha) noexcept
  21477. {
  21478. components.a = newAlpha;
  21479. }
  21480. /** Multiplies the colour's alpha value with another one. */
  21481. forcedinline void multiplyAlpha (int multiplier) noexcept
  21482. {
  21483. ++multiplier;
  21484. argb = ((multiplier * getAG()) & 0xff00ff00)
  21485. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  21486. }
  21487. forcedinline void multiplyAlpha (const float multiplier) noexcept
  21488. {
  21489. multiplyAlpha ((int) (multiplier * 256.0f));
  21490. }
  21491. /** Sets the pixel's colour from individual components. */
  21492. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) noexcept
  21493. {
  21494. components.b = b;
  21495. components.g = g;
  21496. components.r = r;
  21497. components.a = a;
  21498. }
  21499. /** Premultiplies the pixel's RGB values by its alpha. */
  21500. forcedinline void premultiply() noexcept
  21501. {
  21502. const uint32 alpha = components.a;
  21503. if (alpha < 0xff)
  21504. {
  21505. if (alpha == 0)
  21506. {
  21507. components.b = 0;
  21508. components.g = 0;
  21509. components.r = 0;
  21510. }
  21511. else
  21512. {
  21513. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  21514. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  21515. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  21516. }
  21517. }
  21518. }
  21519. /** Unpremultiplies the pixel's RGB values. */
  21520. forcedinline void unpremultiply() noexcept
  21521. {
  21522. const uint32 alpha = components.a;
  21523. if (alpha < 0xff)
  21524. {
  21525. if (alpha == 0)
  21526. {
  21527. components.b = 0;
  21528. components.g = 0;
  21529. components.r = 0;
  21530. }
  21531. else
  21532. {
  21533. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  21534. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  21535. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  21536. }
  21537. }
  21538. }
  21539. forcedinline void desaturate() noexcept
  21540. {
  21541. if (components.a < 0xff && components.a > 0)
  21542. {
  21543. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  21544. components.r = components.g = components.b
  21545. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  21546. }
  21547. else
  21548. {
  21549. components.r = components.g = components.b
  21550. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  21551. }
  21552. }
  21553. /** The indexes of the different components in the byte layout of this type of colour. */
  21554. #if JUCE_BIG_ENDIAN
  21555. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  21556. #else
  21557. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  21558. #endif
  21559. private:
  21560. union
  21561. {
  21562. uint32 argb;
  21563. struct
  21564. {
  21565. #if JUCE_BIG_ENDIAN
  21566. uint8 a : 8, r : 8, g : 8, b : 8;
  21567. #else
  21568. uint8 b, g, r, a;
  21569. #endif
  21570. } PACKED components;
  21571. };
  21572. }
  21573. #ifndef DOXYGEN
  21574. PACKED
  21575. #endif
  21576. ;
  21577. /**
  21578. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  21579. This is used internally by the imaging classes.
  21580. @see PixelARGB
  21581. */
  21582. class JUCE_API PixelRGB
  21583. {
  21584. public:
  21585. /** Creates a pixel without defining its colour. */
  21586. PixelRGB() noexcept {}
  21587. ~PixelRGB() noexcept {}
  21588. /** Creates a pixel from a 32-bit argb value.
  21589. (The argb format is that used by PixelARGB)
  21590. */
  21591. PixelRGB (const uint32 argb) noexcept
  21592. {
  21593. r = (uint8) (argb >> 16);
  21594. g = (uint8) (argb >> 8);
  21595. b = (uint8) (argb);
  21596. }
  21597. forcedinline uint32 getARGB() const noexcept { return 0xff000000 | b | (g << 8) | (r << 16); }
  21598. forcedinline uint32 getUnpremultipliedARGB() const noexcept { return getARGB(); }
  21599. forcedinline uint32 getRB() const noexcept { return b | (uint32) (r << 16); }
  21600. forcedinline uint32 getAG() const noexcept { return 0xff0000 | g; }
  21601. forcedinline uint8 getAlpha() const noexcept { return 0xff; }
  21602. forcedinline uint8 getRed() const noexcept { return r; }
  21603. forcedinline uint8 getGreen() const noexcept { return g; }
  21604. forcedinline uint8 getBlue() const noexcept { return b; }
  21605. /** Blends another pixel onto this one.
  21606. This takes into account the opacity of the pixel being overlaid, and blends
  21607. it accordingly.
  21608. */
  21609. forcedinline void blend (const PixelARGB& src) noexcept
  21610. {
  21611. uint32 sargb = src.getARGB();
  21612. const uint32 alpha = 0x100 - (sargb >> 24);
  21613. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21614. sargb += 0x0000ff00 & (g * alpha);
  21615. r = (uint8) (sargb >> 16);
  21616. g = (uint8) (sargb >> 8);
  21617. b = (uint8) sargb;
  21618. }
  21619. forcedinline void blend (const PixelRGB& src) noexcept
  21620. {
  21621. set (src);
  21622. }
  21623. forcedinline void blend (const PixelAlpha& src) noexcept;
  21624. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21625. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21626. being used, so this can blend semi-transparently from a PixelRGB argument.
  21627. */
  21628. template <class Pixel>
  21629. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21630. {
  21631. ++extraAlpha;
  21632. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  21633. const uint32 sag = extraAlpha * src.getAG();
  21634. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  21635. const uint32 alpha = 0x100 - (sargb >> 24);
  21636. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21637. sargb += 0x0000ff00 & (g * alpha);
  21638. b = (uint8) sargb;
  21639. g = (uint8) (sargb >> 8);
  21640. r = (uint8) (sargb >> 16);
  21641. }
  21642. /** Blends another pixel with this one, creating a colour that is somewhere
  21643. between the two, as specified by the amount.
  21644. */
  21645. template <class Pixel>
  21646. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21647. {
  21648. uint32 drb = getRB();
  21649. drb += (((src.getRB() - drb) * amount) >> 8);
  21650. uint32 dag = getAG();
  21651. dag += (((src.getAG() - dag) * amount) >> 8);
  21652. b = (uint8) drb;
  21653. g = (uint8) dag;
  21654. r = (uint8) (drb >> 16);
  21655. }
  21656. /** Copies another pixel colour over this one.
  21657. This doesn't blend it - this colour is simply replaced by the other one.
  21658. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  21659. is thrown away.
  21660. */
  21661. template <class Pixel>
  21662. forcedinline void set (const Pixel& src) noexcept
  21663. {
  21664. b = src.getBlue();
  21665. g = src.getGreen();
  21666. r = src.getRed();
  21667. }
  21668. /** This method is included for compatibility with the PixelARGB class. */
  21669. forcedinline void setAlpha (const uint8) noexcept {}
  21670. /** Multiplies the colour's alpha value with another one. */
  21671. forcedinline void multiplyAlpha (int) noexcept {}
  21672. /** Sets the pixel's colour from individual components. */
  21673. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) noexcept
  21674. {
  21675. r = r_;
  21676. g = g_;
  21677. b = b_;
  21678. }
  21679. /** Premultiplies the pixel's RGB values by its alpha. */
  21680. forcedinline void premultiply() noexcept {}
  21681. /** Unpremultiplies the pixel's RGB values. */
  21682. forcedinline void unpremultiply() noexcept {}
  21683. forcedinline void desaturate() noexcept
  21684. {
  21685. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  21686. }
  21687. /** The indexes of the different components in the byte layout of this type of colour. */
  21688. #if JUCE_MAC
  21689. enum { indexR = 0, indexG = 1, indexB = 2 };
  21690. #else
  21691. enum { indexR = 2, indexG = 1, indexB = 0 };
  21692. #endif
  21693. private:
  21694. #if JUCE_MAC
  21695. uint8 r, g, b;
  21696. #else
  21697. uint8 b, g, r;
  21698. #endif
  21699. }
  21700. #ifndef DOXYGEN
  21701. PACKED
  21702. #endif
  21703. ;
  21704. forcedinline void PixelARGB::blend (const PixelRGB& src) noexcept
  21705. {
  21706. set (src);
  21707. }
  21708. /**
  21709. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  21710. This is used internally by the imaging classes.
  21711. @see PixelARGB, PixelRGB
  21712. */
  21713. class JUCE_API PixelAlpha
  21714. {
  21715. public:
  21716. /** Creates a pixel without defining its colour. */
  21717. PixelAlpha() noexcept {}
  21718. ~PixelAlpha() noexcept {}
  21719. /** Creates a pixel from a 32-bit argb value.
  21720. (The argb format is that used by PixelARGB)
  21721. */
  21722. PixelAlpha (const uint32 argb) noexcept
  21723. {
  21724. a = (uint8) (argb >> 24);
  21725. }
  21726. forcedinline uint32 getARGB() const noexcept { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  21727. forcedinline uint32 getUnpremultipliedARGB() const noexcept { return (((uint32) a) << 24) | 0xffffff; }
  21728. forcedinline uint32 getRB() const noexcept { return (((uint32) a) << 16) | a; }
  21729. forcedinline uint32 getAG() const noexcept { return (((uint32) a) << 16) | a; }
  21730. forcedinline uint8 getAlpha() const noexcept { return a; }
  21731. forcedinline uint8 getRed() const noexcept { return 0; }
  21732. forcedinline uint8 getGreen() const noexcept { return 0; }
  21733. forcedinline uint8 getBlue() const noexcept { return 0; }
  21734. /** Blends another pixel onto this one.
  21735. This takes into account the opacity of the pixel being overlaid, and blends
  21736. it accordingly.
  21737. */
  21738. template <class Pixel>
  21739. forcedinline void blend (const Pixel& src) noexcept
  21740. {
  21741. const int srcA = src.getAlpha();
  21742. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  21743. }
  21744. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21745. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21746. being used, so this can blend semi-transparently from a PixelRGB argument.
  21747. */
  21748. template <class Pixel>
  21749. forcedinline void blend (const Pixel& src, uint32 extraAlpha) noexcept
  21750. {
  21751. ++extraAlpha;
  21752. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  21753. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  21754. }
  21755. /** Blends another pixel with this one, creating a colour that is somewhere
  21756. between the two, as specified by the amount.
  21757. */
  21758. template <class Pixel>
  21759. forcedinline void tween (const Pixel& src, const uint32 amount) noexcept
  21760. {
  21761. a += ((src,getAlpha() - a) * amount) >> 8;
  21762. }
  21763. /** Copies another pixel colour over this one.
  21764. This doesn't blend it - this colour is simply replaced by the other one.
  21765. */
  21766. template <class Pixel>
  21767. forcedinline void set (const Pixel& src) noexcept
  21768. {
  21769. a = src.getAlpha();
  21770. }
  21771. /** Replaces the colour's alpha value with another one. */
  21772. forcedinline void setAlpha (const uint8 newAlpha) noexcept
  21773. {
  21774. a = newAlpha;
  21775. }
  21776. /** Multiplies the colour's alpha value with another one. */
  21777. forcedinline void multiplyAlpha (int multiplier) noexcept
  21778. {
  21779. ++multiplier;
  21780. a = (uint8) ((a * multiplier) >> 8);
  21781. }
  21782. forcedinline void multiplyAlpha (const float multiplier) noexcept
  21783. {
  21784. a = (uint8) (a * multiplier);
  21785. }
  21786. /** Sets the pixel's colour from individual components. */
  21787. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) noexcept
  21788. {
  21789. a = a_;
  21790. }
  21791. /** Premultiplies the pixel's RGB values by its alpha. */
  21792. forcedinline void premultiply() noexcept
  21793. {
  21794. }
  21795. /** Unpremultiplies the pixel's RGB values. */
  21796. forcedinline void unpremultiply() noexcept
  21797. {
  21798. }
  21799. forcedinline void desaturate() noexcept
  21800. {
  21801. }
  21802. /** The indexes of the different components in the byte layout of this type of colour. */
  21803. enum { indexA = 0 };
  21804. private:
  21805. uint8 a : 8;
  21806. }
  21807. #ifndef DOXYGEN
  21808. PACKED
  21809. #endif
  21810. ;
  21811. forcedinline void PixelRGB::blend (const PixelAlpha& src) noexcept
  21812. {
  21813. blend (PixelARGB (src.getARGB()));
  21814. }
  21815. forcedinline void PixelARGB::blend (const PixelAlpha& src) noexcept
  21816. {
  21817. uint32 sargb = src.getARGB();
  21818. const uint32 alpha = 0x100 - (sargb >> 24);
  21819. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21820. sargb += 0xff00ff00 & (getAG() * alpha);
  21821. argb = sargb;
  21822. }
  21823. #if JUCE_MSVC
  21824. #pragma pack (pop)
  21825. #endif
  21826. #undef PACKED
  21827. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  21828. /*** End of inlined file: juce_PixelFormats.h ***/
  21829. /**
  21830. Represents a colour, also including a transparency value.
  21831. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  21832. */
  21833. class JUCE_API Colour
  21834. {
  21835. public:
  21836. /** Creates a transparent black colour. */
  21837. Colour() noexcept;
  21838. /** Creates a copy of another Colour object. */
  21839. Colour (const Colour& other) noexcept;
  21840. /** Creates a colour from a 32-bit ARGB value.
  21841. The format of this number is:
  21842. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  21843. All components in the range 0x00 to 0xff.
  21844. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21845. @see getPixelARGB
  21846. */
  21847. explicit Colour (uint32 argb) noexcept;
  21848. /** Creates an opaque colour using 8-bit red, green and blue values */
  21849. Colour (uint8 red,
  21850. uint8 green,
  21851. uint8 blue) noexcept;
  21852. /** Creates an opaque colour using 8-bit red, green and blue values */
  21853. static Colour fromRGB (uint8 red,
  21854. uint8 green,
  21855. uint8 blue) noexcept;
  21856. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21857. Colour (uint8 red,
  21858. uint8 green,
  21859. uint8 blue,
  21860. uint8 alpha) noexcept;
  21861. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21862. static Colour fromRGBA (uint8 red,
  21863. uint8 green,
  21864. uint8 blue,
  21865. uint8 alpha) noexcept;
  21866. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  21867. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  21868. Values outside the valid range will be clipped.
  21869. */
  21870. Colour (uint8 red,
  21871. uint8 green,
  21872. uint8 blue,
  21873. float alpha) noexcept;
  21874. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  21875. static Colour fromRGBAFloat (uint8 red,
  21876. uint8 green,
  21877. uint8 blue,
  21878. float alpha) noexcept;
  21879. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21880. The floating point values must be between 0.0 and 1.0.
  21881. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21882. Values outside the valid range will be clipped.
  21883. */
  21884. Colour (float hue,
  21885. float saturation,
  21886. float brightness,
  21887. uint8 alpha) noexcept;
  21888. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  21889. All values must be between 0.0 and 1.0.
  21890. Numbers outside the valid range will be clipped.
  21891. */
  21892. Colour (float hue,
  21893. float saturation,
  21894. float brightness,
  21895. float alpha) noexcept;
  21896. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21897. The floating point values must be between 0.0 and 1.0.
  21898. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21899. Values outside the valid range will be clipped.
  21900. */
  21901. static Colour fromHSV (float hue,
  21902. float saturation,
  21903. float brightness,
  21904. float alpha) noexcept;
  21905. /** Destructor. */
  21906. ~Colour() noexcept;
  21907. /** Copies another Colour object. */
  21908. Colour& operator= (const Colour& other) noexcept;
  21909. /** Compares two colours. */
  21910. bool operator== (const Colour& other) const noexcept;
  21911. /** Compares two colours. */
  21912. bool operator!= (const Colour& other) const noexcept;
  21913. /** Returns the red component of this colour.
  21914. @returns a value between 0x00 and 0xff.
  21915. */
  21916. uint8 getRed() const noexcept { return argb.getRed(); }
  21917. /** Returns the green component of this colour.
  21918. @returns a value between 0x00 and 0xff.
  21919. */
  21920. uint8 getGreen() const noexcept { return argb.getGreen(); }
  21921. /** Returns the blue component of this colour.
  21922. @returns a value between 0x00 and 0xff.
  21923. */
  21924. uint8 getBlue() const noexcept { return argb.getBlue(); }
  21925. /** Returns the red component of this colour as a floating point value.
  21926. @returns a value between 0.0 and 1.0
  21927. */
  21928. float getFloatRed() const noexcept;
  21929. /** Returns the green component of this colour as a floating point value.
  21930. @returns a value between 0.0 and 1.0
  21931. */
  21932. float getFloatGreen() const noexcept;
  21933. /** Returns the blue component of this colour as a floating point value.
  21934. @returns a value between 0.0 and 1.0
  21935. */
  21936. float getFloatBlue() const noexcept;
  21937. /** Returns a premultiplied ARGB pixel object that represents this colour.
  21938. */
  21939. const PixelARGB getPixelARGB() const noexcept;
  21940. /** Returns a 32-bit integer that represents this colour.
  21941. The format of this number is:
  21942. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  21943. */
  21944. uint32 getARGB() const noexcept;
  21945. /** Returns the colour's alpha (opacity).
  21946. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  21947. */
  21948. uint8 getAlpha() const noexcept { return argb.getAlpha(); }
  21949. /** Returns the colour's alpha (opacity) as a floating point value.
  21950. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  21951. */
  21952. float getFloatAlpha() const noexcept;
  21953. /** Returns true if this colour is completely opaque.
  21954. Equivalent to (getAlpha() == 0xff).
  21955. */
  21956. bool isOpaque() const noexcept;
  21957. /** Returns true if this colour is completely transparent.
  21958. Equivalent to (getAlpha() == 0x00).
  21959. */
  21960. bool isTransparent() const noexcept;
  21961. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21962. Colour withAlpha (uint8 newAlpha) const noexcept;
  21963. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21964. Colour withAlpha (float newAlpha) const noexcept;
  21965. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  21966. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  21967. */
  21968. Colour withMultipliedAlpha (float alphaMultiplier) const noexcept;
  21969. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  21970. If the foreground colour is semi-transparent, it is blended onto this colour
  21971. accordingly.
  21972. */
  21973. Colour overlaidWith (const Colour& foregroundColour) const noexcept;
  21974. /** Returns a colour that lies somewhere between this one and another.
  21975. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  21976. is 1.0, the result is 100% of the other colour.
  21977. */
  21978. Colour interpolatedWith (const Colour& other, float proportionOfOther) const noexcept;
  21979. /** Returns the colour's hue component.
  21980. The value returned is in the range 0.0 to 1.0
  21981. */
  21982. float getHue() const noexcept;
  21983. /** Returns the colour's saturation component.
  21984. The value returned is in the range 0.0 to 1.0
  21985. */
  21986. float getSaturation() const noexcept;
  21987. /** Returns the colour's brightness component.
  21988. The value returned is in the range 0.0 to 1.0
  21989. */
  21990. float getBrightness() const noexcept;
  21991. /** Returns the colour's hue, saturation and brightness components all at once.
  21992. The values returned are in the range 0.0 to 1.0
  21993. */
  21994. void getHSB (float& hue,
  21995. float& saturation,
  21996. float& brightness) const noexcept;
  21997. /** Returns a copy of this colour with a different hue. */
  21998. Colour withHue (float newHue) const noexcept;
  21999. /** Returns a copy of this colour with a different saturation. */
  22000. Colour withSaturation (float newSaturation) const noexcept;
  22001. /** Returns a copy of this colour with a different brightness.
  22002. @see brighter, darker, withMultipliedBrightness
  22003. */
  22004. Colour withBrightness (float newBrightness) const noexcept;
  22005. /** Returns a copy of this colour with it hue rotated.
  22006. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  22007. @see brighter, darker, withMultipliedBrightness
  22008. */
  22009. Colour withRotatedHue (float amountToRotate) const noexcept;
  22010. /** Returns a copy of this colour with its saturation multiplied by the given value.
  22011. The new colour's saturation is (this->getSaturation() * multiplier)
  22012. (the result is clipped to legal limits).
  22013. */
  22014. Colour withMultipliedSaturation (float multiplier) const noexcept;
  22015. /** Returns a copy of this colour with its brightness multiplied by the given value.
  22016. The new colour's saturation is (this->getBrightness() * multiplier)
  22017. (the result is clipped to legal limits).
  22018. */
  22019. Colour withMultipliedBrightness (float amount) const noexcept;
  22020. /** Returns a brighter version of this colour.
  22021. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  22022. unchanged, and higher values make it brighter
  22023. @see withMultipliedBrightness
  22024. */
  22025. Colour brighter (float amountBrighter = 0.4f) const noexcept;
  22026. /** Returns a darker version of this colour.
  22027. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  22028. unchanged, and higher values make it darker
  22029. @see withMultipliedBrightness
  22030. */
  22031. Colour darker (float amountDarker = 0.4f) const noexcept;
  22032. /** Returns a colour that will be clearly visible against this colour.
  22033. The amount parameter indicates how contrasting the new colour should
  22034. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  22035. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  22036. return white; Colours::white.contrasting (1.0f) will return black, etc.
  22037. */
  22038. Colour contrasting (float amount = 1.0f) const noexcept;
  22039. /** Returns a colour that contrasts against two colours.
  22040. Looks for a colour that contrasts with both of the colours passed-in.
  22041. Handy for things like choosing a highlight colour in text editors, etc.
  22042. */
  22043. static Colour contrasting (const Colour& colour1,
  22044. const Colour& colour2) noexcept;
  22045. /** Returns an opaque shade of grey.
  22046. @param brightness the level of grey to return - 0 is black, 1.0 is white
  22047. */
  22048. static Colour greyLevel (float brightness) noexcept;
  22049. /** Returns a stringified version of this colour.
  22050. The string can be turned back into a colour using the fromString() method.
  22051. */
  22052. String toString() const;
  22053. /** Reads the colour from a string that was created with toString().
  22054. */
  22055. static Colour fromString (const String& encodedColourString);
  22056. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  22057. String toDisplayString (bool includeAlphaValue) const;
  22058. private:
  22059. PixelARGB argb;
  22060. };
  22061. #endif // __JUCE_COLOUR_JUCEHEADER__
  22062. /*** End of inlined file: juce_Colour.h ***/
  22063. /**
  22064. Contains a set of predefined named colours (mostly standard HTML colours)
  22065. @see Colour, Colours::greyLevel
  22066. */
  22067. class Colours
  22068. {
  22069. public:
  22070. static JUCE_API const Colour
  22071. transparentBlack, /**< ARGB = 0x00000000 */
  22072. transparentWhite, /**< ARGB = 0x00ffffff */
  22073. black, /**< ARGB = 0xff000000 */
  22074. white, /**< ARGB = 0xffffffff */
  22075. blue, /**< ARGB = 0xff0000ff */
  22076. grey, /**< ARGB = 0xff808080 */
  22077. green, /**< ARGB = 0xff008000 */
  22078. red, /**< ARGB = 0xffff0000 */
  22079. yellow, /**< ARGB = 0xffffff00 */
  22080. aliceblue, antiquewhite, aqua, aquamarine,
  22081. azure, beige, bisque, blanchedalmond,
  22082. blueviolet, brown, burlywood, cadetblue,
  22083. chartreuse, chocolate, coral, cornflowerblue,
  22084. cornsilk, crimson, cyan, darkblue,
  22085. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  22086. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  22087. darkorchid, darkred, darksalmon, darkseagreen,
  22088. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  22089. deeppink, deepskyblue, dimgrey, dodgerblue,
  22090. firebrick, floralwhite, forestgreen, fuchsia,
  22091. gainsboro, gold, goldenrod, greenyellow,
  22092. honeydew, hotpink, indianred, indigo,
  22093. ivory, khaki, lavender, lavenderblush,
  22094. lemonchiffon, lightblue, lightcoral, lightcyan,
  22095. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  22096. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  22097. lightsteelblue, lightyellow, lime, limegreen,
  22098. linen, magenta, maroon, mediumaquamarine,
  22099. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  22100. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  22101. midnightblue, mintcream, mistyrose, navajowhite,
  22102. navy, oldlace, olive, olivedrab,
  22103. orange, orangered, orchid, palegoldenrod,
  22104. palegreen, paleturquoise, palevioletred, papayawhip,
  22105. peachpuff, peru, pink, plum,
  22106. powderblue, purple, rosybrown, royalblue,
  22107. saddlebrown, salmon, sandybrown, seagreen,
  22108. seashell, sienna, silver, skyblue,
  22109. slateblue, slategrey, snow, springgreen,
  22110. steelblue, tan, teal, thistle,
  22111. tomato, turquoise, violet, wheat,
  22112. whitesmoke, yellowgreen;
  22113. /** Attempts to look up a string in the list of known colour names, and return
  22114. the appropriate colour.
  22115. A non-case-sensitive search is made of the list of predefined colours, and
  22116. if a match is found, that colour is returned. If no match is found, the
  22117. colour passed in as the defaultColour parameter is returned.
  22118. */
  22119. static JUCE_API const Colour findColourForName (const String& colourName,
  22120. const Colour& defaultColour);
  22121. private:
  22122. // this isn't a class you should ever instantiate - it's just here for the
  22123. // static values in it.
  22124. Colours();
  22125. JUCE_DECLARE_NON_COPYABLE (Colours);
  22126. };
  22127. #endif // __JUCE_COLOURS_JUCEHEADER__
  22128. /*** End of inlined file: juce_Colours.h ***/
  22129. /*** Start of inlined file: juce_ColourGradient.h ***/
  22130. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  22131. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  22132. /**
  22133. Describes the layout and colours that should be used to paint a colour gradient.
  22134. @see Graphics::setGradientFill
  22135. */
  22136. class JUCE_API ColourGradient
  22137. {
  22138. public:
  22139. /** Creates a gradient object.
  22140. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  22141. colour2 should be. In between them there's a gradient.
  22142. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  22143. its centre.
  22144. The alpha transparencies of the colours are used, so note that
  22145. if you blend from transparent to a solid colour, the RGB of the transparent
  22146. colour will become visible in parts of the gradient. e.g. blending
  22147. from Colour::transparentBlack to Colours::white will produce a
  22148. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  22149. will be white all the way across.
  22150. @see ColourGradient
  22151. */
  22152. ColourGradient (const Colour& colour1, float x1, float y1,
  22153. const Colour& colour2, float x2, float y2,
  22154. bool isRadial);
  22155. /** Creates an uninitialised gradient.
  22156. If you use this constructor instead of the other one, be sure to set all the
  22157. object's public member variables before using it!
  22158. */
  22159. ColourGradient() noexcept;
  22160. /** Destructor */
  22161. ~ColourGradient();
  22162. /** Removes any colours that have been added.
  22163. This will also remove any start and end colours, so the gradient won't work. You'll
  22164. need to add more colours with addColour().
  22165. */
  22166. void clearColours();
  22167. /** Adds a colour at a point along the length of the gradient.
  22168. This allows the gradient to go through a spectrum of colours, instead of just a
  22169. start and end colour.
  22170. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  22171. of the distance along the line between the two points
  22172. at which the colour should occur.
  22173. @param colour the colour that should be used at this point
  22174. @returns the index at which the new point was added
  22175. */
  22176. int addColour (double proportionAlongGradient,
  22177. const Colour& colour);
  22178. /** Removes one of the colours from the gradient. */
  22179. void removeColour (int index);
  22180. /** Multiplies the alpha value of all the colours by the given scale factor */
  22181. void multiplyOpacity (float multiplier) noexcept;
  22182. /** Returns the number of colour-stops that have been added. */
  22183. int getNumColours() const noexcept;
  22184. /** Returns the position along the length of the gradient of the colour with this index.
  22185. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  22186. */
  22187. double getColourPosition (int index) const noexcept;
  22188. /** Returns the colour that was added with a given index.
  22189. The index is from 0 to getNumColours() - 1.
  22190. */
  22191. const Colour getColour (int index) const noexcept;
  22192. /** Changes the colour at a given index.
  22193. The index is from 0 to getNumColours() - 1.
  22194. */
  22195. void setColour (int index, const Colour& newColour) noexcept;
  22196. /** Returns the an interpolated colour at any position along the gradient.
  22197. @param position the position along the gradient, between 0 and 1
  22198. */
  22199. Colour getColourAtPosition (double position) const noexcept;
  22200. /** Creates a set of interpolated premultiplied ARGB values.
  22201. This will resize the HeapBlock, fill it with the colours, and will return the number of
  22202. colours that it added.
  22203. */
  22204. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  22205. /** Returns true if all colours are opaque. */
  22206. bool isOpaque() const noexcept;
  22207. /** Returns true if all colours are completely transparent. */
  22208. bool isInvisible() const noexcept;
  22209. Point<float> point1, point2;
  22210. /** If true, the gradient should be filled circularly, centred around
  22211. point1, with point2 defining a point on the circumference.
  22212. If false, the gradient is linear between the two points.
  22213. */
  22214. bool isRadial;
  22215. bool operator== (const ColourGradient& other) const noexcept;
  22216. bool operator!= (const ColourGradient& other) const noexcept;
  22217. private:
  22218. struct ColourPoint
  22219. {
  22220. ColourPoint() noexcept {}
  22221. ColourPoint (const double position_, const Colour& colour_) noexcept
  22222. : position (position_), colour (colour_)
  22223. {}
  22224. bool operator== (const ColourPoint& other) const noexcept;
  22225. bool operator!= (const ColourPoint& other) const noexcept;
  22226. double position;
  22227. Colour colour;
  22228. };
  22229. Array <ColourPoint> colours;
  22230. JUCE_LEAK_DETECTOR (ColourGradient);
  22231. };
  22232. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  22233. /*** End of inlined file: juce_ColourGradient.h ***/
  22234. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  22235. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  22236. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  22237. /**
  22238. Defines the method used to postion some kind of rectangular object within
  22239. a rectangular viewport.
  22240. Although similar to Justification, this is more specific, and has some extra
  22241. options.
  22242. */
  22243. class JUCE_API RectanglePlacement
  22244. {
  22245. public:
  22246. /** Creates a RectanglePlacement object using a combination of flags. */
  22247. inline RectanglePlacement (int flags_) noexcept : flags (flags_) {}
  22248. /** Creates a copy of another RectanglePlacement object. */
  22249. RectanglePlacement (const RectanglePlacement& other) noexcept;
  22250. /** Copies another RectanglePlacement object. */
  22251. RectanglePlacement& operator= (const RectanglePlacement& other) noexcept;
  22252. bool operator== (const RectanglePlacement& other) const noexcept;
  22253. bool operator!= (const RectanglePlacement& other) const noexcept;
  22254. /** Flag values that can be combined and used in the constructor. */
  22255. enum
  22256. {
  22257. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  22258. xLeft = 1,
  22259. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  22260. xRight = 2,
  22261. /** Indicates that the source should be placed in the centre between the left and right
  22262. sides of the available space. */
  22263. xMid = 4,
  22264. /** Indicates that the source's top edge should be aligned with the top edge of the
  22265. destination rectangle. */
  22266. yTop = 8,
  22267. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  22268. destination rectangle. */
  22269. yBottom = 16,
  22270. /** Indicates that the source should be placed in the centre between the top and bottom
  22271. sides of the available space. */
  22272. yMid = 32,
  22273. /** If this flag is set, then the source rectangle will be resized to completely fill
  22274. the destination rectangle, and all other flags are ignored.
  22275. */
  22276. stretchToFit = 64,
  22277. /** If this flag is set, then the source rectangle will be resized so that it is the
  22278. minimum size to completely fill the destination rectangle, without changing its
  22279. aspect ratio. This means that some of the source rectangle may fall outside
  22280. the destination.
  22281. If this flag is not set, the source will be given the maximum size at which none
  22282. of it falls outside the destination rectangle.
  22283. */
  22284. fillDestination = 128,
  22285. /** Indicates that the source rectangle can be reduced in size if required, but should
  22286. never be made larger than its original size.
  22287. */
  22288. onlyReduceInSize = 256,
  22289. /** Indicates that the source rectangle can be enlarged if required, but should
  22290. never be made smaller than its original size.
  22291. */
  22292. onlyIncreaseInSize = 512,
  22293. /** Indicates that the source rectangle's size should be left unchanged.
  22294. */
  22295. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  22296. /** A shorthand value that is equivalent to (xMid | yMid). */
  22297. centred = 4 + 32
  22298. };
  22299. /** Returns the raw flags that are set for this object. */
  22300. inline int getFlags() const noexcept { return flags; }
  22301. /** Tests a set of flags for this object.
  22302. @returns true if any of the flags passed in are set on this object.
  22303. */
  22304. inline bool testFlags (int flagsToTest) const noexcept { return (flags & flagsToTest) != 0; }
  22305. /** Adjusts the position and size of a rectangle to fit it into a space.
  22306. The source rectangle co-ordinates will be adjusted so that they fit into
  22307. the destination rectangle based on this object's flags.
  22308. */
  22309. void applyTo (double& sourceX,
  22310. double& sourceY,
  22311. double& sourceW,
  22312. double& sourceH,
  22313. double destinationX,
  22314. double destinationY,
  22315. double destinationW,
  22316. double destinationH) const noexcept;
  22317. /** Returns the transform that should be applied to these source co-ordinates to fit them
  22318. into the destination rectangle using the current flags.
  22319. */
  22320. template <typename ValueType>
  22321. const Rectangle<ValueType> appliedTo (const Rectangle<ValueType>& source,
  22322. const Rectangle<ValueType>& destination) const noexcept
  22323. {
  22324. double x = source.getX(), y = source.getY(), w = source.getWidth(), h = source.getHeight();
  22325. applyTo (x, y, w, h, static_cast <double> (destination.getX()), static_cast <double> (destination.getY()),
  22326. static_cast <double> (destination.getWidth()), static_cast <double> (destination.getHeight()));
  22327. return Rectangle<ValueType> (static_cast <ValueType> (x), static_cast <ValueType> (y),
  22328. static_cast <ValueType> (w), static_cast <ValueType> (h));
  22329. }
  22330. /** Returns the transform that should be applied to these source co-ordinates to fit them
  22331. into the destination rectangle using the current flags.
  22332. */
  22333. const AffineTransform getTransformToFit (const Rectangle<float>& source,
  22334. const Rectangle<float>& destination) const noexcept;
  22335. private:
  22336. int flags;
  22337. };
  22338. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  22339. /*** End of inlined file: juce_RectanglePlacement.h ***/
  22340. class LowLevelGraphicsContext;
  22341. class Image;
  22342. class FillType;
  22343. class RectangleList;
  22344. /**
  22345. A graphics context, used for drawing a component or image.
  22346. When a Component needs painting, a Graphics context is passed to its
  22347. Component::paint() method, and this you then call methods within this
  22348. object to actually draw the component's content.
  22349. A Graphics can also be created from an image, to allow drawing directly onto
  22350. that image.
  22351. @see Component::paint
  22352. */
  22353. class JUCE_API Graphics
  22354. {
  22355. public:
  22356. /** Creates a Graphics object to draw directly onto the given image.
  22357. The graphics object that is created will be set up to draw onto the image,
  22358. with the context's clipping area being the entire size of the image, and its
  22359. origin being the image's origin. To draw into a subsection of an image, use the
  22360. reduceClipRegion() and setOrigin() methods.
  22361. Obviously you shouldn't delete the image before this context is deleted.
  22362. */
  22363. explicit Graphics (const Image& imageToDrawOnto);
  22364. /** Destructor. */
  22365. ~Graphics();
  22366. /** Changes the current drawing colour.
  22367. This sets the colour that will now be used for drawing operations - it also
  22368. sets the opacity to that of the colour passed-in.
  22369. If a brush is being used when this method is called, the brush will be deselected,
  22370. and any subsequent drawing will be done with a solid colour brush instead.
  22371. @see setOpacity
  22372. */
  22373. void setColour (const Colour& newColour);
  22374. /** Changes the opacity to use with the current colour.
  22375. If a solid colour is being used for drawing, this changes its opacity
  22376. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  22377. If a gradient is being used, this will have no effect on it.
  22378. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  22379. */
  22380. void setOpacity (float newOpacity);
  22381. /** Sets the context to use a gradient for its fill pattern.
  22382. */
  22383. void setGradientFill (const ColourGradient& gradient);
  22384. /** Sets the context to use a tiled image pattern for filling.
  22385. Make sure that you don't delete this image while it's still being used by
  22386. this context!
  22387. */
  22388. void setTiledImageFill (const Image& imageToUse,
  22389. int anchorX, int anchorY,
  22390. float opacity);
  22391. /** Changes the current fill settings.
  22392. @see setColour, setGradientFill, setTiledImageFill
  22393. */
  22394. void setFillType (const FillType& newFill);
  22395. /** Changes the font to use for subsequent text-drawing functions.
  22396. Note there's also a setFont (float, int) method to quickly change the size and
  22397. style of the current font.
  22398. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  22399. */
  22400. void setFont (const Font& newFont);
  22401. /** Changes the size and style of the currently-selected font.
  22402. This is a convenient shortcut that changes the context's current font to a
  22403. different size or style. The typeface won't be changed.
  22404. @see Font
  22405. */
  22406. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  22407. /** Returns the currently selected font. */
  22408. Font getCurrentFont() const;
  22409. /** Draws a one-line text string.
  22410. This will use the current colour (or brush) to fill the text. The font is the last
  22411. one specified by setFont().
  22412. @param text the string to draw
  22413. @param startX the position to draw the left-hand edge of the text
  22414. @param baselineY the position of the text's baseline
  22415. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  22416. */
  22417. void drawSingleLineText (const String& text,
  22418. int startX, int baselineY) const;
  22419. /** Draws text across multiple lines.
  22420. This will break the text onto a new line where there's a new-line or
  22421. carriage-return character, or at a word-boundary when the text becomes wider
  22422. than the size specified by the maximumLineWidth parameter.
  22423. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  22424. */
  22425. void drawMultiLineText (const String& text,
  22426. int startX, int baselineY,
  22427. int maximumLineWidth) const;
  22428. /** Renders a string of text as a vector path.
  22429. This allows a string to be transformed with an arbitrary AffineTransform and
  22430. rendered using the current colour/brush. It's much slower than the normal text methods
  22431. but more accurate.
  22432. @see setFont
  22433. */
  22434. void drawTextAsPath (const String& text,
  22435. const AffineTransform& transform) const;
  22436. /** Draws a line of text within a specified rectangle.
  22437. The text will be positioned within the rectangle based on the justification
  22438. flags passed-in. If the string is too long to fit inside the rectangle, it will
  22439. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  22440. flag is true).
  22441. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  22442. */
  22443. void drawText (const String& text,
  22444. int x, int y, int width, int height,
  22445. const Justification& justificationType,
  22446. bool useEllipsesIfTooBig) const;
  22447. /** Tries to draw a text string inside a given space.
  22448. This does its best to make the given text readable within the specified rectangle,
  22449. so it useful for labelling things.
  22450. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  22451. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  22452. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  22453. it's been truncated.
  22454. A Justification parameter lets you specify how the text is laid out within the rectangle,
  22455. both horizontally and vertically.
  22456. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  22457. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  22458. can set this value to 1.0f.
  22459. @see GlyphArrangement::addFittedText
  22460. */
  22461. void drawFittedText (const String& text,
  22462. int x, int y, int width, int height,
  22463. const Justification& justificationFlags,
  22464. int maximumNumberOfLines,
  22465. float minimumHorizontalScale = 0.7f) const;
  22466. /** Fills the context's entire clip region with the current colour or brush.
  22467. (See also the fillAll (const Colour&) method which is a quick way of filling
  22468. it with a given colour).
  22469. */
  22470. void fillAll() const;
  22471. /** Fills the context's entire clip region with a given colour.
  22472. This leaves the context's current colour and brush unchanged, it just
  22473. uses the specified colour temporarily.
  22474. */
  22475. void fillAll (const Colour& colourToUse) const;
  22476. /** Fills a rectangle with the current colour or brush.
  22477. @see drawRect, fillRoundedRectangle
  22478. */
  22479. void fillRect (int x, int y, int width, int height) const;
  22480. /** Fills a rectangle with the current colour or brush. */
  22481. void fillRect (const Rectangle<int>& rectangle) const;
  22482. /** Fills a rectangle with the current colour or brush.
  22483. This uses sub-pixel positioning so is slower than the fillRect method which
  22484. takes integer co-ordinates.
  22485. */
  22486. void fillRect (float x, float y, float width, float height) const;
  22487. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  22488. @see drawRoundedRectangle, Path::addRoundedRectangle
  22489. */
  22490. void fillRoundedRectangle (float x, float y, float width, float height,
  22491. float cornerSize) const;
  22492. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  22493. @see drawRoundedRectangle, Path::addRoundedRectangle
  22494. */
  22495. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  22496. float cornerSize) const;
  22497. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  22498. */
  22499. void fillCheckerBoard (const Rectangle<int>& area,
  22500. int checkWidth, int checkHeight,
  22501. const Colour& colour1, const Colour& colour2) const;
  22502. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22503. The lines are drawn inside the given rectangle, and greater line thicknesses
  22504. extend inwards.
  22505. @see fillRect
  22506. */
  22507. void drawRect (int x, int y, int width, int height,
  22508. int lineThickness = 1) const;
  22509. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22510. The lines are drawn inside the given rectangle, and greater line thicknesses
  22511. extend inwards.
  22512. @see fillRect
  22513. */
  22514. void drawRect (float x, float y, float width, float height,
  22515. float lineThickness = 1.0f) const;
  22516. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22517. The lines are drawn inside the given rectangle, and greater line thicknesses
  22518. extend inwards.
  22519. @see fillRect
  22520. */
  22521. void drawRect (const Rectangle<int>& rectangle,
  22522. int lineThickness = 1) const;
  22523. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  22524. @see fillRoundedRectangle, Path::addRoundedRectangle
  22525. */
  22526. void drawRoundedRectangle (float x, float y, float width, float height,
  22527. float cornerSize, float lineThickness) const;
  22528. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  22529. @see fillRoundedRectangle, Path::addRoundedRectangle
  22530. */
  22531. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  22532. float cornerSize, float lineThickness) const;
  22533. /** Draws a 3D raised (or indented) bevel using two colours.
  22534. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  22535. extend inwards.
  22536. The top-left colour is used for the top- and left-hand edges of the
  22537. bevel; the bottom-right colour is used for the bottom- and right-hand
  22538. edges.
  22539. If useGradient is true, then the bevel fades out to make it look more curved
  22540. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  22541. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  22542. the centre edges are sharp and it fades towards the outside.
  22543. */
  22544. void drawBevel (int x, int y, int width, int height,
  22545. int bevelThickness,
  22546. const Colour& topLeftColour = Colours::white,
  22547. const Colour& bottomRightColour = Colours::black,
  22548. bool useGradient = true,
  22549. bool sharpEdgeOnOutside = true) const;
  22550. /** Draws a pixel using the current colour or brush.
  22551. */
  22552. void setPixel (int x, int y) const;
  22553. /** Fills an ellipse with the current colour or brush.
  22554. The ellipse is drawn to fit inside the given rectangle.
  22555. @see drawEllipse, Path::addEllipse
  22556. */
  22557. void fillEllipse (float x, float y, float width, float height) const;
  22558. /** Draws an elliptical stroke using the current colour or brush.
  22559. @see fillEllipse, Path::addEllipse
  22560. */
  22561. void drawEllipse (float x, float y, float width, float height,
  22562. float lineThickness) const;
  22563. /** Draws a line between two points.
  22564. The line is 1 pixel wide and drawn with the current colour or brush.
  22565. */
  22566. void drawLine (float startX, float startY, float endX, float endY) const;
  22567. /** Draws a line between two points with a given thickness.
  22568. @see Path::addLineSegment
  22569. */
  22570. void drawLine (float startX, float startY, float endX, float endY,
  22571. float lineThickness) const;
  22572. /** Draws a line between two points.
  22573. The line is 1 pixel wide and drawn with the current colour or brush.
  22574. */
  22575. void drawLine (const Line<float>& line) const;
  22576. /** Draws a line between two points with a given thickness.
  22577. @see Path::addLineSegment
  22578. */
  22579. void drawLine (const Line<float>& line, float lineThickness) const;
  22580. /** Draws a dashed line using a custom set of dash-lengths.
  22581. @param line the line to draw
  22582. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  22583. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  22584. draw 6 pixels, skip 7 pixels, and then repeat.
  22585. @param numDashLengths the number of elements in the array (this must be an even number).
  22586. @param lineThickness the thickness of the line to draw
  22587. @param dashIndexToStartFrom the index in the dash-length array to use for the first segment
  22588. @see PathStrokeType::createDashedStroke
  22589. */
  22590. void drawDashedLine (const Line<float>& line,
  22591. const float* dashLengths, int numDashLengths,
  22592. float lineThickness = 1.0f,
  22593. int dashIndexToStartFrom = 0) const;
  22594. /** Draws a vertical line of pixels at a given x position.
  22595. The x position is an integer, but the top and bottom of the line can be sub-pixel
  22596. positions, and these will be anti-aliased if necessary.
  22597. The bottom parameter must be greater than or equal to the top parameter.
  22598. */
  22599. void drawVerticalLine (int x, float top, float bottom) const;
  22600. /** Draws a horizontal line of pixels at a given y position.
  22601. The y position is an integer, but the left and right ends of the line can be sub-pixel
  22602. positions, and these will be anti-aliased if necessary.
  22603. The right parameter must be greater than or equal to the left parameter.
  22604. */
  22605. void drawHorizontalLine (int y, float left, float right) const;
  22606. /** Fills a path using the currently selected colour or brush.
  22607. */
  22608. void fillPath (const Path& path,
  22609. const AffineTransform& transform = AffineTransform::identity) const;
  22610. /** Draws a path's outline using the currently selected colour or brush.
  22611. */
  22612. void strokePath (const Path& path,
  22613. const PathStrokeType& strokeType,
  22614. const AffineTransform& transform = AffineTransform::identity) const;
  22615. /** Draws a line with an arrowhead at its end.
  22616. @param line the line to draw
  22617. @param lineThickness the thickness of the line
  22618. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  22619. @param arrowheadLength the length of the arrow head (along the length of the line)
  22620. */
  22621. void drawArrow (const Line<float>& line,
  22622. float lineThickness,
  22623. float arrowheadWidth,
  22624. float arrowheadLength) const;
  22625. /** Types of rendering quality that can be specified when drawing images.
  22626. @see blendImage, Graphics::setImageResamplingQuality
  22627. */
  22628. enum ResamplingQuality
  22629. {
  22630. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  22631. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  22632. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  22633. };
  22634. /** Changes the quality that will be used when resampling images.
  22635. By default a Graphics object will be set to mediumRenderingQuality.
  22636. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  22637. */
  22638. void setImageResamplingQuality (const ResamplingQuality newQuality);
  22639. /** Draws an image.
  22640. This will draw the whole of an image, positioning its top-left corner at the
  22641. given co-ordinates, and keeping its size the same. This is the simplest image
  22642. drawing method - the others give more control over the scaling and clipping
  22643. of the images.
  22644. Images are composited using the context's current opacity, so if you
  22645. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22646. (or setColour() with an opaque colour) before drawing images.
  22647. */
  22648. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  22649. bool fillAlphaChannelWithCurrentBrush = false) const;
  22650. /** Draws part of an image, rescaling it to fit in a given target region.
  22651. The specified area of the source image is rescaled and drawn to fill the
  22652. specifed destination rectangle.
  22653. Images are composited using the context's current opacity, so if you
  22654. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22655. (or setColour() with an opaque colour) before drawing images.
  22656. @param imageToDraw the image to overlay
  22657. @param destX the left of the destination rectangle
  22658. @param destY the top of the destination rectangle
  22659. @param destWidth the width of the destination rectangle
  22660. @param destHeight the height of the destination rectangle
  22661. @param sourceX the left of the rectangle to copy from the source image
  22662. @param sourceY the top of the rectangle to copy from the source image
  22663. @param sourceWidth the width of the rectangle to copy from the source image
  22664. @param sourceHeight the height of the rectangle to copy from the source image
  22665. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  22666. the source image's alpha channel is used as a mask with
  22667. which to fill the destination using the current colour
  22668. or brush. (If the source is has no alpha channel, then
  22669. it will just fill the target with a solid rectangle)
  22670. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  22671. */
  22672. void drawImage (const Image& imageToDraw,
  22673. int destX, int destY, int destWidth, int destHeight,
  22674. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  22675. bool fillAlphaChannelWithCurrentBrush = false) const;
  22676. /** Draws an image, having applied an affine transform to it.
  22677. This lets you throw the image around in some wacky ways, rotate it, shear,
  22678. scale it, etc.
  22679. Images are composited using the context's current opacity, so if you
  22680. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22681. (or setColour() with an opaque colour) before drawing images.
  22682. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  22683. are ignored and it is filled with the current brush, masked by its alpha channel.
  22684. If you want to render only a subsection of an image, use Image::getClippedImage() to
  22685. create the section that you need.
  22686. @see setImageResamplingQuality, drawImage
  22687. */
  22688. void drawImageTransformed (const Image& imageToDraw,
  22689. const AffineTransform& transform,
  22690. bool fillAlphaChannelWithCurrentBrush = false) const;
  22691. /** Draws an image to fit within a designated rectangle.
  22692. If the image is too big or too small for the space, it will be rescaled
  22693. to fit as nicely as it can do without affecting its aspect ratio. It will
  22694. then be placed within the target rectangle according to the justification flags
  22695. specified.
  22696. @param imageToDraw the source image to draw
  22697. @param destX top-left of the target rectangle to fit it into
  22698. @param destY top-left of the target rectangle to fit it into
  22699. @param destWidth size of the target rectangle to fit the image into
  22700. @param destHeight size of the target rectangle to fit the image into
  22701. @param placementWithinTarget this specifies how the image should be positioned
  22702. within the target rectangle - see the RectanglePlacement
  22703. class for more details about this.
  22704. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  22705. alpha channel will be used as a mask with which to
  22706. draw with the current brush or colour. This is
  22707. similar to fillAlphaMap(), and see also drawImage()
  22708. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  22709. */
  22710. void drawImageWithin (const Image& imageToDraw,
  22711. int destX, int destY, int destWidth, int destHeight,
  22712. const RectanglePlacement& placementWithinTarget,
  22713. bool fillAlphaChannelWithCurrentBrush = false) const;
  22714. /** Returns the position of the bounding box for the current clipping region.
  22715. @see getClipRegion, clipRegionIntersects
  22716. */
  22717. const Rectangle<int> getClipBounds() const;
  22718. /** Checks whether a rectangle overlaps the context's clipping region.
  22719. If this returns false, no part of the given area can be drawn onto, so this
  22720. method can be used to optimise a component's paint() method, by letting it
  22721. avoid drawing complex objects that aren't within the region being repainted.
  22722. */
  22723. bool clipRegionIntersects (const Rectangle<int>& area) const;
  22724. /** Intersects the current clipping region with another region.
  22725. @returns true if the resulting clipping region is non-zero in size
  22726. @see setOrigin, clipRegionIntersects
  22727. */
  22728. bool reduceClipRegion (int x, int y, int width, int height);
  22729. /** Intersects the current clipping region with another region.
  22730. @returns true if the resulting clipping region is non-zero in size
  22731. @see setOrigin, clipRegionIntersects
  22732. */
  22733. bool reduceClipRegion (const Rectangle<int>& area);
  22734. /** Intersects the current clipping region with a rectangle list region.
  22735. @returns true if the resulting clipping region is non-zero in size
  22736. @see setOrigin, clipRegionIntersects
  22737. */
  22738. bool reduceClipRegion (const RectangleList& clipRegion);
  22739. /** Intersects the current clipping region with a path.
  22740. @returns true if the resulting clipping region is non-zero in size
  22741. @see reduceClipRegion
  22742. */
  22743. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  22744. /** Intersects the current clipping region with an image's alpha-channel.
  22745. The current clipping path is intersected with the area covered by this image's
  22746. alpha-channel, after the image has been transformed by the specified matrix.
  22747. @param image the image whose alpha-channel should be used. If the image doesn't
  22748. have an alpha-channel, it is treated as entirely opaque.
  22749. @param transform a matrix to apply to the image
  22750. @returns true if the resulting clipping region is non-zero in size
  22751. @see reduceClipRegion
  22752. */
  22753. bool reduceClipRegion (const Image& image, const AffineTransform& transform);
  22754. /** Excludes a rectangle to stop it being drawn into. */
  22755. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  22756. /** Returns true if no drawing can be done because the clip region is zero. */
  22757. bool isClipEmpty() const;
  22758. /** Saves the current graphics state on an internal stack.
  22759. To restore the state, use restoreState().
  22760. @see ScopedSaveState
  22761. */
  22762. void saveState();
  22763. /** Restores a graphics state that was previously saved with saveState().
  22764. @see ScopedSaveState
  22765. */
  22766. void restoreState();
  22767. /** Uses RAII to save and restore the state of a graphics context.
  22768. On construction, this calls Graphics::saveState(), and on destruction it calls
  22769. Graphics::restoreState() on the Graphics object that you supply.
  22770. */
  22771. class ScopedSaveState
  22772. {
  22773. public:
  22774. ScopedSaveState (Graphics& g);
  22775. ~ScopedSaveState();
  22776. private:
  22777. Graphics& context;
  22778. JUCE_DECLARE_NON_COPYABLE (ScopedSaveState);
  22779. };
  22780. /** Begins rendering to an off-screen bitmap which will later be flattened onto the current
  22781. context with the given opacity.
  22782. The context uses an internal stack of temporary image layers to do this. When you've
  22783. finished drawing to the layer, call endTransparencyLayer() to complete the operation and
  22784. composite the finished layer. Every call to beginTransparencyLayer() MUST be matched
  22785. by a corresponding call to endTransparencyLayer()!
  22786. This call also saves the current state, and endTransparencyLayer() restores it.
  22787. */
  22788. void beginTransparencyLayer (float layerOpacity);
  22789. /** Completes a drawing operation to a temporary semi-transparent buffer.
  22790. See beginTransparencyLayer() for more details.
  22791. */
  22792. void endTransparencyLayer();
  22793. /** Moves the position of the context's origin.
  22794. This changes the position that the context considers to be (0, 0) to
  22795. the specified position.
  22796. So if you call setOrigin (100, 100), then the position that was previously
  22797. referred to as (100, 100) will subsequently be considered to be (0, 0).
  22798. @see reduceClipRegion, addTransform
  22799. */
  22800. void setOrigin (int newOriginX, int newOriginY);
  22801. /** Adds a transformation which will be performed on all the graphics operations that
  22802. the context subsequently performs.
  22803. After calling this, all the coordinates that are passed into the context will be
  22804. transformed by this matrix.
  22805. @see setOrigin
  22806. */
  22807. void addTransform (const AffineTransform& transform);
  22808. /** Resets the current colour, brush, and font to default settings. */
  22809. void resetToDefaultState();
  22810. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  22811. bool isVectorDevice() const;
  22812. /** Create a graphics that uses a given low-level renderer.
  22813. For internal use only.
  22814. NB. The context will NOT be deleted by this object when it is deleted.
  22815. */
  22816. Graphics (LowLevelGraphicsContext* internalContext) noexcept;
  22817. /** @internal */
  22818. LowLevelGraphicsContext* getInternalContext() const noexcept { return context; }
  22819. private:
  22820. LowLevelGraphicsContext* const context;
  22821. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  22822. bool saveStatePending;
  22823. void saveStateIfPending();
  22824. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Graphics);
  22825. };
  22826. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  22827. /*** End of inlined file: juce_Graphics.h ***/
  22828. /**
  22829. A graphical effect filter that can be applied to components.
  22830. An ImageEffectFilter can be applied to the image that a component
  22831. paints before it hits the screen.
  22832. This is used for adding effects like shadows, blurs, etc.
  22833. @see Component::setComponentEffect
  22834. */
  22835. class JUCE_API ImageEffectFilter
  22836. {
  22837. public:
  22838. /** Overridden to render the effect.
  22839. The implementation of this method must use the image that is passed in
  22840. as its source, and should render its output to the graphics context passed in.
  22841. @param sourceImage the image that the source component has just rendered with
  22842. its paint() method. The image may or may not have an alpha
  22843. channel, depending on whether the component is opaque.
  22844. @param destContext the graphics context to use to draw the resultant image.
  22845. @param alpha the alpha with which to draw the resultant image to the
  22846. target context
  22847. */
  22848. virtual void applyEffect (Image& sourceImage,
  22849. Graphics& destContext,
  22850. float alpha) = 0;
  22851. /** Destructor. */
  22852. virtual ~ImageEffectFilter() {}
  22853. };
  22854. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  22855. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  22856. /*** Start of inlined file: juce_Image.h ***/
  22857. #ifndef __JUCE_IMAGE_JUCEHEADER__
  22858. #define __JUCE_IMAGE_JUCEHEADER__
  22859. /**
  22860. Holds a fixed-size bitmap.
  22861. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  22862. To draw into an image, create a Graphics object for it.
  22863. e.g. @code
  22864. // create a transparent 500x500 image..
  22865. Image myImage (Image::RGB, 500, 500, true);
  22866. Graphics g (myImage);
  22867. g.setColour (Colours::red);
  22868. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  22869. @endcode
  22870. Other useful ways to create an image are with the ImageCache class, or the
  22871. ImageFileFormat, which provides a way to load common image files.
  22872. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  22873. */
  22874. class JUCE_API Image
  22875. {
  22876. public:
  22877. /**
  22878. */
  22879. enum PixelFormat
  22880. {
  22881. UnknownFormat,
  22882. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  22883. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  22884. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  22885. };
  22886. /**
  22887. */
  22888. enum ImageType
  22889. {
  22890. SoftwareImage = 0,
  22891. NativeImage
  22892. };
  22893. /** Creates a null image. */
  22894. Image();
  22895. /** Creates an image with a specified size and format.
  22896. @param format the number of colour channels in the image
  22897. @param imageWidth the desired width of the image, in pixels - this value must be
  22898. greater than zero (otherwise a width of 1 will be used)
  22899. @param imageHeight the desired width of the image, in pixels - this value must be
  22900. greater than zero (otherwise a height of 1 will be used)
  22901. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  22902. or transparent black (if it's ARGB). If false, the image may contain
  22903. junk initially, so you need to make sure you overwrite it thoroughly.
  22904. @param type the type of image - this lets you specify whether you want a purely
  22905. memory-based image, or one that may be managed by the OS if possible.
  22906. */
  22907. Image (PixelFormat format,
  22908. int imageWidth,
  22909. int imageHeight,
  22910. bool clearImage,
  22911. ImageType type = NativeImage);
  22912. /** Creates a shared reference to another image.
  22913. This won't create a duplicate of the image - when Image objects are copied, they simply
  22914. point to the same shared image data. To make sure that an Image object has its own unique,
  22915. unshared internal data, call duplicateIfShared().
  22916. */
  22917. Image (const Image& other);
  22918. /** Makes this image refer to the same underlying image as another object.
  22919. This won't create a duplicate of the image - when Image objects are copied, they simply
  22920. point to the same shared image data. To make sure that an Image object has its own unique,
  22921. unshared internal data, call duplicateIfShared().
  22922. */
  22923. Image& operator= (const Image&);
  22924. /** Destructor. */
  22925. ~Image();
  22926. /** Returns true if the two images are referring to the same internal, shared image. */
  22927. bool operator== (const Image& other) const noexcept { return image == other.image; }
  22928. /** Returns true if the two images are not referring to the same internal, shared image. */
  22929. bool operator!= (const Image& other) const noexcept { return image != other.image; }
  22930. /** Returns true if this image isn't null.
  22931. If you create an Image with the default constructor, it has no size or content, and is null
  22932. until you reassign it to an Image which contains some actual data.
  22933. The isNull() method is the opposite of isValid().
  22934. @see isNull
  22935. */
  22936. inline bool isValid() const noexcept { return image != nullptr; }
  22937. /** Returns true if this image is not valid.
  22938. If you create an Image with the default constructor, it has no size or content, and is null
  22939. until you reassign it to an Image which contains some actual data.
  22940. The isNull() method is the opposite of isValid().
  22941. @see isValid
  22942. */
  22943. inline bool isNull() const noexcept { return image == nullptr; }
  22944. /** A null Image object that can be used when you need to return an invalid image.
  22945. This object is the equivalient to an Image created with the default constructor.
  22946. */
  22947. static const Image null;
  22948. /** Returns the image's width (in pixels). */
  22949. int getWidth() const noexcept { return image == nullptr ? 0 : image->width; }
  22950. /** Returns the image's height (in pixels). */
  22951. int getHeight() const noexcept { return image == nullptr ? 0 : image->height; }
  22952. /** Returns a rectangle with the same size as this image.
  22953. The rectangle's origin is always (0, 0).
  22954. */
  22955. const Rectangle<int> getBounds() const noexcept { return image == nullptr ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  22956. /** Returns the image's pixel format. */
  22957. PixelFormat getFormat() const noexcept { return image == nullptr ? UnknownFormat : image->format; }
  22958. /** True if the image's format is ARGB. */
  22959. bool isARGB() const noexcept { return getFormat() == ARGB; }
  22960. /** True if the image's format is RGB. */
  22961. bool isRGB() const noexcept { return getFormat() == RGB; }
  22962. /** True if the image's format is a single-channel alpha map. */
  22963. bool isSingleChannel() const noexcept { return getFormat() == SingleChannel; }
  22964. /** True if the image contains an alpha-channel. */
  22965. bool hasAlphaChannel() const noexcept { return getFormat() != RGB; }
  22966. /** Clears a section of the image with a given colour.
  22967. This won't do any alpha-blending - it just sets all pixels in the image to
  22968. the given colour (which may be non-opaque if the image has an alpha channel).
  22969. */
  22970. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  22971. /** Returns a rescaled version of this image.
  22972. A new image is returned which is a copy of this one, rescaled to the given size.
  22973. Note that if the new size is identical to the existing image, this will just return
  22974. a reference to the original image, and won't actually create a duplicate.
  22975. */
  22976. Image rescaled (int newWidth, int newHeight,
  22977. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  22978. /** Returns a version of this image with a different image format.
  22979. A new image is returned which has been converted to the specified format.
  22980. Note that if the new format is no different to the current one, this will just return
  22981. a reference to the original image, and won't actually create a copy.
  22982. */
  22983. Image convertedToFormat (PixelFormat newFormat) const;
  22984. /** Makes sure that no other Image objects share the same underlying data as this one.
  22985. If no other Image objects refer to the same shared data as this one, this method has no
  22986. effect. But if there are other references to the data, this will create a new copy of
  22987. the data internally.
  22988. Call this if you want to draw onto the image, but want to make sure that this doesn't
  22989. affect any other code that may be sharing the same data.
  22990. @see getReferenceCount
  22991. */
  22992. void duplicateIfShared();
  22993. /** Returns an image which refers to a subsection of this image.
  22994. This will not make a copy of the original - the new image will keep a reference to it, so that
  22995. if the original image is changed, the contents of the subsection will also change. Likewise if you
  22996. draw into the subimage, you'll also be drawing onto that area of the original image. Note that if
  22997. you use operator= to make the original Image object refer to something else, the subsection image
  22998. won't pick up this change, it'll remain pointing at the original.
  22999. The area passed-in will be clipped to the bounds of this image, so this may return a smaller
  23000. image than the area you asked for, or even a null image if the area was out-of-bounds.
  23001. */
  23002. Image getClippedImage (const Rectangle<int>& area) const;
  23003. /** Returns the colour of one of the pixels in the image.
  23004. If the co-ordinates given are beyond the image's boundaries, this will
  23005. return Colours::transparentBlack.
  23006. @see setPixelAt, Image::BitmapData::getPixelColour
  23007. */
  23008. const Colour getPixelAt (int x, int y) const;
  23009. /** Sets the colour of one of the image's pixels.
  23010. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  23011. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  23012. with the given one. The colour's opacity will be ignored if this image doesn't have
  23013. an alpha-channel.
  23014. @see getPixelAt, Image::BitmapData::setPixelColour
  23015. */
  23016. void setPixelAt (int x, int y, const Colour& colour);
  23017. /** Changes the opacity of a pixel.
  23018. This only has an effect if the image has an alpha channel and if the
  23019. given co-ordinates are inside the image's boundary.
  23020. The multiplier must be in the range 0 to 1.0, and the current alpha
  23021. at the given co-ordinates will be multiplied by this value.
  23022. @see setPixelAt
  23023. */
  23024. void multiplyAlphaAt (int x, int y, float multiplier);
  23025. /** Changes the overall opacity of the image.
  23026. This will multiply the alpha value of each pixel in the image by the given
  23027. amount (limiting the resulting alpha values between 0 and 255). This allows
  23028. you to make an image more or less transparent.
  23029. If the image doesn't have an alpha channel, this won't have any effect.
  23030. */
  23031. void multiplyAllAlphas (float amountToMultiplyBy);
  23032. /** Changes all the colours to be shades of grey, based on their current luminosity.
  23033. */
  23034. void desaturate();
  23035. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  23036. You should only use this class as a last resort - messing about with the internals of
  23037. an image is only recommended for people who really know what they're doing!
  23038. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  23039. hanging around while the image is being used elsewhere.
  23040. Depending on the way the image class is implemented, this may create a temporary buffer
  23041. which is copied back to the image when the object is deleted, or it may just get a pointer
  23042. directly into the image's raw data.
  23043. You can use the stride and data values in this class directly, but don't alter them!
  23044. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  23045. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  23046. */
  23047. class BitmapData
  23048. {
  23049. public:
  23050. enum ReadWriteMode
  23051. {
  23052. readOnly,
  23053. writeOnly,
  23054. readWrite
  23055. };
  23056. BitmapData (Image& image, int x, int y, int w, int h, ReadWriteMode mode);
  23057. BitmapData (const Image& image, int x, int y, int w, int h);
  23058. BitmapData (const Image& image, ReadWriteMode mode);
  23059. ~BitmapData();
  23060. /** Returns a pointer to the start of a line in the image.
  23061. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  23062. sure it's not out-of-range.
  23063. */
  23064. inline uint8* getLinePointer (int y) const noexcept { return data + y * lineStride; }
  23065. /** Returns a pointer to a pixel in the image.
  23066. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  23067. not out-of-range.
  23068. */
  23069. inline uint8* getPixelPointer (int x, int y) const noexcept { return data + y * lineStride + x * pixelStride; }
  23070. /** Returns the colour of a given pixel.
  23071. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  23072. repsonsibility to make sure they're within the image's size.
  23073. */
  23074. const Colour getPixelColour (int x, int y) const noexcept;
  23075. /** Sets the colour of a given pixel.
  23076. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  23077. repsonsibility to make sure they're within the image's size.
  23078. */
  23079. void setPixelColour (int x, int y, const Colour& colour) const noexcept;
  23080. uint8* data;
  23081. PixelFormat pixelFormat;
  23082. int lineStride, pixelStride, width, height;
  23083. /** Used internally by custom image types to manage pixel data lifetime. */
  23084. class BitmapDataReleaser
  23085. {
  23086. protected:
  23087. BitmapDataReleaser() {}
  23088. public:
  23089. virtual ~BitmapDataReleaser() {}
  23090. };
  23091. ScopedPointer<BitmapDataReleaser> dataReleaser;
  23092. private:
  23093. JUCE_DECLARE_NON_COPYABLE (BitmapData);
  23094. };
  23095. /** Copies some pixel values to a rectangle of the image.
  23096. The format of the pixel data must match that of the image itself, and the
  23097. rectangle supplied must be within the image's bounds.
  23098. */
  23099. void setPixelData (int destX, int destY, int destW, int destH,
  23100. const uint8* sourcePixelData, int sourceLineStride);
  23101. /** Copies a section of the image to somewhere else within itself. */
  23102. void moveImageSection (int destX, int destY,
  23103. int sourceX, int sourceY,
  23104. int width, int height);
  23105. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  23106. of the image.
  23107. @param result the list that will have the area added to it
  23108. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  23109. above this level will be considered opaque
  23110. */
  23111. void createSolidAreaMask (RectangleList& result,
  23112. float alphaThreshold = 0.5f) const;
  23113. /** Returns a NamedValueSet that is attached to the image and which can be used for
  23114. associating custom values with it.
  23115. If this is a null image, this will return a null pointer.
  23116. */
  23117. NamedValueSet* getProperties() const;
  23118. /** Creates a context suitable for drawing onto this image.
  23119. Don't call this method directly! It's used internally by the Graphics class.
  23120. */
  23121. LowLevelGraphicsContext* createLowLevelContext() const;
  23122. /** Returns the number of Image objects which are currently referring to the same internal
  23123. shared image data.
  23124. @see duplicateIfShared
  23125. */
  23126. int getReferenceCount() const noexcept { return image == nullptr ? 0 : image->getReferenceCount(); }
  23127. /** This is a base class for task-specific types of image.
  23128. Don't use this class directly! It's used internally by the Image class.
  23129. */
  23130. class SharedImage : public ReferenceCountedObject
  23131. {
  23132. public:
  23133. SharedImage (PixelFormat format, int width, int height);
  23134. ~SharedImage();
  23135. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  23136. virtual SharedImage* clone() = 0;
  23137. virtual ImageType getType() const = 0;
  23138. virtual void initialiseBitmapData (BitmapData& bitmapData, int x, int y, BitmapData::ReadWriteMode mode) = 0;
  23139. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  23140. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  23141. const PixelFormat getPixelFormat() const noexcept { return format; }
  23142. int getWidth() const noexcept { return width; }
  23143. int getHeight() const noexcept { return height; }
  23144. protected:
  23145. friend class Image;
  23146. friend class BitmapData;
  23147. const PixelFormat format;
  23148. const int width, height;
  23149. NamedValueSet userData;
  23150. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedImage);
  23151. };
  23152. /** @internal */
  23153. SharedImage* getSharedImage() const noexcept { return image; }
  23154. /** @internal */
  23155. explicit Image (SharedImage* instance);
  23156. private:
  23157. friend class SharedImage;
  23158. friend class BitmapData;
  23159. ReferenceCountedObjectPtr<SharedImage> image;
  23160. JUCE_LEAK_DETECTOR (Image);
  23161. };
  23162. #endif // __JUCE_IMAGE_JUCEHEADER__
  23163. /*** End of inlined file: juce_Image.h ***/
  23164. /*** Start of inlined file: juce_RectangleList.h ***/
  23165. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  23166. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  23167. /**
  23168. Maintains a set of rectangles as a complex region.
  23169. This class allows a set of rectangles to be treated as a solid shape, and can
  23170. add and remove rectangular sections of it, and simplify overlapping or
  23171. adjacent rectangles.
  23172. @see Rectangle
  23173. */
  23174. class JUCE_API RectangleList
  23175. {
  23176. public:
  23177. /** Creates an empty RectangleList */
  23178. RectangleList() noexcept;
  23179. /** Creates a copy of another list */
  23180. RectangleList (const RectangleList& other);
  23181. /** Creates a list containing just one rectangle. */
  23182. RectangleList (const Rectangle<int>& rect);
  23183. /** Copies this list from another one. */
  23184. RectangleList& operator= (const RectangleList& other);
  23185. /** Destructor. */
  23186. ~RectangleList();
  23187. /** Returns true if the region is empty. */
  23188. bool isEmpty() const noexcept;
  23189. /** Returns the number of rectangles in the list. */
  23190. int getNumRectangles() const noexcept { return rects.size(); }
  23191. /** Returns one of the rectangles at a particular index.
  23192. @returns the rectangle at the index, or an empty rectangle if the
  23193. index is out-of-range.
  23194. */
  23195. Rectangle<int> getRectangle (int index) const noexcept;
  23196. /** Removes all rectangles to leave an empty region. */
  23197. void clear();
  23198. /** Merges a new rectangle into the list.
  23199. The rectangle being added will first be clipped to remove any parts of it
  23200. that overlap existing rectangles in the list.
  23201. */
  23202. void add (int x, int y, int width, int height);
  23203. /** Merges a new rectangle into the list.
  23204. The rectangle being added will first be clipped to remove any parts of it
  23205. that overlap existing rectangles in the list, and adjacent rectangles will be
  23206. merged into it.
  23207. */
  23208. void add (const Rectangle<int>& rect);
  23209. /** Dumbly adds a rectangle to the list without checking for overlaps.
  23210. This simply adds the rectangle to the end, it doesn't merge it or remove
  23211. any overlapping bits.
  23212. */
  23213. void addWithoutMerging (const Rectangle<int>& rect);
  23214. /** Merges another rectangle list into this one.
  23215. Any overlaps between the two lists will be clipped, so that the result is
  23216. the union of both lists.
  23217. */
  23218. void add (const RectangleList& other);
  23219. /** Removes a rectangular region from the list.
  23220. Any rectangles in the list which overlap this will be clipped and subdivided
  23221. if necessary.
  23222. */
  23223. void subtract (const Rectangle<int>& rect);
  23224. /** Removes all areas in another RectangleList from this one.
  23225. Any rectangles in the list which overlap this will be clipped and subdivided
  23226. if necessary.
  23227. @returns true if the resulting list is non-empty.
  23228. */
  23229. bool subtract (const RectangleList& otherList);
  23230. /** Removes any areas of the region that lie outside a given rectangle.
  23231. Any rectangles in the list which overlap this will be clipped and subdivided
  23232. if necessary.
  23233. Returns true if the resulting region is not empty, false if it is empty.
  23234. @see getIntersectionWith
  23235. */
  23236. bool clipTo (const Rectangle<int>& rect);
  23237. /** Removes any areas of the region that lie outside a given rectangle list.
  23238. Any rectangles in this object which overlap the specified list will be clipped
  23239. and subdivided if necessary.
  23240. Returns true if the resulting region is not empty, false if it is empty.
  23241. @see getIntersectionWith
  23242. */
  23243. bool clipTo (const RectangleList& other);
  23244. /** Creates a region which is the result of clipping this one to a given rectangle.
  23245. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  23246. resulting region into the list whose reference is passed-in.
  23247. Returns true if the resulting region is not empty, false if it is empty.
  23248. @see clipTo
  23249. */
  23250. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  23251. /** Swaps the contents of this and another list.
  23252. This swaps their internal pointers, so is hugely faster than using copy-by-value
  23253. to swap them.
  23254. */
  23255. void swapWith (RectangleList& otherList) noexcept;
  23256. /** Checks whether the region contains a given point.
  23257. @returns true if the point lies within one of the rectangles in the list
  23258. */
  23259. bool containsPoint (int x, int y) const noexcept;
  23260. /** Checks whether the region contains the whole of a given rectangle.
  23261. @returns true all parts of the rectangle passed in lie within the region
  23262. defined by this object
  23263. @see intersectsRectangle, containsPoint
  23264. */
  23265. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  23266. /** Checks whether the region contains any part of a given rectangle.
  23267. @returns true if any part of the rectangle passed in lies within the region
  23268. defined by this object
  23269. @see containsRectangle
  23270. */
  23271. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const noexcept;
  23272. /** Checks whether this region intersects any part of another one.
  23273. @see intersectsRectangle
  23274. */
  23275. bool intersects (const RectangleList& other) const noexcept;
  23276. /** Returns the smallest rectangle that can enclose the whole of this region. */
  23277. Rectangle<int> getBounds() const noexcept;
  23278. /** Optimises the list into a minimum number of constituent rectangles.
  23279. This will try to combine any adjacent rectangles into larger ones where
  23280. possible, to simplify lists that might have been fragmented by repeated
  23281. add/subtract calls.
  23282. */
  23283. void consolidate();
  23284. /** Adds an x and y value to all the co-ordinates. */
  23285. void offsetAll (int dx, int dy) noexcept;
  23286. /** Creates a Path object to represent this region. */
  23287. Path toPath() const;
  23288. /** An iterator for accessing all the rectangles in a RectangleList. */
  23289. class JUCE_API Iterator
  23290. {
  23291. public:
  23292. Iterator (const RectangleList& list) noexcept;
  23293. ~Iterator();
  23294. /** Advances to the next rectangle, and returns true if it's not finished.
  23295. Call this before using getRectangle() to find the rectangle that was returned.
  23296. */
  23297. bool next() noexcept;
  23298. /** Returns the current rectangle. */
  23299. const Rectangle<int>* getRectangle() const noexcept { return current; }
  23300. private:
  23301. const Rectangle<int>* current;
  23302. const RectangleList& owner;
  23303. int index;
  23304. JUCE_DECLARE_NON_COPYABLE (Iterator);
  23305. };
  23306. private:
  23307. friend class Iterator;
  23308. Array <Rectangle<int> > rects;
  23309. JUCE_LEAK_DETECTOR (RectangleList);
  23310. };
  23311. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  23312. /*** End of inlined file: juce_RectangleList.h ***/
  23313. /*** Start of inlined file: juce_BorderSize.h ***/
  23314. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  23315. #define __JUCE_BORDERSIZE_JUCEHEADER__
  23316. /**
  23317. Specifies a set of gaps to be left around the sides of a rectangle.
  23318. This is basically the size of the spaces at the top, bottom, left and right of
  23319. a rectangle. It's used by various component classes to specify borders.
  23320. @see Rectangle
  23321. */
  23322. template <typename ValueType>
  23323. class BorderSize
  23324. {
  23325. public:
  23326. /** Creates a null border.
  23327. All sizes are left as 0.
  23328. */
  23329. BorderSize() noexcept
  23330. : top(), left(), bottom(), right()
  23331. {
  23332. }
  23333. /** Creates a copy of another border. */
  23334. BorderSize (const BorderSize& other) noexcept
  23335. : top (other.top), left (other.left), bottom (other.bottom), right (other.right)
  23336. {
  23337. }
  23338. /** Creates a border with the given gaps. */
  23339. BorderSize (ValueType topGap, ValueType leftGap, ValueType bottomGap, ValueType rightGap) noexcept
  23340. : top (topGap), left (leftGap), bottom (bottomGap), right (rightGap)
  23341. {
  23342. }
  23343. /** Creates a border with the given gap on all sides. */
  23344. explicit BorderSize (ValueType allGaps) noexcept
  23345. : top (allGaps), left (allGaps), bottom (allGaps), right (allGaps)
  23346. {
  23347. }
  23348. /** Returns the gap that should be left at the top of the region. */
  23349. ValueType getTop() const noexcept { return top; }
  23350. /** Returns the gap that should be left at the top of the region. */
  23351. ValueType getLeft() const noexcept { return left; }
  23352. /** Returns the gap that should be left at the top of the region. */
  23353. ValueType getBottom() const noexcept { return bottom; }
  23354. /** Returns the gap that should be left at the top of the region. */
  23355. ValueType getRight() const noexcept { return right; }
  23356. /** Returns the sum of the top and bottom gaps. */
  23357. ValueType getTopAndBottom() const noexcept { return top + bottom; }
  23358. /** Returns the sum of the left and right gaps. */
  23359. ValueType getLeftAndRight() const noexcept { return left + right; }
  23360. /** Returns true if this border has no thickness along any edge. */
  23361. bool isEmpty() const noexcept { return left + right + top + bottom == ValueType(); }
  23362. /** Changes the top gap. */
  23363. void setTop (ValueType newTopGap) noexcept { top = newTopGap; }
  23364. /** Changes the left gap. */
  23365. void setLeft (ValueType newLeftGap) noexcept { left = newLeftGap; }
  23366. /** Changes the bottom gap. */
  23367. void setBottom (ValueType newBottomGap) noexcept { bottom = newBottomGap; }
  23368. /** Changes the right gap. */
  23369. void setRight (ValueType newRightGap) noexcept { right = newRightGap; }
  23370. /** Returns a rectangle with these borders removed from it. */
  23371. Rectangle<ValueType> subtractedFrom (const Rectangle<ValueType>& original) const noexcept
  23372. {
  23373. return Rectangle<ValueType> (original.getX() + left,
  23374. original.getY() + top,
  23375. original.getWidth() - (left + right),
  23376. original.getHeight() - (top + bottom));
  23377. }
  23378. /** Removes this border from a given rectangle. */
  23379. void subtractFrom (Rectangle<ValueType>& rectangle) const noexcept
  23380. {
  23381. rectangle = subtractedFrom (rectangle);
  23382. }
  23383. /** Returns a rectangle with these borders added around it. */
  23384. Rectangle<ValueType> addedTo (const Rectangle<ValueType>& original) const noexcept
  23385. {
  23386. return Rectangle<ValueType> (original.getX() - left,
  23387. original.getY() - top,
  23388. original.getWidth() + (left + right),
  23389. original.getHeight() + (top + bottom));
  23390. }
  23391. /** Adds this border around a given rectangle. */
  23392. void addTo (Rectangle<ValueType>& rectangle) const noexcept
  23393. {
  23394. rectangle = addedTo (rectangle);
  23395. }
  23396. bool operator== (const BorderSize& other) const noexcept
  23397. {
  23398. return top == other.top && left == other.left && bottom == other.bottom && right == other.right;
  23399. }
  23400. bool operator!= (const BorderSize& other) const noexcept
  23401. {
  23402. return ! operator== (other);
  23403. }
  23404. private:
  23405. ValueType top, left, bottom, right;
  23406. JUCE_LEAK_DETECTOR (BorderSize);
  23407. };
  23408. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  23409. /*** End of inlined file: juce_BorderSize.h ***/
  23410. /*** Start of inlined file: juce_ModalComponentManager.h ***/
  23411. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23412. #define __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23413. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  23414. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23415. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23416. /**
  23417. Classes derived from this will be automatically deleted when the application exits.
  23418. After JUCEApplication::shutdown() has been called, any objects derived from
  23419. DeletedAtShutdown which are still in existence will be deleted in the reverse
  23420. order to that in which they were created.
  23421. So if you've got a singleton and don't want to have to explicitly delete it, just
  23422. inherit from this and it'll be taken care of.
  23423. */
  23424. class JUCE_API DeletedAtShutdown
  23425. {
  23426. protected:
  23427. /** Creates a DeletedAtShutdown object. */
  23428. DeletedAtShutdown();
  23429. /** Destructor.
  23430. It's ok to delete these objects explicitly - it's only the ones left
  23431. dangling at the end that will be deleted automatically.
  23432. */
  23433. virtual ~DeletedAtShutdown();
  23434. public:
  23435. /** Deletes all extant objects.
  23436. This shouldn't be used by applications, as it's called automatically
  23437. in the shutdown code of the JUCEApplication class.
  23438. */
  23439. static void deleteAll();
  23440. private:
  23441. static Array <DeletedAtShutdown*>& getObjects();
  23442. JUCE_DECLARE_NON_COPYABLE (DeletedAtShutdown);
  23443. };
  23444. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23445. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  23446. /**
  23447. Manages the system's stack of modal components.
  23448. Normally you'll just use the Component methods to invoke modal states in components,
  23449. and won't have to deal with this class directly, but this is the singleton object that's
  23450. used internally to manage the stack.
  23451. @see Component::enterModalState, Component::exitModalState, Component::isCurrentlyModal,
  23452. Component::getCurrentlyModalComponent, Component::isCurrentlyBlockedByAnotherModalComponent
  23453. */
  23454. class JUCE_API ModalComponentManager : public AsyncUpdater,
  23455. public DeletedAtShutdown
  23456. {
  23457. public:
  23458. /** Receives callbacks when a modal component is dismissed.
  23459. You can register a callback using Component::enterModalState() or
  23460. ModalComponentManager::attachCallback().
  23461. For some quick ways of creating callback objects, see the ModalCallbackFunction class.
  23462. @see ModalCallbackFunction
  23463. */
  23464. class Callback
  23465. {
  23466. public:
  23467. /** */
  23468. Callback() {}
  23469. /** Destructor. */
  23470. virtual ~Callback() {}
  23471. /** Called to indicate that a modal component has been dismissed.
  23472. You can register a callback using Component::enterModalState() or
  23473. ModalComponentManager::attachCallback().
  23474. The returnValue parameter is the value that was passed to Component::exitModalState()
  23475. when the component was dismissed.
  23476. The callback object will be deleted shortly after this method is called.
  23477. */
  23478. virtual void modalStateFinished (int returnValue) = 0;
  23479. };
  23480. /** Returns the number of components currently being shown modally.
  23481. @see getModalComponent
  23482. */
  23483. int getNumModalComponents() const;
  23484. /** Returns one of the components being shown modally.
  23485. An index of 0 is the most recently-shown, topmost component.
  23486. */
  23487. Component* getModalComponent (int index) const;
  23488. /** Returns true if the specified component is in a modal state. */
  23489. bool isModal (Component* component) const;
  23490. /** Returns true if the specified component is currently the topmost modal component. */
  23491. bool isFrontModalComponent (Component* component) const;
  23492. /** Adds a new callback that will be called when the specified modal component is dismissed.
  23493. If the component is modal, then when it is dismissed, either by being hidden, or by calling
  23494. Component::exitModalState(), then the Callback::modalStateFinished() method will be
  23495. called.
  23496. Each component can have any number of callbacks associated with it, and this one is added
  23497. to that list.
  23498. The object that is passed in will be deleted by the manager when it's no longer needed. If
  23499. the given component is not currently modal, the callback object is deleted immediately and
  23500. no action is taken.
  23501. */
  23502. void attachCallback (Component* component, Callback* callback);
  23503. /** Brings any modal components to the front. */
  23504. void bringModalComponentsToFront (bool topOneShouldGrabFocus = true);
  23505. #if JUCE_MODAL_LOOPS_PERMITTED
  23506. /** Runs the event loop until the currently topmost modal component is dismissed, and
  23507. returns the exit code for that component.
  23508. */
  23509. int runEventLoopForCurrentComponent();
  23510. #endif
  23511. juce_DeclareSingleton_SingleThreaded_Minimal (ModalComponentManager);
  23512. protected:
  23513. /** Creates a ModalComponentManager.
  23514. You shouldn't ever call the constructor - it's a singleton, so use ModalComponentManager::getInstance()
  23515. */
  23516. ModalComponentManager();
  23517. /** Destructor. */
  23518. ~ModalComponentManager();
  23519. /** @internal */
  23520. void handleAsyncUpdate();
  23521. private:
  23522. class ModalItem;
  23523. class ReturnValueRetriever;
  23524. friend class Component;
  23525. friend class OwnedArray <ModalItem>;
  23526. OwnedArray <ModalItem> stack;
  23527. void startModal (Component* component);
  23528. void endModal (Component* component, int returnValue);
  23529. void endModal (Component* component);
  23530. JUCE_DECLARE_NON_COPYABLE (ModalComponentManager);
  23531. };
  23532. /**
  23533. This class provides some handy utility methods for creating ModalComponentManager::Callback
  23534. objects that will invoke a static function with some parameters when a modal component is dismissed.
  23535. */
  23536. class ModalCallbackFunction
  23537. {
  23538. public:
  23539. /** This is a utility function to create a ModalComponentManager::Callback that will
  23540. call a static function with a parameter.
  23541. The function that you supply must take two parameters - the first being an int, which is
  23542. the result code that was used when the modal component was dismissed, and the second
  23543. can be a custom type. Note that this custom value will be copied and stored, so it must
  23544. be a primitive type or a class that provides copy-by-value semantics.
  23545. E.g. @code
  23546. static void myCallbackFunction (int modalResult, double customValue)
  23547. {
  23548. if (modalResult == 1)
  23549. doSomethingWith (customValue);
  23550. }
  23551. Component* someKindOfComp;
  23552. ...
  23553. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0));
  23554. @endcode
  23555. @see ModalComponentManager::Callback
  23556. */
  23557. template <typename ParamType>
  23558. static ModalComponentManager::Callback* create (void (*functionToCall) (int, ParamType),
  23559. ParamType parameterValue)
  23560. {
  23561. return new FunctionCaller1 <ParamType> (functionToCall, parameterValue);
  23562. }
  23563. /** This is a utility function to create a ModalComponentManager::Callback that will
  23564. call a static function with two custom parameters.
  23565. The function that you supply must take three parameters - the first being an int, which is
  23566. the result code that was used when the modal component was dismissed, and the next two are
  23567. your custom types. Note that these custom values will be copied and stored, so they must
  23568. be primitive types or classes that provide copy-by-value semantics.
  23569. E.g. @code
  23570. static void myCallbackFunction (int modalResult, double customValue1, String customValue2)
  23571. {
  23572. if (modalResult == 1)
  23573. doSomethingWith (customValue1, customValue2);
  23574. }
  23575. Component* someKindOfComp;
  23576. ...
  23577. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0, String ("xyz")));
  23578. @endcode
  23579. @see ModalComponentManager::Callback
  23580. */
  23581. template <typename ParamType1, typename ParamType2>
  23582. static ModalComponentManager::Callback* withParam (void (*functionToCall) (int, ParamType1, ParamType2),
  23583. ParamType1 parameterValue1,
  23584. ParamType2 parameterValue2)
  23585. {
  23586. return new FunctionCaller2 <ParamType1, ParamType2> (functionToCall, parameterValue1, parameterValue2);
  23587. }
  23588. /** This is a utility function to create a ModalComponentManager::Callback that will
  23589. call a static function with a component.
  23590. The function that you supply must take two parameters - the first being an int, which is
  23591. the result code that was used when the modal component was dismissed, and the second
  23592. can be a Component class. The component will be stored as a WeakReference, so that if it gets
  23593. deleted before this callback is invoked, the pointer that is passed to the function will be null.
  23594. E.g. @code
  23595. static void myCallbackFunction (int modalResult, Slider* mySlider)
  23596. {
  23597. if (modalResult == 1 && mySlider != nullptr) // (must check that mySlider isn't null in case it was deleted..)
  23598. mySlider->setValue (0.0);
  23599. }
  23600. Component* someKindOfComp;
  23601. Slider* mySlider;
  23602. ...
  23603. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider));
  23604. @endcode
  23605. @see ModalComponentManager::Callback
  23606. */
  23607. template <class ComponentType>
  23608. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*),
  23609. ComponentType* component)
  23610. {
  23611. return new ComponentCaller1 <ComponentType> (functionToCall, component);
  23612. }
  23613. /** Creates a ModalComponentManager::Callback that will call a static function with a component.
  23614. The function that you supply must take three parameters - the first being an int, which is
  23615. the result code that was used when the modal component was dismissed, the second being a Component
  23616. class, and the third being a custom type (which must be a primitive type or have copy-by-value semantics).
  23617. The component will be stored as a WeakReference, so that if it gets deleted before this callback is
  23618. invoked, the pointer that is passed into the function will be null.
  23619. E.g. @code
  23620. static void myCallbackFunction (int modalResult, Slider* mySlider, String customParam)
  23621. {
  23622. if (modalResult == 1 && mySlider != nullptr) // (must check that mySlider isn't null in case it was deleted..)
  23623. mySlider->setName (customParam);
  23624. }
  23625. Component* someKindOfComp;
  23626. Slider* mySlider;
  23627. ...
  23628. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider, String ("hello")));
  23629. @endcode
  23630. @see ModalComponentManager::Callback
  23631. */
  23632. template <class ComponentType, typename ParamType>
  23633. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*, ParamType),
  23634. ComponentType* component,
  23635. ParamType param)
  23636. {
  23637. return new ComponentCaller2 <ComponentType, ParamType> (functionToCall, component, param);
  23638. }
  23639. private:
  23640. template <typename ParamType>
  23641. class FunctionCaller1 : public ModalComponentManager::Callback
  23642. {
  23643. public:
  23644. typedef void (*FunctionType) (int, ParamType);
  23645. FunctionCaller1 (FunctionType& function_, ParamType& param_)
  23646. : function (function_), param (param_) {}
  23647. void modalStateFinished (int returnValue) { function (returnValue, param); }
  23648. private:
  23649. const FunctionType function;
  23650. ParamType param;
  23651. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller1);
  23652. };
  23653. template <typename ParamType1, typename ParamType2>
  23654. class FunctionCaller2 : public ModalComponentManager::Callback
  23655. {
  23656. public:
  23657. typedef void (*FunctionType) (int, ParamType1, ParamType2);
  23658. FunctionCaller2 (FunctionType& function_, ParamType1& param1_, ParamType2& param2_)
  23659. : function (function_), param1 (param1_), param2 (param2_) {}
  23660. void modalStateFinished (int returnValue) { function (returnValue, param1, param2); }
  23661. private:
  23662. const FunctionType function;
  23663. ParamType1 param1;
  23664. ParamType2 param2;
  23665. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller2);
  23666. };
  23667. template <typename ComponentType>
  23668. class ComponentCaller1 : public ModalComponentManager::Callback
  23669. {
  23670. public:
  23671. typedef void (*FunctionType) (int, ComponentType*);
  23672. ComponentCaller1 (FunctionType& function_, ComponentType* comp_)
  23673. : function (function_), comp (comp_) {}
  23674. void modalStateFinished (int returnValue)
  23675. {
  23676. function (returnValue, static_cast <ComponentType*> (comp.get()));
  23677. }
  23678. private:
  23679. const FunctionType function;
  23680. WeakReference<Component> comp;
  23681. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller1);
  23682. };
  23683. template <typename ComponentType, typename ParamType1>
  23684. class ComponentCaller2 : public ModalComponentManager::Callback
  23685. {
  23686. public:
  23687. typedef void (*FunctionType) (int, ComponentType*, ParamType1);
  23688. ComponentCaller2 (FunctionType& function_, ComponentType* comp_, ParamType1 param1_)
  23689. : function (function_), comp (comp_), param1 (param1_) {}
  23690. void modalStateFinished (int returnValue)
  23691. {
  23692. function (returnValue, static_cast <ComponentType*> (comp.get()), param1);
  23693. }
  23694. private:
  23695. const FunctionType function;
  23696. WeakReference<Component> comp;
  23697. ParamType1 param1;
  23698. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller2);
  23699. };
  23700. ModalCallbackFunction();
  23701. ~ModalCallbackFunction();
  23702. JUCE_DECLARE_NON_COPYABLE (ModalCallbackFunction);
  23703. };
  23704. #endif // __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23705. /*** End of inlined file: juce_ModalComponentManager.h ***/
  23706. class LookAndFeel;
  23707. class MouseInputSource;
  23708. class MouseInputSourceInternal;
  23709. class ComponentPeer;
  23710. class MarkerList;
  23711. class RelativeRectangle;
  23712. /**
  23713. The base class for all JUCE user-interface objects.
  23714. */
  23715. class JUCE_API Component : public MouseListener
  23716. {
  23717. public:
  23718. /** Creates a component.
  23719. To get it to actually appear, you'll also need to:
  23720. - Either add it to a parent component or use the addToDesktop() method to
  23721. make it a desktop window
  23722. - Set its size and position to something sensible
  23723. - Use setVisible() to make it visible
  23724. And for it to serve any useful purpose, you'll need to write a
  23725. subclass of Component or use one of the other types of component from
  23726. the library.
  23727. */
  23728. Component();
  23729. /** Destructor.
  23730. Note that when a component is deleted, any child components it contains are NOT
  23731. automatically deleted. It's your responsibilty to manage their lifespan - you
  23732. may want to use helper methods like deleteAllChildren(), or less haphazard
  23733. approaches like using ScopedPointers or normal object aggregation to manage them.
  23734. If the component being deleted is currently the child of another one, then during
  23735. deletion, it will be removed from its parent, and the parent will receive a childrenChanged()
  23736. callback. Any ComponentListener objects that have registered with it will also have their
  23737. ComponentListener::componentBeingDeleted() methods called.
  23738. */
  23739. virtual ~Component();
  23740. /** Creates a component, setting its name at the same time.
  23741. @see getName, setName
  23742. */
  23743. explicit Component (const String& componentName);
  23744. /** Returns the name of this component.
  23745. @see setName
  23746. */
  23747. const String& getName() const noexcept { return componentName; }
  23748. /** Sets the name of this component.
  23749. When the name changes, all registered ComponentListeners will receive a
  23750. ComponentListener::componentNameChanged() callback.
  23751. @see getName
  23752. */
  23753. virtual void setName (const String& newName);
  23754. /** Returns the ID string that was set by setComponentID().
  23755. @see setComponentID
  23756. */
  23757. const String& getComponentID() const noexcept { return componentID; }
  23758. /** Sets the component's ID string.
  23759. You can retrieve the ID using getComponentID().
  23760. @see getComponentID
  23761. */
  23762. void setComponentID (const String& newID);
  23763. /** Makes the component visible or invisible.
  23764. This method will show or hide the component.
  23765. Note that components default to being non-visible when first created.
  23766. Also note that visible components won't be seen unless all their parent components
  23767. are also visible.
  23768. This method will call visibilityChanged() and also componentVisibilityChanged()
  23769. for any component listeners that are interested in this component.
  23770. @param shouldBeVisible whether to show or hide the component
  23771. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  23772. */
  23773. virtual void setVisible (bool shouldBeVisible);
  23774. /** Tests whether the component is visible or not.
  23775. this doesn't necessarily tell you whether this comp is actually on the screen
  23776. because this depends on whether all the parent components are also visible - use
  23777. isShowing() to find this out.
  23778. @see isShowing, setVisible
  23779. */
  23780. bool isVisible() const noexcept { return flags.visibleFlag; }
  23781. /** Called when this component's visiblility changes.
  23782. @see setVisible, isVisible
  23783. */
  23784. virtual void visibilityChanged();
  23785. /** Tests whether this component and all its parents are visible.
  23786. @returns true only if this component and all its parents are visible.
  23787. @see isVisible
  23788. */
  23789. bool isShowing() const;
  23790. /** Makes this component appear as a window on the desktop.
  23791. Note that before calling this, you should make sure that the component's opacity is
  23792. set correctly using setOpaque(). If the component is non-opaque, the windowing
  23793. system will try to create a special transparent window for it, which will generally take
  23794. a lot more CPU to operate (and might not even be possible on some platforms).
  23795. If the component is inside a parent component at the time this method is called, it
  23796. will be first be removed from that parent. Likewise if a component on the desktop
  23797. is subsequently added to another component, it'll be removed from the desktop.
  23798. @param windowStyleFlags a combination of the flags specified in the
  23799. ComponentPeer::StyleFlags enum, which define the
  23800. window's characteristics.
  23801. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  23802. in which the juce component should place itself. On Windows,
  23803. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  23804. supported on all platforms, and best left as 0 unless you know
  23805. what you're doing
  23806. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  23807. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  23808. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  23809. */
  23810. virtual void addToDesktop (int windowStyleFlags,
  23811. void* nativeWindowToAttachTo = nullptr);
  23812. /** If the component is currently showing on the desktop, this will hide it.
  23813. You can also use setVisible() to hide a desktop window temporarily, but
  23814. removeFromDesktop() will free any system resources that are being used up.
  23815. @see addToDesktop, isOnDesktop
  23816. */
  23817. void removeFromDesktop();
  23818. /** Returns true if this component is currently showing on the desktop.
  23819. @see addToDesktop, removeFromDesktop
  23820. */
  23821. bool isOnDesktop() const noexcept;
  23822. /** Returns the heavyweight window that contains this component.
  23823. If this component is itself on the desktop, this will return the window
  23824. object that it is using. Otherwise, it will return the window of
  23825. its top-level parent component.
  23826. This may return 0 if there isn't a desktop component.
  23827. @see addToDesktop, isOnDesktop
  23828. */
  23829. ComponentPeer* getPeer() const;
  23830. /** For components on the desktop, this is called if the system wants to close the window.
  23831. This is a signal that either the user or the system wants the window to close. The
  23832. default implementation of this method will trigger an assertion to warn you that your
  23833. component should do something about it, but you can override this to ignore the event
  23834. if you want.
  23835. */
  23836. virtual void userTriedToCloseWindow();
  23837. /** Called for a desktop component which has just been minimised or un-minimised.
  23838. This will only be called for components on the desktop.
  23839. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  23840. */
  23841. virtual void minimisationStateChanged (bool isNowMinimised);
  23842. /** Brings the component to the front of its siblings.
  23843. If some of the component's siblings have had their 'always-on-top' flag set,
  23844. then they will still be kept in front of this one (unless of course this
  23845. one is also 'always-on-top').
  23846. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  23847. to the component (see grabKeyboardFocus() for more details)
  23848. @see toBack, toBehind, setAlwaysOnTop
  23849. */
  23850. void toFront (bool shouldAlsoGainFocus);
  23851. /** Changes this component's z-order to be at the back of all its siblings.
  23852. If the component is set to be 'always-on-top', it will only be moved to the
  23853. back of the other other 'always-on-top' components.
  23854. @see toFront, toBehind, setAlwaysOnTop
  23855. */
  23856. void toBack();
  23857. /** Changes this component's z-order so that it's just behind another component.
  23858. @see toFront, toBack
  23859. */
  23860. void toBehind (Component* other);
  23861. /** Sets whether the component should always be kept at the front of its siblings.
  23862. @see isAlwaysOnTop
  23863. */
  23864. void setAlwaysOnTop (bool shouldStayOnTop);
  23865. /** Returns true if this component is set to always stay in front of its siblings.
  23866. @see setAlwaysOnTop
  23867. */
  23868. bool isAlwaysOnTop() const noexcept;
  23869. /** Returns the x coordinate of the component's left edge.
  23870. This is a distance in pixels from the left edge of the component's parent.
  23871. Note that if you've used setTransform() to apply a transform, then the component's
  23872. bounds will no longer be a direct reflection of the position at which it appears within
  23873. its parent, as the transform will be applied to its bounding box.
  23874. */
  23875. inline int getX() const noexcept { return bounds.getX(); }
  23876. /** Returns the y coordinate of the top of this component.
  23877. This is a distance in pixels from the top edge of the component's parent.
  23878. Note that if you've used setTransform() to apply a transform, then the component's
  23879. bounds will no longer be a direct reflection of the position at which it appears within
  23880. its parent, as the transform will be applied to its bounding box.
  23881. */
  23882. inline int getY() const noexcept { return bounds.getY(); }
  23883. /** Returns the component's width in pixels. */
  23884. inline int getWidth() const noexcept { return bounds.getWidth(); }
  23885. /** Returns the component's height in pixels. */
  23886. inline int getHeight() const noexcept { return bounds.getHeight(); }
  23887. /** Returns the x coordinate of the component's right-hand edge.
  23888. This is a distance in pixels from the left edge of the component's parent.
  23889. Note that if you've used setTransform() to apply a transform, then the component's
  23890. bounds will no longer be a direct reflection of the position at which it appears within
  23891. its parent, as the transform will be applied to its bounding box.
  23892. */
  23893. int getRight() const noexcept { return bounds.getRight(); }
  23894. /** Returns the component's top-left position as a Point. */
  23895. Point<int> getPosition() const noexcept { return bounds.getPosition(); }
  23896. /** Returns the y coordinate of the bottom edge of this component.
  23897. This is a distance in pixels from the top edge of the component's parent.
  23898. Note that if you've used setTransform() to apply a transform, then the component's
  23899. bounds will no longer be a direct reflection of the position at which it appears within
  23900. its parent, as the transform will be applied to its bounding box.
  23901. */
  23902. int getBottom() const noexcept { return bounds.getBottom(); }
  23903. /** Returns this component's bounding box.
  23904. The rectangle returned is relative to the top-left of the component's parent.
  23905. Note that if you've used setTransform() to apply a transform, then the component's
  23906. bounds will no longer be a direct reflection of the position at which it appears within
  23907. its parent, as the transform will be applied to its bounding box.
  23908. */
  23909. const Rectangle<int>& getBounds() const noexcept { return bounds; }
  23910. /** Returns the component's bounds, relative to its own origin.
  23911. This is like getBounds(), but returns the rectangle in local coordinates, In practice, it'll
  23912. return a rectangle with position (0, 0), and the same size as this component.
  23913. */
  23914. Rectangle<int> getLocalBounds() const noexcept;
  23915. /** Returns the area of this component's parent which this component covers.
  23916. The returned area is relative to the parent's coordinate space.
  23917. If the component has an affine transform specified, then the resulting area will be
  23918. the smallest rectangle that fully covers the component's transformed bounding box.
  23919. If this component has no parent, the return value will simply be the same as getBounds().
  23920. */
  23921. Rectangle<int> getBoundsInParent() const noexcept;
  23922. /** Returns the region of this component that's not obscured by other, opaque components.
  23923. The RectangleList that is returned represents the area of this component
  23924. which isn't covered by opaque child components.
  23925. If includeSiblings is true, it will also take into account any siblings
  23926. that may be overlapping the component.
  23927. */
  23928. void getVisibleArea (RectangleList& result,
  23929. bool includeSiblings) const;
  23930. /** Returns this component's x coordinate relative the the screen's top-left origin.
  23931. @see getX, localPointToGlobal
  23932. */
  23933. int getScreenX() const;
  23934. /** Returns this component's y coordinate relative the the screen's top-left origin.
  23935. @see getY, localPointToGlobal
  23936. */
  23937. int getScreenY() const;
  23938. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  23939. @see getScreenBounds
  23940. */
  23941. Point<int> getScreenPosition() const;
  23942. /** Returns the bounds of this component, relative to the screen's top-left.
  23943. @see getScreenPosition
  23944. */
  23945. Rectangle<int> getScreenBounds() const;
  23946. /** Converts a point to be relative to this component's coordinate space.
  23947. This takes a point relative to a different component, and returns its position relative to this
  23948. component. If the sourceComponent parameter is null, the source point is assumed to be a global
  23949. screen coordinate.
  23950. */
  23951. Point<int> getLocalPoint (const Component* sourceComponent,
  23952. const Point<int>& pointRelativeToSourceComponent) const;
  23953. /** Converts a rectangle to be relative to this component's coordinate space.
  23954. This takes a rectangle that is relative to a different component, and returns its position relative
  23955. to this component. If the sourceComponent parameter is null, the source rectangle is assumed to be
  23956. a screen coordinate.
  23957. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23958. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23959. the smallest rectangle that fully contains the transformed area.
  23960. */
  23961. Rectangle<int> getLocalArea (const Component* sourceComponent,
  23962. const Rectangle<int>& areaRelativeToSourceComponent) const;
  23963. /** Converts a point relative to this component's top-left into a screen coordinate.
  23964. @see getLocalPoint, localAreaToGlobal
  23965. */
  23966. Point<int> localPointToGlobal (const Point<int>& localPoint) const;
  23967. /** Converts a rectangle from this component's coordinate space to a screen coordinate.
  23968. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23969. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23970. the smallest rectangle that fully contains the transformed area.
  23971. @see getLocalPoint, localPointToGlobal
  23972. */
  23973. Rectangle<int> localAreaToGlobal (const Rectangle<int>& localArea) const;
  23974. /** Moves the component to a new position.
  23975. Changes the component's top-left position (without changing its size).
  23976. The position is relative to the top-left of the component's parent.
  23977. If the component actually moves, this method will make a synchronous call to moved().
  23978. Note that if you've used setTransform() to apply a transform, then the component's
  23979. bounds will no longer be a direct reflection of the position at which it appears within
  23980. its parent, as the transform will be applied to whatever bounds you set for it.
  23981. @see setBounds, ComponentListener::componentMovedOrResized
  23982. */
  23983. void setTopLeftPosition (int x, int y);
  23984. /** Moves the component to a new position.
  23985. Changes the position of the component's top-right corner (keeping it the same size).
  23986. The position is relative to the top-left of the component's parent.
  23987. If the component actually moves, this method will make a synchronous call to moved().
  23988. Note that if you've used setTransform() to apply a transform, then the component's
  23989. bounds will no longer be a direct reflection of the position at which it appears within
  23990. its parent, as the transform will be applied to whatever bounds you set for it.
  23991. */
  23992. void setTopRightPosition (int x, int y);
  23993. /** Changes the size of the component.
  23994. A synchronous call to resized() will be occur if the size actually changes.
  23995. Note that if you've used setTransform() to apply a transform, then the component's
  23996. bounds will no longer be a direct reflection of the position at which it appears within
  23997. its parent, as the transform will be applied to whatever bounds you set for it.
  23998. */
  23999. void setSize (int newWidth, int newHeight);
  24000. /** Changes the component's position and size.
  24001. The coordinates are relative to the top-left of the component's parent, or relative
  24002. to the origin of the screen is the component is on the desktop.
  24003. If this method changes the component's top-left position, it will make a synchronous
  24004. call to moved(). If it changes the size, it will also make a call to resized().
  24005. Note that if you've used setTransform() to apply a transform, then the component's
  24006. bounds will no longer be a direct reflection of the position at which it appears within
  24007. its parent, as the transform will be applied to whatever bounds you set for it.
  24008. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  24009. */
  24010. void setBounds (int x, int y, int width, int height);
  24011. /** Changes the component's position and size.
  24012. The coordinates are relative to the top-left of the component's parent, or relative
  24013. to the origin of the screen is the component is on the desktop.
  24014. If this method changes the component's top-left position, it will make a synchronous
  24015. call to moved(). If it changes the size, it will also make a call to resized().
  24016. Note that if you've used setTransform() to apply a transform, then the component's
  24017. bounds will no longer be a direct reflection of the position at which it appears within
  24018. its parent, as the transform will be applied to whatever bounds you set for it.
  24019. @see setBounds
  24020. */
  24021. void setBounds (const Rectangle<int>& newBounds);
  24022. /** Changes the component's position and size.
  24023. This is similar to the other setBounds() methods, but uses RelativeRectangle::applyToComponent()
  24024. to set the position, This uses a Component::Positioner to make sure that any dynamic
  24025. expressions are used in the RelativeRectangle will be automatically re-applied to the
  24026. component's bounds when the source values change. See RelativeRectangle::applyToComponent()
  24027. for more details.
  24028. When using relative expressions, the following symbols are available:
  24029. - "left", "right", "top", "bottom" refer to the position of those edges in this component, so
  24030. e.g. for a component whose width is always 100, you might set the right edge to the "left + 100".
  24031. - "[id].left", "[id].right", "[id].top", "[id].bottom", "[id].width", "[id].height", where [id] is
  24032. the identifier of one of this component's siblings. A component's identifier is set with
  24033. Component::setComponentID(). So for example if you want your component to always be 50 pixels to the
  24034. right of the one called "xyz", you could set your left edge to be "xyz.right + 50".
  24035. - Instead of an [id], you can use the name "parent" to refer to this component's parent. Like
  24036. any other component, these values are relative to their component's parent, so "parent.right" won't be
  24037. very useful for positioning a component because it refers to a position with the parent's parent.. but
  24038. "parent.width" can be used for setting positions relative to the parent's size. E.g. to make a 10x10
  24039. component which remains 1 pixel away from its parent's bottom-right, you could use
  24040. "right - 10, bottom - 10, parent.width - 1, parent.height - 1".
  24041. - The name of one of the parent component's markers can also be used as a symbol. For markers to be
  24042. used, the parent component must implement its Component::getMarkers() method, and return at least one
  24043. valid MarkerList. So if you want your component's top edge to be 10 pixels below the
  24044. marker called "foobar", you'd set it to "foobar + 10".
  24045. See the Expression class for details about the operators that are supported, but for example
  24046. if you wanted to make your component remain centred within its parent with a size of 100, 100,
  24047. you could express it as:
  24048. @code myComp.setBounds (RelativeBounds ("parent.width / 2 - 50, parent.height / 2 - 50, left + 100, top + 100"));
  24049. @endcode
  24050. ..or an alternative way to achieve the same thing:
  24051. @code myComp.setBounds (RelativeBounds ("right - 100, bottom - 100, parent.width / 2 + 50, parent.height / 2 + 50"));
  24052. @endcode
  24053. Or if you wanted a 100x100 component whose top edge is lined up to a marker called "topMarker" and
  24054. which is positioned 50 pixels to the right of another component called "otherComp", you could write:
  24055. @code myComp.setBounds (RelativeBounds ("otherComp.right + 50, topMarker, left + 100, top + 100"));
  24056. @endcode
  24057. Be careful not to make your coordinate expressions recursive, though, or exceptions and assertions will
  24058. be thrown!
  24059. @see setBounds, RelativeRectangle::applyToComponent(), Expression
  24060. */
  24061. void setBounds (const RelativeRectangle& newBounds);
  24062. /** Sets the component's bounds with an expression.
  24063. The string is parsed as a RelativeRectangle expression - see the notes for
  24064. Component::setBounds (const RelativeRectangle&) for more information. This method is
  24065. basically just a shortcut for writing setBounds (RelativeRectangle ("..."))
  24066. */
  24067. void setBounds (const String& newBoundsExpression);
  24068. /** Changes the component's position and size in terms of fractions of its parent's size.
  24069. The values are factors of the parent's size, so for example
  24070. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  24071. width and height of the parent, with its top-left position 20% of
  24072. the way across and down the parent.
  24073. @see setBounds
  24074. */
  24075. void setBoundsRelative (float proportionalX, float proportionalY,
  24076. float proportionalWidth, float proportionalHeight);
  24077. /** Changes the component's position and size based on the amount of space to leave around it.
  24078. This will position the component within its parent, leaving the specified number of
  24079. pixels around each edge.
  24080. @see setBounds
  24081. */
  24082. void setBoundsInset (const BorderSize<int>& borders);
  24083. /** Positions the component within a given rectangle, keeping its proportions
  24084. unchanged.
  24085. If onlyReduceInSize is false, the component will be resized to fill as much of the
  24086. rectangle as possible without changing its aspect ratio (the component's
  24087. current size is used to determine its aspect ratio, so a zero-size component
  24088. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  24089. too big to fit inside the rectangle.
  24090. It will then be positioned within the rectangle according to the justification flags
  24091. specified.
  24092. @see setBounds
  24093. */
  24094. void setBoundsToFit (int x, int y, int width, int height,
  24095. const Justification& justification,
  24096. bool onlyReduceInSize);
  24097. /** Changes the position of the component's centre.
  24098. Leaves the component's size unchanged, but sets the position of its centre
  24099. relative to its parent's top-left.
  24100. @see setBounds
  24101. */
  24102. void setCentrePosition (int x, int y);
  24103. /** Changes the position of the component's centre.
  24104. Leaves the position unchanged, but positions its centre relative to its
  24105. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  24106. its parent.
  24107. */
  24108. void setCentreRelative (float x, float y);
  24109. /** Changes the component's size and centres it within its parent.
  24110. After changing the size, the component will be moved so that it's
  24111. centred within its parent. If the component is on the desktop (or has no
  24112. parent component), then it'll be centred within the main monitor area.
  24113. */
  24114. void centreWithSize (int width, int height);
  24115. /** Sets a transform matrix to be applied to this component.
  24116. If you set a transform for a component, the component's position will be warped by it, relative to
  24117. the component's parent's top-left origin. This means that the values you pass into setBounds() will no
  24118. longer reflect the actual area within the parent that the component covers, as the bounds will be
  24119. transformed and the component will probably end up actually appearing somewhere else within its parent.
  24120. When using transforms you need to be extremely careful when converting coordinates between the
  24121. coordinate spaces of different components or the screen - you should always use getLocalPoint(),
  24122. getLocalArea(), etc to do this, and never just manually add a component's position to a point in order to
  24123. convert it between different components (but I'm sure you would never have done that anyway...).
  24124. Currently, transforms are not supported for desktop windows, so the transform will be ignored if you
  24125. put a component on the desktop.
  24126. To remove a component's transform, simply pass AffineTransform::identity as the parameter to this method.
  24127. */
  24128. void setTransform (const AffineTransform& transform);
  24129. /** Returns the transform that is currently being applied to this component.
  24130. For more details about transforms, see setTransform().
  24131. @see setTransform
  24132. */
  24133. AffineTransform getTransform() const;
  24134. /** Returns true if a non-identity transform is being applied to this component.
  24135. For more details about transforms, see setTransform().
  24136. @see setTransform
  24137. */
  24138. bool isTransformed() const noexcept;
  24139. /** Returns a proportion of the component's width.
  24140. This is a handy equivalent of (getWidth() * proportion).
  24141. */
  24142. int proportionOfWidth (float proportion) const noexcept;
  24143. /** Returns a proportion of the component's height.
  24144. This is a handy equivalent of (getHeight() * proportion).
  24145. */
  24146. int proportionOfHeight (float proportion) const noexcept;
  24147. /** Returns the width of the component's parent.
  24148. If the component has no parent (i.e. if it's on the desktop), this will return
  24149. the width of the screen.
  24150. */
  24151. int getParentWidth() const noexcept;
  24152. /** Returns the height of the component's parent.
  24153. If the component has no parent (i.e. if it's on the desktop), this will return
  24154. the height of the screen.
  24155. */
  24156. int getParentHeight() const noexcept;
  24157. /** Returns the screen coordinates of the monitor that contains this component.
  24158. If there's only one monitor, this will return its size - if there are multiple
  24159. monitors, it will return the area of the monitor that contains the component's
  24160. centre.
  24161. */
  24162. Rectangle<int> getParentMonitorArea() const;
  24163. /** Returns the number of child components that this component contains.
  24164. @see getChildComponent, getIndexOfChildComponent
  24165. */
  24166. int getNumChildComponents() const noexcept;
  24167. /** Returns one of this component's child components, by it index.
  24168. The component with index 0 is at the back of the z-order, the one at the
  24169. front will have index (getNumChildComponents() - 1).
  24170. If the index is out-of-range, this will return a null pointer.
  24171. @see getNumChildComponents, getIndexOfChildComponent
  24172. */
  24173. Component* getChildComponent (int index) const noexcept;
  24174. /** Returns the index of this component in the list of child components.
  24175. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  24176. values are further towards the front.
  24177. Returns -1 if the component passed-in is not a child of this component.
  24178. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  24179. */
  24180. int getIndexOfChildComponent (const Component* child) const noexcept;
  24181. /** Adds a child component to this one.
  24182. Adding a child component does not mean that the component will own or delete the child - it's
  24183. your responsibility to delete the component. Note that it's safe to delete a component
  24184. without first removing it from its parent - doing so will automatically remove it and
  24185. send out the appropriate notifications before the deletion completes.
  24186. If the child is already a child of this component, then no action will be taken, and its
  24187. z-order will be left unchanged.
  24188. @param child the new component to add. If the component passed-in is already
  24189. the child of another component, it'll first be removed from it current parent.
  24190. @param zOrder The index in the child-list at which this component should be inserted.
  24191. A value of -1 will insert it in front of the others, 0 is the back.
  24192. @see removeChildComponent, addAndMakeVisible, getChild, ComponentListener::componentChildrenChanged
  24193. */
  24194. void addChildComponent (Component* child, int zOrder = -1);
  24195. /** Adds a child component to this one, and also makes the child visible if it isn't.
  24196. Quite a useful function, this is just the same as calling setVisible (true) on the child
  24197. and then addChildComponent(). See addChildComponent() for more details.
  24198. */
  24199. void addAndMakeVisible (Component* child, int zOrder = -1);
  24200. /** Removes one of this component's child-components.
  24201. If the child passed-in isn't actually a child of this component (either because
  24202. it's invalid or is the child of a different parent), then no action is taken.
  24203. Note that removing a child will not delete it! But it's ok to delete a component
  24204. without first removing it - doing so will automatically remove it and send out the
  24205. appropriate notifications before the deletion completes.
  24206. @see addChildComponent, ComponentListener::componentChildrenChanged
  24207. */
  24208. void removeChildComponent (Component* childToRemove);
  24209. /** Removes one of this component's child-components by index.
  24210. This will return a pointer to the component that was removed, or null if
  24211. the index was out-of-range.
  24212. Note that removing a child will not delete it! But it's ok to delete a component
  24213. without first removing it - doing so will automatically remove it and send out the
  24214. appropriate notifications before the deletion completes.
  24215. @see addChildComponent, ComponentListener::componentChildrenChanged
  24216. */
  24217. Component* removeChildComponent (int childIndexToRemove);
  24218. /** Removes all this component's children.
  24219. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  24220. */
  24221. void removeAllChildren();
  24222. /** Removes all this component's children, and deletes them.
  24223. @see removeAllChildren
  24224. */
  24225. void deleteAllChildren();
  24226. /** Returns the component which this component is inside.
  24227. If this is the highest-level component or hasn't yet been added to
  24228. a parent, this will return null.
  24229. */
  24230. Component* getParentComponent() const noexcept { return parentComponent; }
  24231. /** Searches the parent components for a component of a specified class.
  24232. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  24233. component that can be dynamically cast to a MyComp, or will return 0 if none
  24234. of the parents are suitable.
  24235. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  24236. */
  24237. template <class TargetClass>
  24238. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = nullptr) const
  24239. {
  24240. (void) dummyParameter;
  24241. Component* p = parentComponent;
  24242. while (p != nullptr)
  24243. {
  24244. TargetClass* target = dynamic_cast <TargetClass*> (p);
  24245. if (target != nullptr)
  24246. return target;
  24247. p = p->parentComponent;
  24248. }
  24249. return nullptr;
  24250. }
  24251. /** Returns the highest-level component which contains this one or its parents.
  24252. This will search upwards in the parent-hierarchy from this component, until it
  24253. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  24254. not yet added to a parent), and will return that.
  24255. */
  24256. Component* getTopLevelComponent() const noexcept;
  24257. /** Checks whether a component is anywhere inside this component or its children.
  24258. This will recursively check through this component's children to see if the
  24259. given component is anywhere inside.
  24260. */
  24261. bool isParentOf (const Component* possibleChild) const noexcept;
  24262. /** Called to indicate that the component's parents have changed.
  24263. When a component is added or removed from its parent, this method will
  24264. be called on all of its children (recursively - so all children of its
  24265. children will also be called as well).
  24266. Subclasses can override this if they need to react to this in some way.
  24267. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  24268. */
  24269. virtual void parentHierarchyChanged();
  24270. /** Subclasses can use this callback to be told when children are added or removed.
  24271. @see parentHierarchyChanged
  24272. */
  24273. virtual void childrenChanged();
  24274. /** Tests whether a given point inside the component.
  24275. Overriding this method allows you to create components which only intercept
  24276. mouse-clicks within a user-defined area.
  24277. This is called to find out whether a particular x, y coordinate is
  24278. considered to be inside the component or not, and is used by methods such
  24279. as contains() and getComponentAt() to work out which component
  24280. the mouse is clicked on.
  24281. Components with custom shapes will probably want to override it to perform
  24282. some more complex hit-testing.
  24283. The default implementation of this method returns either true or false,
  24284. depending on the value that was set by calling setInterceptsMouseClicks() (true
  24285. is the default return value).
  24286. Note that the hit-test region is not related to the opacity with which
  24287. areas of a component are painted.
  24288. Applications should never call hitTest() directly - instead use the
  24289. contains() method, because this will also test for occlusion by the
  24290. component's parent.
  24291. Note that for components on the desktop, this method will be ignored, because it's
  24292. not always possible to implement this behaviour on all platforms.
  24293. @param x the x coordinate to test, relative to the left hand edge of this
  24294. component. This value is guaranteed to be greater than or equal to
  24295. zero, and less than the component's width
  24296. @param y the y coordinate to test, relative to the top edge of this
  24297. component. This value is guaranteed to be greater than or equal to
  24298. zero, and less than the component's height
  24299. @returns true if the click is considered to be inside the component
  24300. @see setInterceptsMouseClicks, contains
  24301. */
  24302. virtual bool hitTest (int x, int y);
  24303. /** Changes the default return value for the hitTest() method.
  24304. Setting this to false is an easy way to make a component pass its mouse-clicks
  24305. through to the components behind it.
  24306. When a component is created, the default setting for this is true.
  24307. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  24308. return false (or true for child components if allowClicksOnChildComponents
  24309. is true)
  24310. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  24311. components can be clicked on as normal but clicks on this component pass
  24312. straight through; if this is false and allowClicksOnThisComponent
  24313. is false, then neither this component nor any child components can
  24314. be clicked on
  24315. @see hitTest, getInterceptsMouseClicks
  24316. */
  24317. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  24318. bool allowClicksOnChildComponents) noexcept;
  24319. /** Retrieves the current state of the mouse-click interception flags.
  24320. On return, the two parameters are set to the state used in the last call to
  24321. setInterceptsMouseClicks().
  24322. @see setInterceptsMouseClicks
  24323. */
  24324. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  24325. bool& allowsClicksOnChildComponents) const noexcept;
  24326. /** Returns true if a given point lies within this component or one of its children.
  24327. Never override this method! Use hitTest to create custom hit regions.
  24328. @param localPoint the coordinate to test, relative to this component's top-left.
  24329. @returns true if the point is within the component's hit-test area, but only if
  24330. that part of the component isn't clipped by its parent component. Note
  24331. that this won't take into account any overlapping sibling components
  24332. which might be in the way - for that, see reallyContains()
  24333. @see hitTest, reallyContains, getComponentAt
  24334. */
  24335. bool contains (const Point<int>& localPoint);
  24336. /** Returns true if a given point lies in this component, taking any overlapping
  24337. siblings into account.
  24338. @param localPoint the coordinate to test, relative to this component's top-left.
  24339. @param returnTrueIfWithinAChild if the point actually lies within a child of this component,
  24340. this determines whether that is counted as a hit.
  24341. @see contains, getComponentAt
  24342. */
  24343. bool reallyContains (const Point<int>& localPoint, bool returnTrueIfWithinAChild);
  24344. /** Returns the component at a certain point within this one.
  24345. @param x the x coordinate to test, relative to this component's left edge.
  24346. @param y the y coordinate to test, relative to this component's top edge.
  24347. @returns the component that is at this position - which may be 0, this component,
  24348. or one of its children. Note that overlapping siblings that might actually
  24349. be in the way are not taken into account by this method - to account for these,
  24350. instead call getComponentAt on the top-level parent of this component.
  24351. @see hitTest, contains, reallyContains
  24352. */
  24353. Component* getComponentAt (int x, int y);
  24354. /** Returns the component at a certain point within this one.
  24355. @param position the coordinate to test, relative to this component's top-left.
  24356. @returns the component that is at this position - which may be 0, this component,
  24357. or one of its children. Note that overlapping siblings that might actually
  24358. be in the way are not taken into account by this method - to account for these,
  24359. instead call getComponentAt on the top-level parent of this component.
  24360. @see hitTest, contains, reallyContains
  24361. */
  24362. Component* getComponentAt (const Point<int>& position);
  24363. /** Marks the whole component as needing to be redrawn.
  24364. Calling this will not do any repainting immediately, but will mark the component
  24365. as 'dirty'. At some point in the near future the operating system will send a paint
  24366. message, which will redraw all the dirty regions of all components.
  24367. There's no guarantee about how soon after calling repaint() the redraw will actually
  24368. happen, and other queued events may be delivered before a redraw is done.
  24369. If the setBufferedToImage() method has been used to cause this component
  24370. to use a buffer, the repaint() call will invalidate the component's buffer.
  24371. To redraw just a subsection of the component rather than the whole thing,
  24372. use the repaint (int, int, int, int) method.
  24373. @see paint
  24374. */
  24375. void repaint();
  24376. /** Marks a subsection of this component as needing to be redrawn.
  24377. Calling this will not do any repainting immediately, but will mark the given region
  24378. of the component as 'dirty'. At some point in the near future the operating system
  24379. will send a paint message, which will redraw all the dirty regions of all components.
  24380. There's no guarantee about how soon after calling repaint() the redraw will actually
  24381. happen, and other queued events may be delivered before a redraw is done.
  24382. The region that is passed in will be clipped to keep it within the bounds of this
  24383. component.
  24384. @see repaint()
  24385. */
  24386. void repaint (int x, int y, int width, int height);
  24387. /** Marks a subsection of this component as needing to be redrawn.
  24388. Calling this will not do any repainting immediately, but will mark the given region
  24389. of the component as 'dirty'. At some point in the near future the operating system
  24390. will send a paint message, which will redraw all the dirty regions of all components.
  24391. There's no guarantee about how soon after calling repaint() the redraw will actually
  24392. happen, and other queued events may be delivered before a redraw is done.
  24393. The region that is passed in will be clipped to keep it within the bounds of this
  24394. component.
  24395. @see repaint()
  24396. */
  24397. void repaint (const Rectangle<int>& area);
  24398. /** Makes the component use an internal buffer to optimise its redrawing.
  24399. Setting this flag to true will cause the component to allocate an
  24400. internal buffer into which it paints itself, so that when asked to
  24401. redraw itself, it can use this buffer rather than actually calling the
  24402. paint() method.
  24403. The buffer is kept until the repaint() method is called directly on
  24404. this component (or until it is resized), when the image is invalidated
  24405. and then redrawn the next time the component is painted.
  24406. Note that only the drawing that happens within the component's paint()
  24407. method is drawn into the buffer, it's child components are not buffered, and
  24408. nor is the paintOverChildren() method.
  24409. @see repaint, paint, createComponentSnapshot
  24410. */
  24411. void setBufferedToImage (bool shouldBeBuffered);
  24412. /** Generates a snapshot of part of this component.
  24413. This will return a new Image, the size of the rectangle specified,
  24414. containing a snapshot of the specified area of the component and all
  24415. its children.
  24416. The image may or may not have an alpha-channel, depending on whether the
  24417. image is opaque or not.
  24418. If the clipImageToComponentBounds parameter is true and the area is greater than
  24419. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  24420. then parts of the component beyond its bounds can be drawn.
  24421. @see paintEntireComponent
  24422. */
  24423. Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  24424. bool clipImageToComponentBounds = true);
  24425. /** Draws this component and all its subcomponents onto the specified graphics
  24426. context.
  24427. You should very rarely have to use this method, it's simply there in case you need
  24428. to draw a component with a custom graphics context for some reason, e.g. for
  24429. creating a snapshot of the component.
  24430. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  24431. on its children in order to render the entire tree.
  24432. The graphics context may be left in an undefined state after this method returns,
  24433. so you may need to reset it if you're going to use it again.
  24434. If ignoreAlphaLevel is false, then the component will be drawn with the opacity level
  24435. specified by getAlpha(); if ignoreAlphaLevel is true, then this will be ignored and
  24436. an alpha of 1.0 will be used.
  24437. */
  24438. void paintEntireComponent (Graphics& context, bool ignoreAlphaLevel);
  24439. /** This allows you to indicate that this component doesn't require its graphics
  24440. context to be clipped when it is being painted.
  24441. Most people will never need to use this setting, but in situations where you have a very large
  24442. number of simple components being rendered, and where they are guaranteed never to do any drawing
  24443. beyond their own boundaries, setting this to true will reduce the overhead involved in clipping
  24444. the graphics context that gets passed to the component's paint() callback.
  24445. If you enable this mode, you'll need to make sure your paint method doesn't call anything like
  24446. Graphics::fillAll(), and doesn't draw beyond the component's bounds, because that'll produce
  24447. artifacts. Your component also can't have any child components that may be placed beyond its
  24448. bounds.
  24449. */
  24450. void setPaintingIsUnclipped (bool shouldPaintWithoutClipping) noexcept;
  24451. /** Adds an effect filter to alter the component's appearance.
  24452. When a component has an effect filter set, then this is applied to the
  24453. results of its paint() method. There are a few preset effects, such as
  24454. a drop-shadow or glow, but they can be user-defined as well.
  24455. The effect that is passed in will not be deleted by the component - the
  24456. caller must take care of deleting it.
  24457. To remove an effect from a component, pass a null pointer in as the parameter.
  24458. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  24459. */
  24460. void setComponentEffect (ImageEffectFilter* newEffect);
  24461. /** Returns the current component effect.
  24462. @see setComponentEffect
  24463. */
  24464. ImageEffectFilter* getComponentEffect() const noexcept { return effect; }
  24465. /** Finds the appropriate look-and-feel to use for this component.
  24466. If the component hasn't had a look-and-feel explicitly set, this will
  24467. return the parent's look-and-feel, or just the default one if there's no
  24468. parent.
  24469. @see setLookAndFeel, lookAndFeelChanged
  24470. */
  24471. LookAndFeel& getLookAndFeel() const noexcept;
  24472. /** Sets the look and feel to use for this component.
  24473. This will also change the look and feel for any child components that haven't
  24474. had their look set explicitly.
  24475. The object passed in will not be deleted by the component, so it's the caller's
  24476. responsibility to manage it. It may be used at any time until this component
  24477. has been deleted.
  24478. Calling this method will also invoke the sendLookAndFeelChange() method.
  24479. @see getLookAndFeel, lookAndFeelChanged
  24480. */
  24481. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  24482. /** Called to let the component react to a change in the look-and-feel setting.
  24483. When the look-and-feel is changed for a component, this will be called in
  24484. all its child components, recursively.
  24485. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  24486. an application uses a LookAndFeel class that might have changed internally.
  24487. @see sendLookAndFeelChange, getLookAndFeel
  24488. */
  24489. virtual void lookAndFeelChanged();
  24490. /** Calls the lookAndFeelChanged() method in this component and all its children.
  24491. This will recurse through the children and their children, calling lookAndFeelChanged()
  24492. on them all.
  24493. @see lookAndFeelChanged
  24494. */
  24495. void sendLookAndFeelChange();
  24496. /** Indicates whether any parts of the component might be transparent.
  24497. Components that always paint all of their contents with solid colour and
  24498. thus completely cover any components behind them should use this method
  24499. to tell the repaint system that they are opaque.
  24500. This information is used to optimise drawing, because it means that
  24501. objects underneath opaque windows don't need to be painted.
  24502. By default, components are considered transparent, unless this is used to
  24503. make it otherwise.
  24504. @see isOpaque, getVisibleArea
  24505. */
  24506. void setOpaque (bool shouldBeOpaque);
  24507. /** Returns true if no parts of this component are transparent.
  24508. @returns the value that was set by setOpaque, (the default being false)
  24509. @see setOpaque
  24510. */
  24511. bool isOpaque() const noexcept;
  24512. /** Indicates whether the component should be brought to the front when clicked.
  24513. Setting this flag to true will cause the component to be brought to the front
  24514. when the mouse is clicked somewhere inside it or its child components.
  24515. Note that a top-level desktop window might still be brought to the front by the
  24516. operating system when it's clicked, depending on how the OS works.
  24517. By default this is set to false.
  24518. @see setMouseClickGrabsKeyboardFocus
  24519. */
  24520. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) noexcept;
  24521. /** Indicates whether the component should be brought to the front when clicked-on.
  24522. @see setBroughtToFrontOnMouseClick
  24523. */
  24524. bool isBroughtToFrontOnMouseClick() const noexcept;
  24525. // Keyboard focus methods
  24526. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  24527. By default components aren't actually interested in gaining the
  24528. focus, but this method can be used to turn this on.
  24529. See the grabKeyboardFocus() method for details about the way a component
  24530. is chosen to receive the focus.
  24531. @see grabKeyboardFocus, getWantsKeyboardFocus
  24532. */
  24533. void setWantsKeyboardFocus (bool wantsFocus) noexcept;
  24534. /** Returns true if the component is interested in getting keyboard focus.
  24535. This returns the flag set by setWantsKeyboardFocus(). The default
  24536. setting is false.
  24537. @see setWantsKeyboardFocus
  24538. */
  24539. bool getWantsKeyboardFocus() const noexcept;
  24540. /** Chooses whether a click on this component automatically grabs the focus.
  24541. By default this is set to true, but you might want a component which can
  24542. be focused, but where you don't want the user to be able to affect it directly
  24543. by clicking.
  24544. */
  24545. void setMouseClickGrabsKeyboardFocus (bool shouldGrabFocus);
  24546. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  24547. See setMouseClickGrabsKeyboardFocus() for more info.
  24548. */
  24549. bool getMouseClickGrabsKeyboardFocus() const noexcept;
  24550. /** Tries to give keyboard focus to this component.
  24551. When the user clicks on a component or its grabKeyboardFocus()
  24552. method is called, the following procedure is used to work out which
  24553. component should get it:
  24554. - if the component that was clicked on actually wants focus (as indicated
  24555. by calling getWantsKeyboardFocus), it gets it.
  24556. - if the component itself doesn't want focus, it will try to pass it
  24557. on to whichever of its children is the default component, as determined by
  24558. KeyboardFocusTraverser::getDefaultComponent()
  24559. - if none of its children want focus at all, it will pass it up to its
  24560. parent instead, unless it's a top-level component without a parent,
  24561. in which case it just takes the focus itself.
  24562. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  24563. getCurrentlyFocusedComponent, focusGained, focusLost,
  24564. keyPressed, keyStateChanged
  24565. */
  24566. void grabKeyboardFocus();
  24567. /** Returns true if this component currently has the keyboard focus.
  24568. @param trueIfChildIsFocused if this is true, then the method returns true if
  24569. either this component or any of its children (recursively)
  24570. have the focus. If false, the method only returns true if
  24571. this component has the focus.
  24572. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  24573. focusGained, focusLost
  24574. */
  24575. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  24576. /** Returns the component that currently has the keyboard focus.
  24577. @returns the focused component, or null if nothing is focused.
  24578. */
  24579. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() noexcept;
  24580. /** Tries to move the keyboard focus to one of this component's siblings.
  24581. This will try to move focus to either the next or previous component. (This
  24582. is the method that is used when shifting focus by pressing the tab key).
  24583. Components for which getWantsKeyboardFocus() returns false are not looked at.
  24584. @param moveToNext if true, the focus will move forwards; if false, it will
  24585. move backwards
  24586. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  24587. */
  24588. void moveKeyboardFocusToSibling (bool moveToNext);
  24589. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  24590. which focus should be passed from this component.
  24591. The default implementation of this method will return a default
  24592. KeyboardFocusTraverser if this component is a focus container (as determined
  24593. by the setFocusContainer() method). If the component isn't a focus
  24594. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  24595. If you overrride this to return a custom KeyboardFocusTraverser, then
  24596. this component and all its sub-components will use the new object to
  24597. make their focusing decisions.
  24598. The method should return a new object, which the caller is required to
  24599. delete when no longer needed.
  24600. */
  24601. virtual KeyboardFocusTraverser* createFocusTraverser();
  24602. /** Returns the focus order of this component, if one has been specified.
  24603. By default components don't have a focus order - in that case, this
  24604. will return 0. Lower numbers indicate that the component will be
  24605. earlier in the focus traversal order.
  24606. To change the order, call setExplicitFocusOrder().
  24607. The focus order may be used by the KeyboardFocusTraverser class as part of
  24608. its algorithm for deciding the order in which components should be traversed.
  24609. See the KeyboardFocusTraverser class for more details on this.
  24610. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  24611. */
  24612. int getExplicitFocusOrder() const;
  24613. /** Sets the index used in determining the order in which focusable components
  24614. should be traversed.
  24615. A value of 0 or less is taken to mean that no explicit order is wanted, and
  24616. that traversal should use other factors, like the component's position.
  24617. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  24618. */
  24619. void setExplicitFocusOrder (int newFocusOrderIndex);
  24620. /** Indicates whether this component is a parent for components that can have
  24621. their focus traversed.
  24622. This flag is used by the default implementation of the createFocusTraverser()
  24623. method, which uses the flag to find the first parent component (of the currently
  24624. focused one) which wants to be a focus container.
  24625. So using this method to set the flag to 'true' causes this component to
  24626. act as the top level within which focus is passed around.
  24627. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  24628. */
  24629. void setFocusContainer (bool shouldBeFocusContainer) noexcept;
  24630. /** Returns true if this component has been marked as a focus container.
  24631. See setFocusContainer() for more details.
  24632. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  24633. */
  24634. bool isFocusContainer() const noexcept;
  24635. /** Returns true if the component (and all its parents) are enabled.
  24636. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  24637. what difference this makes to the component depends on the type. E.g. buttons
  24638. and sliders will choose to draw themselves differently, etc.
  24639. Note that if one of this component's parents is disabled, this will always
  24640. return false, even if this component itself is enabled.
  24641. @see setEnabled, enablementChanged
  24642. */
  24643. bool isEnabled() const noexcept;
  24644. /** Enables or disables this component.
  24645. Disabling a component will also cause all of its child components to become
  24646. disabled.
  24647. Similarly, enabling a component which is inside a disabled parent
  24648. component won't make any difference until the parent is re-enabled.
  24649. @see isEnabled, enablementChanged
  24650. */
  24651. void setEnabled (bool shouldBeEnabled);
  24652. /** Callback to indicate that this component has been enabled or disabled.
  24653. This can be triggered by one of the component's parent components
  24654. being enabled or disabled, as well as changes to the component itself.
  24655. The default implementation of this method does nothing; your class may
  24656. wish to repaint itself or something when this happens.
  24657. @see setEnabled, isEnabled
  24658. */
  24659. virtual void enablementChanged();
  24660. /** Changes the transparency of this component.
  24661. When painted, the entire component and all its children will be rendered
  24662. with this as the overall opacity level, where 0 is completely invisible, and
  24663. 1.0 is fully opaque (i.e. normal).
  24664. @see getAlpha
  24665. */
  24666. void setAlpha (float newAlpha);
  24667. /** Returns the component's current transparancy level.
  24668. See setAlpha() for more details.
  24669. */
  24670. float getAlpha() const;
  24671. /** Changes the mouse cursor shape to use when the mouse is over this component.
  24672. Note that the cursor set by this method can be overridden by the getMouseCursor
  24673. method.
  24674. @see MouseCursor
  24675. */
  24676. void setMouseCursor (const MouseCursor& cursorType);
  24677. /** Returns the mouse cursor shape to use when the mouse is over this component.
  24678. The default implementation will return the cursor that was set by setCursor()
  24679. but can be overridden for more specialised purposes, e.g. returning different
  24680. cursors depending on the mouse position.
  24681. @see MouseCursor
  24682. */
  24683. virtual const MouseCursor getMouseCursor();
  24684. /** Forces the current mouse cursor to be updated.
  24685. If you're overriding the getMouseCursor() method to control which cursor is
  24686. displayed, then this will only be checked each time the user moves the mouse. So
  24687. if you want to force the system to check that the cursor being displayed is
  24688. up-to-date (even if the mouse is just sitting there), call this method.
  24689. (If you're changing the cursor using setMouseCursor(), you don't need to bother
  24690. calling this).
  24691. */
  24692. void updateMouseCursor() const;
  24693. /** Components can override this method to draw their content.
  24694. The paint() method gets called when a region of a component needs redrawing,
  24695. either because the component's repaint() method has been called, or because
  24696. something has happened on the screen that means a section of a window needs
  24697. to be redrawn.
  24698. Any child components will draw themselves over whatever this method draws. If
  24699. you need to paint over the top of your child components, you can also implement
  24700. the paintOverChildren() method to do this.
  24701. If you want to cause a component to redraw itself, this is done asynchronously -
  24702. calling the repaint() method marks a region of the component as "dirty", and the
  24703. paint() method will automatically be called sometime later, by the message thread,
  24704. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  24705. you never redraw something synchronously.
  24706. You should never need to call this method directly - to take a snapshot of the
  24707. component you could use createComponentSnapshot() or paintEntireComponent().
  24708. @param g the graphics context that must be used to do the drawing operations.
  24709. @see repaint, paintOverChildren, Graphics
  24710. */
  24711. virtual void paint (Graphics& g);
  24712. /** Components can override this method to draw over the top of their children.
  24713. For most drawing operations, it's better to use the normal paint() method,
  24714. but if you need to overlay something on top of the children, this can be
  24715. used.
  24716. @see paint, Graphics
  24717. */
  24718. virtual void paintOverChildren (Graphics& g);
  24719. /** Called when the mouse moves inside this component.
  24720. If the mouse button isn't pressed and the mouse moves over a component,
  24721. this will be called to let the component react to this.
  24722. A component will always get a mouseEnter callback before a mouseMove.
  24723. @param e details about the position and status of the mouse event
  24724. @see mouseEnter, mouseExit, mouseDrag, contains
  24725. */
  24726. virtual void mouseMove (const MouseEvent& e);
  24727. /** Called when the mouse first enters this component.
  24728. If the mouse button isn't pressed and the mouse moves into a component,
  24729. this will be called to let the component react to this.
  24730. When the mouse button is pressed and held down while being moved in
  24731. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  24732. mouseDrag messages are sent to the component that the mouse was originally
  24733. clicked on, until the button is released.
  24734. If you're writing a component that needs to repaint itself when the mouse
  24735. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  24736. method.
  24737. @param e details about the position and status of the mouse event
  24738. @see mouseExit, mouseDrag, mouseMove, contains
  24739. */
  24740. virtual void mouseEnter (const MouseEvent& e);
  24741. /** Called when the mouse moves out of this component.
  24742. This will be called when the mouse moves off the edge of this
  24743. component.
  24744. If the mouse button was pressed, and it was then dragged off the
  24745. edge of the component and released, then this callback will happen
  24746. when the button is released, after the mouseUp callback.
  24747. If you're writing a component that needs to repaint itself when the mouse
  24748. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  24749. method.
  24750. @param e details about the position and status of the mouse event
  24751. @see mouseEnter, mouseDrag, mouseMove, contains
  24752. */
  24753. virtual void mouseExit (const MouseEvent& e);
  24754. /** Called when a mouse button is pressed while it's over this component.
  24755. The MouseEvent object passed in contains lots of methods for finding out
  24756. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  24757. were held down at the time.
  24758. Once a button is held down, the mouseDrag method will be called when the
  24759. mouse moves, until the button is released.
  24760. @param e details about the position and status of the mouse event
  24761. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  24762. */
  24763. virtual void mouseDown (const MouseEvent& e);
  24764. /** Called when the mouse is moved while a button is held down.
  24765. When a mouse button is pressed inside a component, that component
  24766. receives mouseDrag callbacks each time the mouse moves, even if the
  24767. mouse strays outside the component's bounds.
  24768. If you want to be able to drag things off the edge of a component
  24769. and have the component scroll when you get to the edges, the
  24770. beginDragAutoRepeat() method might be useful.
  24771. @param e details about the position and status of the mouse event
  24772. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  24773. */
  24774. virtual void mouseDrag (const MouseEvent& e);
  24775. /** Called when a mouse button is released.
  24776. A mouseUp callback is sent to the component in which a button was pressed
  24777. even if the mouse is actually over a different component when the
  24778. button is released.
  24779. The MouseEvent object passed in contains lots of methods for finding out
  24780. which buttons were down just before they were released.
  24781. @param e details about the position and status of the mouse event
  24782. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  24783. */
  24784. virtual void mouseUp (const MouseEvent& e);
  24785. /** Called when a mouse button has been double-clicked in this component.
  24786. The MouseEvent object passed in contains lots of methods for finding out
  24787. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  24788. were held down at the time.
  24789. For altering the time limit used to detect double-clicks,
  24790. see MouseEvent::setDoubleClickTimeout.
  24791. @param e details about the position and status of the mouse event
  24792. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  24793. MouseEvent::getDoubleClickTimeout
  24794. */
  24795. virtual void mouseDoubleClick (const MouseEvent& e);
  24796. /** Called when the mouse-wheel is moved.
  24797. This callback is sent to the component that the mouse is over when the
  24798. wheel is moved.
  24799. If not overridden, the component will forward this message to its parent, so
  24800. that parent components can collect mouse-wheel messages that happen to
  24801. child components which aren't interested in them.
  24802. @param e details about the position and status of the mouse event
  24803. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  24804. value means the wheel has been pushed to the right, negative means it
  24805. was pushed to the left
  24806. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  24807. value means the wheel has been pushed upwards, negative means it
  24808. was pushed downwards
  24809. */
  24810. virtual void mouseWheelMove (const MouseEvent& e,
  24811. float wheelIncrementX,
  24812. float wheelIncrementY);
  24813. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  24814. current mouse-drag operation.
  24815. This allows you to make sure that mouseDrag() events are sent continuously, even
  24816. when the mouse isn't moving. This can be useful for things like auto-scrolling
  24817. components when the mouse is near an edge.
  24818. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  24819. minimum interval between consecutive mouse drag callbacks. The callbacks
  24820. will continue until the mouse is released, and then the interval will be reset,
  24821. so you need to make sure it's called every time you begin a drag event.
  24822. Passing an interval of 0 or less will cancel the auto-repeat.
  24823. @see mouseDrag, Desktop::beginDragAutoRepeat
  24824. */
  24825. static void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  24826. /** Causes automatic repaints when the mouse enters or exits this component.
  24827. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  24828. on the component, it will trigger a repaint.
  24829. This is handy for things like buttons that need to draw themselves differently when
  24830. the mouse moves over them, and it avoids having to override all the different mouse
  24831. callbacks and call repaint().
  24832. @see mouseEnter, mouseExit, mouseDown, mouseUp
  24833. */
  24834. void setRepaintsOnMouseActivity (bool shouldRepaint) noexcept;
  24835. /** Registers a listener to be told when mouse events occur in this component.
  24836. If you need to get informed about mouse events in a component but can't or
  24837. don't want to override its methods, you can attach any number of listeners
  24838. to the component, and these will get told about the events in addition to
  24839. the component's own callbacks being called.
  24840. Note that a MouseListener can also be attached to more than one component.
  24841. @param newListener the listener to register
  24842. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  24843. for events that happen to any child component
  24844. within this component, including deeply-nested
  24845. child components. If false, it will only be
  24846. told about events that this component handles.
  24847. @see MouseListener, removeMouseListener
  24848. */
  24849. void addMouseListener (MouseListener* newListener,
  24850. bool wantsEventsForAllNestedChildComponents);
  24851. /** Deregisters a mouse listener.
  24852. @see addMouseListener, MouseListener
  24853. */
  24854. void removeMouseListener (MouseListener* listenerToRemove);
  24855. /** Adds a listener that wants to hear about keypresses that this component receives.
  24856. The listeners that are registered with a component are called by its keyPressed() or
  24857. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  24858. If you add an object as a key listener, be careful to remove it when the object
  24859. is deleted, or the component will be left with a dangling pointer.
  24860. @see keyPressed, keyStateChanged, removeKeyListener
  24861. */
  24862. void addKeyListener (KeyListener* newListener);
  24863. /** Removes a previously-registered key listener.
  24864. @see addKeyListener
  24865. */
  24866. void removeKeyListener (KeyListener* listenerToRemove);
  24867. /** Called when a key is pressed.
  24868. When a key is pressed, the component that has the keyboard focus will have this
  24869. method called. Remember that a component will only be given the focus if its
  24870. setWantsKeyboardFocus() method has been used to enable this.
  24871. If your implementation returns true, the event will be consumed and not passed
  24872. on to any other listeners. If it returns false, the key will be passed to any
  24873. KeyListeners that have been registered with this component. As soon as one of these
  24874. returns true, the process will stop, but if they all return false, the event will
  24875. be passed upwards to this component's parent, and so on.
  24876. The default implementation of this method does nothing and returns false.
  24877. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  24878. */
  24879. virtual bool keyPressed (const KeyPress& key);
  24880. /** Called when a key is pressed or released.
  24881. Whenever a key on the keyboard is pressed or released (including modifier keys
  24882. like shift and ctrl), this method will be called on the component that currently
  24883. has the keyboard focus. Remember that a component will only be given the focus if
  24884. its setWantsKeyboardFocus() method has been used to enable this.
  24885. If your implementation returns true, the event will be consumed and not passed
  24886. on to any other listeners. If it returns false, then any KeyListeners that have
  24887. been registered with this component will have their keyStateChanged methods called.
  24888. As soon as one of these returns true, the process will stop, but if they all return
  24889. false, the event will be passed upwards to this component's parent, and so on.
  24890. The default implementation of this method does nothing and returns false.
  24891. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  24892. method.
  24893. @param isKeyDown true if a key has been pressed; false if it has been released
  24894. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  24895. */
  24896. virtual bool keyStateChanged (bool isKeyDown);
  24897. /** Called when a modifier key is pressed or released.
  24898. Whenever the shift, control, alt or command keys are pressed or released,
  24899. this method will be called on the component that currently has the keyboard focus.
  24900. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  24901. method has been used to enable this.
  24902. The default implementation of this method actually calls its parent's modifierKeysChanged
  24903. method, so that focused components which aren't interested in this will give their
  24904. parents a chance to act on the event instead.
  24905. @see keyStateChanged, ModifierKeys
  24906. */
  24907. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  24908. /** Enumeration used by the focusChanged() and focusLost() methods. */
  24909. enum FocusChangeType
  24910. {
  24911. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  24912. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  24913. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  24914. };
  24915. /** Called to indicate that this component has just acquired the keyboard focus.
  24916. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24917. */
  24918. virtual void focusGained (FocusChangeType cause);
  24919. /** Called to indicate that this component has just lost the keyboard focus.
  24920. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24921. */
  24922. virtual void focusLost (FocusChangeType cause);
  24923. /** Called to indicate that one of this component's children has been focused or unfocused.
  24924. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  24925. changed. It happens when focus moves from one of this component's children (at any depth)
  24926. to a component that isn't contained in this one, (or vice-versa).
  24927. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24928. */
  24929. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  24930. /** Returns true if the mouse is currently over this component.
  24931. If the mouse isn't over the component, this will return false, even if the
  24932. mouse is currently being dragged - so you can use this in your mouseDrag
  24933. method to find out whether it's really over the component or not.
  24934. Note that when the mouse button is being held down, then the only component
  24935. for which this method will return true is the one that was originally
  24936. clicked on.
  24937. If includeChildren is true, then this will also return true if the mouse is over
  24938. any of the component's children (recursively) as well as the component itself.
  24939. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  24940. */
  24941. bool isMouseOver (bool includeChildren = false) const;
  24942. /** Returns true if the mouse button is currently held down in this component.
  24943. Note that this is a test to see whether the mouse is being pressed in this
  24944. component, so it'll return false if called on component A when the mouse
  24945. is actually being dragged in component B.
  24946. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  24947. */
  24948. bool isMouseButtonDown() const noexcept;
  24949. /** True if the mouse is over this component, or if it's being dragged in this component.
  24950. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  24951. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  24952. */
  24953. bool isMouseOverOrDragging() const noexcept;
  24954. /** Returns true if a mouse button is currently down.
  24955. Unlike isMouseButtonDown, this will test the current state of the
  24956. buttons without regard to which component (if any) it has been
  24957. pressed in.
  24958. @see isMouseButtonDown, ModifierKeys
  24959. */
  24960. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() noexcept;
  24961. /** Returns the mouse's current position, relative to this component.
  24962. The return value is relative to the component's top-left corner.
  24963. */
  24964. Point<int> getMouseXYRelative() const;
  24965. /** Called when this component's size has been changed.
  24966. A component can implement this method to do things such as laying out its
  24967. child components when its width or height changes.
  24968. The method is called synchronously as a result of the setBounds or setSize
  24969. methods, so repeatedly changing a components size will repeatedly call its
  24970. resized method (unlike things like repainting, where multiple calls to repaint
  24971. are coalesced together).
  24972. If the component is a top-level window on the desktop, its size could also
  24973. be changed by operating-system factors beyond the application's control.
  24974. @see moved, setSize
  24975. */
  24976. virtual void resized();
  24977. /** Called when this component's position has been changed.
  24978. This is called when the position relative to its parent changes, not when
  24979. its absolute position on the screen changes (so it won't be called for
  24980. all child components when a parent component is moved).
  24981. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  24982. or any of the other repositioning methods, and like resized(), it will be
  24983. called each time those methods are called.
  24984. If the component is a top-level window on the desktop, its position could also
  24985. be changed by operating-system factors beyond the application's control.
  24986. @see resized, setBounds
  24987. */
  24988. virtual void moved();
  24989. /** Called when one of this component's children is moved or resized.
  24990. If the parent wants to know about changes to its immediate children (not
  24991. to children of its children), this is the method to override.
  24992. @see moved, resized, parentSizeChanged
  24993. */
  24994. virtual void childBoundsChanged (Component* child);
  24995. /** Called when this component's immediate parent has been resized.
  24996. If the component is a top-level window, this indicates that the screen size
  24997. has changed.
  24998. @see childBoundsChanged, moved, resized
  24999. */
  25000. virtual void parentSizeChanged();
  25001. /** Called when this component has been moved to the front of its siblings.
  25002. The component may have been brought to the front by the toFront() method, or
  25003. by the operating system if it's a top-level window.
  25004. @see toFront
  25005. */
  25006. virtual void broughtToFront();
  25007. /** Adds a listener to be told about changes to the component hierarchy or position.
  25008. Component listeners get called when this component's size, position or children
  25009. change - see the ComponentListener class for more details.
  25010. @param newListener the listener to register - if this is already registered, it
  25011. will be ignored.
  25012. @see ComponentListener, removeComponentListener
  25013. */
  25014. void addComponentListener (ComponentListener* newListener);
  25015. /** Removes a component listener.
  25016. @see addComponentListener
  25017. */
  25018. void removeComponentListener (ComponentListener* listenerToRemove);
  25019. /** Dispatches a numbered message to this component.
  25020. This is a quick and cheap way of allowing simple asynchronous messages to
  25021. be sent to components. It's also safe, because if the component that you
  25022. send the message to is a null or dangling pointer, this won't cause an error.
  25023. The command ID is later delivered to the component's handleCommandMessage() method by
  25024. the application's message queue.
  25025. @see handleCommandMessage
  25026. */
  25027. void postCommandMessage (int commandId);
  25028. /** Called to handle a command that was sent by postCommandMessage().
  25029. This is called by the message thread when a command message arrives, and
  25030. the component can override this method to process it in any way it needs to.
  25031. @see postCommandMessage
  25032. */
  25033. virtual void handleCommandMessage (int commandId);
  25034. /** Runs a component modally, waiting until the loop terminates.
  25035. This method first makes the component visible, brings it to the front and
  25036. gives it the keyboard focus.
  25037. It then runs a loop, dispatching messages from the system message queue, but
  25038. blocking all mouse or keyboard messages from reaching any components other
  25039. than this one and its children.
  25040. This loop continues until the component's exitModalState() method is called (or
  25041. the component is deleted), and then this method returns, returning the value
  25042. passed into exitModalState().
  25043. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  25044. isCurrentlyBlockedByAnotherModalComponent, ModalComponentManager
  25045. */
  25046. #if JUCE_MODAL_LOOPS_PERMITTED
  25047. int runModalLoop();
  25048. #endif
  25049. /** Puts the component into a modal state.
  25050. This makes the component modal, so that messages are blocked from reaching
  25051. any components other than this one and its children, but unlike runModalLoop(),
  25052. this method returns immediately.
  25053. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  25054. get the focus, which is usually what you'll want it to do. If not, it will leave
  25055. the focus unchanged.
  25056. The callback is an optional object which will receive a callback when the modal
  25057. component loses its modal status, either by being hidden or when exitModalState()
  25058. is called. If you pass an object in here, the system will take care of deleting it
  25059. later, after making the callback
  25060. If deleteWhenDismissed is true, then when it is dismissed, the component will be
  25061. deleted and then the callback will be called. (This will safely handle the situation
  25062. where the component is deleted before its exitModalState() method is called).
  25063. @see exitModalState, runModalLoop, ModalComponentManager::attachCallback
  25064. */
  25065. void enterModalState (bool takeKeyboardFocus = true,
  25066. ModalComponentManager::Callback* callback = nullptr,
  25067. bool deleteWhenDismissed = false);
  25068. /** Ends a component's modal state.
  25069. If this component is currently modal, this will turn of its modalness, and return
  25070. a value to the runModalLoop() method that might have be running its modal loop.
  25071. @see runModalLoop, enterModalState, isCurrentlyModal
  25072. */
  25073. void exitModalState (int returnValue);
  25074. /** Returns true if this component is the modal one.
  25075. It's possible to have nested modal components, e.g. a pop-up dialog box
  25076. that launches another pop-up, but this will only return true for
  25077. the one at the top of the stack.
  25078. @see getCurrentlyModalComponent
  25079. */
  25080. bool isCurrentlyModal() const noexcept;
  25081. /** Returns the number of components that are currently in a modal state.
  25082. @see getCurrentlyModalComponent
  25083. */
  25084. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() noexcept;
  25085. /** Returns one of the components that are currently modal.
  25086. The index specifies which of the possible modal components to return. The order
  25087. of the components in this list is the reverse of the order in which they became
  25088. modal - so the component at index 0 is always the active component, and the others
  25089. are progressively earlier ones that are themselves now blocked by later ones.
  25090. @returns the modal component, or null if no components are modal (or if the
  25091. index is out of range)
  25092. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  25093. */
  25094. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) noexcept;
  25095. /** Checks whether there's a modal component somewhere that's stopping this one
  25096. from receiving messages.
  25097. If there is a modal component, its canModalEventBeSentToComponent() method
  25098. will be called to see if it will still allow this component to receive events.
  25099. @see runModalLoop, getCurrentlyModalComponent
  25100. */
  25101. bool isCurrentlyBlockedByAnotherModalComponent() const;
  25102. /** When a component is modal, this callback allows it to choose which other
  25103. components can still receive events.
  25104. When a modal component is active and the user clicks on a non-modal component,
  25105. this method is called on the modal component, and if it returns true, the
  25106. event is allowed to reach its target. If it returns false, the event is blocked
  25107. and the inputAttemptWhenModal() callback is made.
  25108. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  25109. implementation just returns false in all cases.
  25110. */
  25111. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  25112. /** Called when the user tries to click on a component that is blocked by another
  25113. modal component.
  25114. When a component is modal and the user clicks on one of the other components,
  25115. the modal component will receive this callback.
  25116. The default implementation of this method will play a beep, and bring the currently
  25117. modal component to the front, but it can be overridden to do other tasks.
  25118. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  25119. */
  25120. virtual void inputAttemptWhenModal();
  25121. /** Returns the set of properties that belong to this component.
  25122. Each component has a NamedValueSet object which you can use to attach arbitrary
  25123. items of data to it.
  25124. */
  25125. NamedValueSet& getProperties() noexcept { return properties; }
  25126. /** Returns the set of properties that belong to this component.
  25127. Each component has a NamedValueSet object which you can use to attach arbitrary
  25128. items of data to it.
  25129. */
  25130. const NamedValueSet& getProperties() const noexcept { return properties; }
  25131. /** Looks for a colour that has been registered with the given colour ID number.
  25132. If a colour has been set for this ID number using setColour(), then it is
  25133. returned. If none has been set, the method will try calling the component's
  25134. LookAndFeel class's findColour() method. If none has been registered with the
  25135. look-and-feel either, it will just return black.
  25136. The colour IDs for various purposes are stored as enums in the components that
  25137. they are relevent to - for an example, see Slider::ColourIds,
  25138. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  25139. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  25140. */
  25141. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  25142. /** Registers a colour to be used for a particular purpose.
  25143. Changing a colour will cause a synchronous callback to the colourChanged()
  25144. method, which your component can override if it needs to do something when
  25145. colours are altered.
  25146. For more details about colour IDs, see the comments for findColour().
  25147. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  25148. */
  25149. void setColour (int colourId, const Colour& colour);
  25150. /** If a colour has been set with setColour(), this will remove it.
  25151. This allows you to make a colour revert to its default state.
  25152. */
  25153. void removeColour (int colourId);
  25154. /** Returns true if the specified colour ID has been explicitly set for this
  25155. component using the setColour() method.
  25156. */
  25157. bool isColourSpecified (int colourId) const;
  25158. /** This looks for any colours that have been specified for this component,
  25159. and copies them to the specified target component.
  25160. */
  25161. void copyAllExplicitColoursTo (Component& target) const;
  25162. /** This method is called when a colour is changed by the setColour() method.
  25163. @see setColour, findColour
  25164. */
  25165. virtual void colourChanged();
  25166. /** Components can implement this method to provide a MarkerList.
  25167. The default implementation of this method returns 0, but you can override it to
  25168. return a pointer to the component's marker list. If xAxis is true, it should
  25169. return the X marker list; if false, it should return the Y markers.
  25170. */
  25171. virtual MarkerList* getMarkers (bool xAxis);
  25172. /** Returns the underlying native window handle for this component.
  25173. This is platform-dependent and strictly for power-users only!
  25174. */
  25175. void* getWindowHandle() const;
  25176. /** Holds a pointer to some type of Component, which automatically becomes null if
  25177. the component is deleted.
  25178. If you're using a component which may be deleted by another event that's outside
  25179. of your control, use a SafePointer instead of a normal pointer to refer to it,
  25180. and you can test whether it's null before using it to see if something has deleted
  25181. it.
  25182. The ComponentType typedef must be Component, or some subclass of Component.
  25183. You may also want to use a WeakReference<Component> object for the same purpose.
  25184. */
  25185. template <class ComponentType>
  25186. class SafePointer
  25187. {
  25188. public:
  25189. /** Creates a null SafePointer. */
  25190. SafePointer() noexcept {}
  25191. /** Creates a SafePointer that points at the given component. */
  25192. SafePointer (ComponentType* const component) : weakRef (component) {}
  25193. /** Creates a copy of another SafePointer. */
  25194. SafePointer (const SafePointer& other) noexcept : weakRef (other.weakRef) {}
  25195. /** Copies another pointer to this one. */
  25196. SafePointer& operator= (const SafePointer& other) { weakRef = other.weakRef; return *this; }
  25197. /** Copies another pointer to this one. */
  25198. SafePointer& operator= (ComponentType* const newComponent) { weakRef = newComponent; return *this; }
  25199. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25200. ComponentType* getComponent() const noexcept { return dynamic_cast <ComponentType*> (weakRef.get()); }
  25201. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25202. operator ComponentType*() const noexcept { return getComponent(); }
  25203. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25204. ComponentType* operator->() noexcept { return getComponent(); }
  25205. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  25206. const ComponentType* operator->() const noexcept { return getComponent(); }
  25207. /** If the component is valid, this deletes it and sets this pointer to null. */
  25208. void deleteAndZero() { delete getComponent(); jassert (getComponent() == nullptr); }
  25209. bool operator== (ComponentType* component) const noexcept { return weakRef == component; }
  25210. bool operator!= (ComponentType* component) const noexcept { return weakRef != component; }
  25211. private:
  25212. WeakReference<Component> weakRef;
  25213. };
  25214. /** A class to keep an eye on a component and check for it being deleted.
  25215. This is designed for use with the ListenerList::callChecked() methods, to allow
  25216. the list iterator to stop cleanly if the component is deleted by a listener callback
  25217. while the list is still being iterated.
  25218. */
  25219. class JUCE_API BailOutChecker
  25220. {
  25221. public:
  25222. /** Creates a checker that watches one component. */
  25223. BailOutChecker (Component* component);
  25224. /** Returns true if either of the two components have been deleted since this object was created. */
  25225. bool shouldBailOut() const noexcept;
  25226. private:
  25227. const WeakReference<Component> safePointer;
  25228. JUCE_DECLARE_NON_COPYABLE (BailOutChecker);
  25229. };
  25230. /**
  25231. Base class for objects that can be used to automatically position a component according to
  25232. some kind of algorithm.
  25233. The component class simply holds onto a reference to a Positioner, but doesn't actually do
  25234. anything with it - all the functionality must be implemented by the positioner itself (e.g.
  25235. it might choose to watch some kind of value and move the component when the value changes).
  25236. */
  25237. class JUCE_API Positioner
  25238. {
  25239. public:
  25240. /** Creates a Positioner which can control the specified component. */
  25241. explicit Positioner (Component& component) noexcept;
  25242. /** Destructor. */
  25243. virtual ~Positioner() {}
  25244. /** Returns the component that this positioner controls. */
  25245. Component& getComponent() const noexcept { return component; }
  25246. /** Attempts to set the component's position to the given rectangle.
  25247. Unlike simply calling Component::setBounds(), this may involve the positioner
  25248. being smart enough to adjust itself to fit the new bounds, e.g. a RelativeRectangle's
  25249. positioner may try to reverse the expressions used to make them fit these new coordinates.
  25250. */
  25251. virtual void applyNewBounds (const Rectangle<int>& newBounds) = 0;
  25252. private:
  25253. Component& component;
  25254. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  25255. };
  25256. /** Returns the Positioner object that has been set for this component.
  25257. @see setPositioner()
  25258. */
  25259. Positioner* getPositioner() const noexcept;
  25260. /** Sets a new Positioner object for this component.
  25261. If there's currently another positioner set, it will be deleted. The object that is passed in
  25262. will be deleted automatically by this component when it's no longer required. Pass a null pointer
  25263. to clear the current positioner.
  25264. @see getPositioner()
  25265. */
  25266. void setPositioner (Positioner* newPositioner);
  25267. #ifndef DOXYGEN
  25268. // These methods are deprecated - use localPointToGlobal, getLocalPoint, getLocalPoint, etc instead.
  25269. JUCE_DEPRECATED (const Point<int> relativePositionToGlobal (const Point<int>&) const);
  25270. JUCE_DEPRECATED (const Point<int> globalPositionToRelative (const Point<int>&) const);
  25271. JUCE_DEPRECATED (const Point<int> relativePositionToOtherComponent (const Component*, const Point<int>&) const);
  25272. #endif
  25273. private:
  25274. friend class ComponentPeer;
  25275. friend class MouseInputSource;
  25276. friend class MouseInputSourceInternal;
  25277. #ifndef DOXYGEN
  25278. static Component* currentlyFocusedComponent;
  25279. String componentName, componentID;
  25280. Component* parentComponent;
  25281. Rectangle<int> bounds;
  25282. ScopedPointer <Positioner> positioner;
  25283. ScopedPointer <AffineTransform> affineTransform;
  25284. Array <Component*> childComponentList;
  25285. LookAndFeel* lookAndFeel;
  25286. MouseCursor cursor;
  25287. ImageEffectFilter* effect;
  25288. Image bufferedImage;
  25289. class MouseListenerList;
  25290. friend class MouseListenerList;
  25291. friend class ScopedPointer <MouseListenerList>;
  25292. ScopedPointer <MouseListenerList> mouseListeners;
  25293. ScopedPointer <Array <KeyListener*> > keyListeners;
  25294. ListenerList <ComponentListener> componentListeners;
  25295. NamedValueSet properties;
  25296. friend class WeakReference<Component>;
  25297. WeakReference<Component>::Master weakReferenceMaster;
  25298. const WeakReference<Component>::SharedRef& getWeakReference();
  25299. struct ComponentFlags
  25300. {
  25301. bool hasHeavyweightPeerFlag : 1;
  25302. bool visibleFlag : 1;
  25303. bool opaqueFlag : 1;
  25304. bool ignoresMouseClicksFlag : 1;
  25305. bool allowChildMouseClicksFlag : 1;
  25306. bool wantsFocusFlag : 1;
  25307. bool isFocusContainerFlag : 1;
  25308. bool dontFocusOnMouseClickFlag : 1;
  25309. bool alwaysOnTopFlag : 1;
  25310. bool bufferToImageFlag : 1;
  25311. bool bringToFrontOnClickFlag : 1;
  25312. bool repaintOnMouseActivityFlag : 1;
  25313. bool mouseDownFlag : 1;
  25314. bool mouseOverFlag : 1;
  25315. bool mouseInsideFlag : 1;
  25316. bool currentlyModalFlag : 1;
  25317. bool isDisabledFlag : 1;
  25318. bool childCompFocusedFlag : 1;
  25319. bool dontClipGraphicsFlag : 1;
  25320. #if JUCE_DEBUG
  25321. bool isInsidePaintCall : 1;
  25322. #endif
  25323. };
  25324. union
  25325. {
  25326. uint32 componentFlags;
  25327. ComponentFlags flags;
  25328. };
  25329. uint8 componentTransparency;
  25330. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25331. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25332. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25333. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  25334. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25335. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  25336. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  25337. void internalBroughtToFront();
  25338. void internalFocusGain (const FocusChangeType cause, const WeakReference<Component>&);
  25339. void internalFocusGain (const FocusChangeType cause);
  25340. void internalFocusLoss (const FocusChangeType cause);
  25341. void internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>&);
  25342. void internalModalInputAttempt();
  25343. void internalModifierKeysChanged();
  25344. void internalChildrenChanged();
  25345. void internalHierarchyChanged();
  25346. Component* removeChildComponent (int index, bool sendParentEvents, bool sendChildEvents);
  25347. void moveChildInternal (int sourceIndex, int destIndex);
  25348. void paintComponentAndChildren (Graphics& g);
  25349. void paintComponent (Graphics& g);
  25350. void paintWithinParentContext (Graphics& g);
  25351. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  25352. void repaintParent();
  25353. void sendFakeMouseMove() const;
  25354. void takeKeyboardFocus (const FocusChangeType cause);
  25355. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  25356. static void giveAwayFocus (bool sendFocusLossEvent);
  25357. void sendEnablementChangeMessage();
  25358. void sendVisibilityChangeMessage();
  25359. class ComponentHelpers;
  25360. friend class ComponentHelpers;
  25361. /* Components aren't allowed to have copy constructors, as this would mess up parent hierarchies.
  25362. You might need to give your subclasses a private dummy constructor to avoid compiler warnings.
  25363. */
  25364. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Component);
  25365. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  25366. // This is included here just to cause a compile error if your code is still handling
  25367. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  25368. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  25369. // implement its methods instead of this Component method).
  25370. virtual void filesDropped (const StringArray&, int, int) {}
  25371. // This is included here to cause an error if you use or overload it - it has been deprecated in
  25372. // favour of contains (const Point<int>&)
  25373. void contains (int, int);
  25374. #endif
  25375. protected:
  25376. /** @internal */
  25377. virtual void internalRepaint (int x, int y, int w, int h);
  25378. /** @internal */
  25379. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  25380. #endif
  25381. };
  25382. #endif // __JUCE_COMPONENT_JUCEHEADER__
  25383. /*** End of inlined file: juce_Component.h ***/
  25384. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  25385. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25386. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25387. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  25388. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25389. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25390. /** A type used to hold the unique ID for an application command.
  25391. This is a numeric type, so it can be stored as an integer.
  25392. @see ApplicationCommandInfo, ApplicationCommandManager,
  25393. ApplicationCommandTarget, KeyPressMappingSet
  25394. */
  25395. typedef int CommandID;
  25396. /** A set of general-purpose application command IDs.
  25397. Because these commands are likely to be used in most apps, they're defined
  25398. here to help different apps to use the same numeric values for them.
  25399. Of course you don't have to use these, but some of them are used internally by
  25400. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  25401. @see ApplicationCommandInfo, ApplicationCommandManager,
  25402. ApplicationCommandTarget, KeyPressMappingSet
  25403. */
  25404. namespace StandardApplicationCommandIDs
  25405. {
  25406. /** This command ID should be used to send a "Quit the App" command.
  25407. This command is recognised by the JUCEApplication class, so if it is invoked
  25408. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  25409. object will catch it and call JUCEApplication::systemRequestedQuit().
  25410. */
  25411. static const CommandID quit = 0x1001;
  25412. /** The command ID that should be used to send a "Delete" command. */
  25413. static const CommandID del = 0x1002;
  25414. /** The command ID that should be used to send a "Cut" command. */
  25415. static const CommandID cut = 0x1003;
  25416. /** The command ID that should be used to send a "Copy to clipboard" command. */
  25417. static const CommandID copy = 0x1004;
  25418. /** The command ID that should be used to send a "Paste from clipboard" command. */
  25419. static const CommandID paste = 0x1005;
  25420. /** The command ID that should be used to send a "Select all" command. */
  25421. static const CommandID selectAll = 0x1006;
  25422. /** The command ID that should be used to send a "Deselect all" command. */
  25423. static const CommandID deselectAll = 0x1007;
  25424. }
  25425. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25426. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  25427. /**
  25428. Holds information describing an application command.
  25429. This object is used to pass information about a particular command, such as its
  25430. name, description and other usage flags.
  25431. When an ApplicationCommandTarget is asked to provide information about the commands
  25432. it can perform, this is the structure gets filled-in to describe each one.
  25433. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  25434. ApplicationCommandManager
  25435. */
  25436. struct JUCE_API ApplicationCommandInfo
  25437. {
  25438. explicit ApplicationCommandInfo (CommandID commandID) noexcept;
  25439. /** Sets a number of the structures values at once.
  25440. The meanings of each of the parameters is described below, in the appropriate
  25441. member variable's description.
  25442. */
  25443. void setInfo (const String& shortName,
  25444. const String& description,
  25445. const String& categoryName,
  25446. int flags) noexcept;
  25447. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  25448. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  25449. is false, the bit is set.
  25450. */
  25451. void setActive (bool isActive) noexcept;
  25452. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  25453. */
  25454. void setTicked (bool isTicked) noexcept;
  25455. /** Handy method for adding a keypress to the defaultKeypresses array.
  25456. This is just so you can write things like:
  25457. @code
  25458. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  25459. @endcode
  25460. instead of
  25461. @code
  25462. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  25463. @endcode
  25464. */
  25465. void addDefaultKeypress (int keyCode,
  25466. const ModifierKeys& modifiers) noexcept;
  25467. /** The command's unique ID number.
  25468. */
  25469. CommandID commandID;
  25470. /** A short name to describe the command.
  25471. This should be suitable for use in menus, on buttons that trigger the command, etc.
  25472. You can use the setInfo() method to quickly set this and some of the command's
  25473. other properties.
  25474. */
  25475. String shortName;
  25476. /** A longer description of the command.
  25477. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  25478. pop-up tooltip describing what the command does.
  25479. You can use the setInfo() method to quickly set this and some of the command's
  25480. other properties.
  25481. */
  25482. String description;
  25483. /** A named category that the command fits into.
  25484. You can give your commands any category you like, and these will be displayed in
  25485. contexts such as the KeyMappingEditorComponent, where the category is used to group
  25486. commands together.
  25487. You can use the setInfo() method to quickly set this and some of the command's
  25488. other properties.
  25489. */
  25490. String categoryName;
  25491. /** A list of zero or more keypresses that should be used as the default keys for
  25492. this command.
  25493. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  25494. this list to initialise the default set of key-to-command mappings.
  25495. @see addDefaultKeypress
  25496. */
  25497. Array <KeyPress> defaultKeypresses;
  25498. /** Flags describing the ways in which this command should be used.
  25499. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  25500. variable.
  25501. */
  25502. enum CommandFlags
  25503. {
  25504. /** Indicates that the command can't currently be performed.
  25505. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  25506. not currently permissable to perform the command. If the flag is set, then
  25507. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  25508. command or show themselves as not being enabled.
  25509. @see ApplicationCommandInfo::setActive
  25510. */
  25511. isDisabled = 1 << 0,
  25512. /** Indicates that the command should have a tick next to it on a menu.
  25513. If your command is shown on a menu and this is set, it'll show a tick next to
  25514. it. Other components such as buttons may also use this flag to indicate that it
  25515. is a value that can be toggled, and is currently in the 'on' state.
  25516. @see ApplicationCommandInfo::setTicked
  25517. */
  25518. isTicked = 1 << 1,
  25519. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  25520. it will call the command twice, once on key-down and again on key-up.
  25521. @see ApplicationCommandTarget::InvocationInfo
  25522. */
  25523. wantsKeyUpDownCallbacks = 1 << 2,
  25524. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  25525. command in its list.
  25526. */
  25527. hiddenFromKeyEditor = 1 << 3,
  25528. /** If this flag is present, then a KeyMappingEditorComponent will display the
  25529. command in its list, but won't allow the assigned keypress to be changed.
  25530. */
  25531. readOnlyInKeyEditor = 1 << 4,
  25532. /** If this flag is present and the command is invoked from a keypress, then any
  25533. buttons or menus that are also connected to the command will not flash to
  25534. indicate that they've been triggered.
  25535. */
  25536. dontTriggerVisualFeedback = 1 << 5
  25537. };
  25538. /** A bitwise-OR of the values specified in the CommandFlags enum.
  25539. You can use the setInfo() method to quickly set this and some of the command's
  25540. other properties.
  25541. */
  25542. int flags;
  25543. };
  25544. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25545. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  25546. /*** Start of inlined file: juce_MessageListener.h ***/
  25547. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  25548. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  25549. /**
  25550. MessageListener subclasses can post and receive Message objects.
  25551. @see Message, MessageManager, ActionListener, ChangeListener
  25552. */
  25553. class JUCE_API MessageListener
  25554. {
  25555. protected:
  25556. /** Creates a MessageListener. */
  25557. MessageListener() noexcept;
  25558. public:
  25559. /** Destructor.
  25560. When a MessageListener is deleted, it removes itself from a global list
  25561. of registered listeners, so that the isValidMessageListener() method
  25562. will no longer return true.
  25563. */
  25564. virtual ~MessageListener();
  25565. /** This is the callback method that receives incoming messages.
  25566. This is called by the MessageManager from its dispatch loop.
  25567. @see postMessage
  25568. */
  25569. virtual void handleMessage (const Message& message) = 0;
  25570. /** Sends a message to the message queue, for asynchronous delivery to this listener
  25571. later on.
  25572. This method can be called safely by any thread.
  25573. @param message the message object to send - this will be deleted
  25574. automatically by the message queue, so don't keep any
  25575. references to it after calling this method.
  25576. @see handleMessage
  25577. */
  25578. void postMessage (Message* message) const noexcept;
  25579. /** Checks whether this MessageListener has been deleted.
  25580. Although not foolproof, this method is safe to call on dangling or null
  25581. pointers. A list of active MessageListeners is kept internally, so this
  25582. checks whether the object is on this list or not.
  25583. Note that it's possible to get a false-positive here, if an object is
  25584. deleted and another is subsequently created that happens to be at the
  25585. exact same memory location, but I can't think of a good way of avoiding
  25586. this.
  25587. */
  25588. bool isValidMessageListener() const noexcept;
  25589. };
  25590. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  25591. /*** End of inlined file: juce_MessageListener.h ***/
  25592. /**
  25593. A command target publishes a list of command IDs that it can perform.
  25594. An ApplicationCommandManager despatches commands to targets, which must be
  25595. able to provide information about what commands they can handle.
  25596. To create a target, you'll need to inherit from this class, implementing all of
  25597. its pure virtual methods.
  25598. For info about how a target is chosen to receive a command, see
  25599. ApplicationCommandManager::getFirstCommandTarget().
  25600. @see ApplicationCommandManager, ApplicationCommandInfo
  25601. */
  25602. class JUCE_API ApplicationCommandTarget
  25603. {
  25604. public:
  25605. /** Creates a command target. */
  25606. ApplicationCommandTarget();
  25607. /** Destructor. */
  25608. virtual ~ApplicationCommandTarget();
  25609. /**
  25610. */
  25611. struct JUCE_API InvocationInfo
  25612. {
  25613. InvocationInfo (const CommandID commandID);
  25614. /** The UID of the command that should be performed. */
  25615. CommandID commandID;
  25616. /** The command's flags.
  25617. See ApplicationCommandInfo for a description of these flag values.
  25618. */
  25619. int commandFlags;
  25620. /** The types of context in which the command might be called. */
  25621. enum InvocationMethod
  25622. {
  25623. direct = 0, /**< The command is being invoked directly by a piece of code. */
  25624. fromKeyPress, /**< The command is being invoked by a key-press. */
  25625. fromMenu, /**< The command is being invoked by a menu selection. */
  25626. fromButton /**< The command is being invoked by a button click. */
  25627. };
  25628. /** The type of event that triggered this command. */
  25629. InvocationMethod invocationMethod;
  25630. /** If triggered by a keypress or menu, this will be the component that had the
  25631. keyboard focus at the time.
  25632. If triggered by a button, it may be set to that component, or it may be null.
  25633. */
  25634. Component* originatingComponent;
  25635. /** The keypress that was used to invoke it.
  25636. Note that this will be an invalid keypress if the command was invoked
  25637. by some other means than a keyboard shortcut.
  25638. */
  25639. KeyPress keyPress;
  25640. /** True if the callback is being invoked when the key is pressed,
  25641. false if the key is being released.
  25642. @see KeyPressMappingSet::addCommand()
  25643. */
  25644. bool isKeyDown;
  25645. /** If the key is being released, this indicates how long it had been held
  25646. down for.
  25647. (Only relevant if isKeyDown is false.)
  25648. */
  25649. int millisecsSinceKeyPressed;
  25650. };
  25651. /** This must return the next target to try after this one.
  25652. When a command is being sent, and the first target can't handle
  25653. that command, this method is used to determine the next target that should
  25654. be tried.
  25655. It may return 0 if it doesn't know of another target.
  25656. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  25657. method to return a parent component that might want to handle it.
  25658. @see invoke
  25659. */
  25660. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  25661. /** This must return a complete list of commands that this target can handle.
  25662. Your target should add all the command IDs that it handles to the array that is
  25663. passed-in.
  25664. */
  25665. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  25666. /** This must provide details about one of the commands that this target can perform.
  25667. This will be called with one of the command IDs that the target provided in its
  25668. getAllCommands() methods.
  25669. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  25670. suitable information about the command. (The commandID field will already have been filled-in
  25671. by the caller).
  25672. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  25673. set all the fields at once.
  25674. If the command is currently inactive for some reason, this method must use
  25675. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  25676. bit of the ApplicationCommandInfo::flags field).
  25677. Any default key-presses for the command should be appended to the
  25678. ApplicationCommandInfo::defaultKeypresses field.
  25679. Note that if you change something that affects the status of the commands
  25680. that would be returned by this method (e.g. something that makes some commands
  25681. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  25682. to cause the manager to refresh its status.
  25683. */
  25684. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  25685. /** This must actually perform the specified command.
  25686. If this target is able to perform the command specified by the commandID field of the
  25687. InvocationInfo structure, then it should do so, and must return true.
  25688. If it can't handle this command, it should return false, which tells the caller to pass
  25689. the command on to the next target in line.
  25690. @see invoke, ApplicationCommandManager::invoke
  25691. */
  25692. virtual bool perform (const InvocationInfo& info) = 0;
  25693. /** Makes this target invoke a command.
  25694. Your code can call this method to invoke a command on this target, but normally
  25695. you'd call it indirectly via ApplicationCommandManager::invoke() or
  25696. ApplicationCommandManager::invokeDirectly().
  25697. If this target can perform the given command, it will call its perform() method to
  25698. do so. If not, then getNextCommandTarget() will be used to determine the next target
  25699. to try, and the command will be passed along to it.
  25700. @param invocationInfo this must be correctly filled-in, describing the context for
  25701. the invocation.
  25702. @param asynchronously if false, the command will be performed before this method returns.
  25703. If true, a message will be posted so that the command will be performed
  25704. later on the message thread, and this method will return immediately.
  25705. @see perform, ApplicationCommandManager::invoke
  25706. */
  25707. bool invoke (const InvocationInfo& invocationInfo,
  25708. const bool asynchronously);
  25709. /** Invokes a given command directly on this target.
  25710. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  25711. structure.
  25712. */
  25713. bool invokeDirectly (const CommandID commandID,
  25714. const bool asynchronously);
  25715. /** Searches this target and all subsequent ones for the first one that can handle
  25716. the specified command.
  25717. This will use getNextCommandTarget() to determine the chain of targets to try
  25718. after this one.
  25719. */
  25720. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  25721. /** Checks whether this command can currently be performed by this target.
  25722. This will return true only if a call to getCommandInfo() doesn't set the
  25723. isDisabled flag to indicate that the command is inactive.
  25724. */
  25725. bool isCommandActive (const CommandID commandID);
  25726. /** If this object is a Component, this method will seach upwards in its current
  25727. UI hierarchy for the next parent component that implements the
  25728. ApplicationCommandTarget class.
  25729. If your target is a Component, this is a very handy method to use in your
  25730. getNextCommandTarget() implementation.
  25731. */
  25732. ApplicationCommandTarget* findFirstTargetParentComponent();
  25733. private:
  25734. // (for async invocation of commands)
  25735. class CommandTargetMessageInvoker : public MessageListener
  25736. {
  25737. public:
  25738. CommandTargetMessageInvoker (ApplicationCommandTarget* owner);
  25739. ~CommandTargetMessageInvoker();
  25740. void handleMessage (const Message& message);
  25741. private:
  25742. ApplicationCommandTarget* const owner;
  25743. JUCE_DECLARE_NON_COPYABLE (CommandTargetMessageInvoker);
  25744. };
  25745. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  25746. friend class CommandTargetMessageInvoker;
  25747. bool tryToInvoke (const InvocationInfo& info, bool async);
  25748. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandTarget);
  25749. };
  25750. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  25751. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  25752. /*** Start of inlined file: juce_ActionListener.h ***/
  25753. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  25754. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  25755. /**
  25756. Receives callbacks to indicate that some kind of event has occurred.
  25757. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  25758. about something that's happened.
  25759. @see ActionBroadcaster, ChangeListener
  25760. */
  25761. class JUCE_API ActionListener
  25762. {
  25763. public:
  25764. /** Destructor. */
  25765. virtual ~ActionListener() {}
  25766. /** Overridden by your subclass to receive the callback.
  25767. @param message the string that was specified when the event was triggered
  25768. by a call to ActionBroadcaster::sendActionMessage()
  25769. */
  25770. virtual void actionListenerCallback (const String& message) = 0;
  25771. };
  25772. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  25773. /*** End of inlined file: juce_ActionListener.h ***/
  25774. /**
  25775. An instance of this class is used to specify initialisation and shutdown
  25776. code for the application.
  25777. An application that wants to run in the JUCE framework needs to declare a
  25778. subclass of JUCEApplication and implement its various pure virtual methods.
  25779. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  25780. to declare an instance of this class and generate a suitable platform-specific
  25781. main() function.
  25782. e.g. @code
  25783. class MyJUCEApp : public JUCEApplication
  25784. {
  25785. public:
  25786. MyJUCEApp()
  25787. {
  25788. }
  25789. ~MyJUCEApp()
  25790. {
  25791. }
  25792. void initialise (const String& commandLine)
  25793. {
  25794. myMainWindow = new MyApplicationWindow();
  25795. myMainWindow->setBounds (100, 100, 400, 500);
  25796. myMainWindow->setVisible (true);
  25797. }
  25798. void shutdown()
  25799. {
  25800. myMainWindow = 0;
  25801. }
  25802. const String getApplicationName()
  25803. {
  25804. return "Super JUCE-o-matic";
  25805. }
  25806. const String getApplicationVersion()
  25807. {
  25808. return "1.0";
  25809. }
  25810. private:
  25811. ScopedPointer <MyApplicationWindow> myMainWindow;
  25812. };
  25813. // this creates wrapper code to actually launch the app properly.
  25814. START_JUCE_APPLICATION (MyJUCEApp)
  25815. @endcode
  25816. @see MessageManager
  25817. */
  25818. class JUCE_API JUCEApplication : public ApplicationCommandTarget
  25819. {
  25820. protected:
  25821. /** Constructs a JUCE app object.
  25822. If subclasses implement a constructor or destructor, they shouldn't call any
  25823. JUCE code in there - put your startup/shutdown code in initialise() and
  25824. shutdown() instead.
  25825. */
  25826. JUCEApplication();
  25827. public:
  25828. /** Destructor.
  25829. If subclasses implement a constructor or destructor, they shouldn't call any
  25830. JUCE code in there - put your startup/shutdown code in initialise() and
  25831. shutdown() instead.
  25832. */
  25833. virtual ~JUCEApplication();
  25834. /** Returns the global instance of the application object being run. */
  25835. static JUCEApplication* getInstance() noexcept { return appInstance; }
  25836. /** Called when the application starts.
  25837. This will be called once to let the application do whatever initialisation
  25838. it needs, create its windows, etc.
  25839. After the method returns, the normal event-dispatch loop will be run,
  25840. until the quit() method is called, at which point the shutdown()
  25841. method will be called to let the application clear up anything it needs
  25842. to delete.
  25843. If during the initialise() method, the application decides not to start-up
  25844. after all, it can just call the quit() method and the event loop won't be run.
  25845. @param commandLineParameters the line passed in does not include the
  25846. name of the executable, just the parameter list.
  25847. @see shutdown, quit
  25848. */
  25849. virtual void initialise (const String& commandLineParameters) = 0;
  25850. /** Returns true if the application hasn't yet completed its initialise() method
  25851. and entered the main event loop.
  25852. This is handy for things like splash screens to know when the app's up-and-running
  25853. properly.
  25854. */
  25855. bool isInitialising() const noexcept { return stillInitialising; }
  25856. /* Called to allow the application to clear up before exiting.
  25857. After JUCEApplication::quit() has been called, the event-dispatch loop will
  25858. terminate, and this method will get called to allow the app to sort itself
  25859. out.
  25860. Be careful that nothing happens in this method that might rely on messages
  25861. being sent, or any kind of window activity, because the message loop is no
  25862. longer running at this point.
  25863. @see DeletedAtShutdown
  25864. */
  25865. virtual void shutdown() = 0;
  25866. /** Returns the application's name.
  25867. An application must implement this to name itself.
  25868. */
  25869. virtual const String getApplicationName() = 0;
  25870. /** Returns the application's version number.
  25871. */
  25872. virtual const String getApplicationVersion() = 0;
  25873. /** Checks whether multiple instances of the app are allowed.
  25874. If you application class returns true for this, more than one instance is
  25875. permitted to run (except on the Mac where this isn't possible).
  25876. If it's false, the second instance won't start, but it you will still get a
  25877. callback to anotherInstanceStarted() to tell you about this - which
  25878. gives you a chance to react to what the user was trying to do.
  25879. */
  25880. virtual bool moreThanOneInstanceAllowed();
  25881. /** Indicates that the user has tried to start up another instance of the app.
  25882. This will get called even if moreThanOneInstanceAllowed() is false.
  25883. */
  25884. virtual void anotherInstanceStarted (const String& commandLine);
  25885. /** Called when the operating system is trying to close the application.
  25886. The default implementation of this method is to call quit(), but it may
  25887. be overloaded to ignore the request or do some other special behaviour
  25888. instead. For example, you might want to offer the user the chance to save
  25889. their changes before quitting, and give them the chance to cancel.
  25890. If you want to send a quit signal to your app, this is the correct method
  25891. to call, because it means that requests that come from the system get handled
  25892. in the same way as those from your own application code. So e.g. you'd
  25893. call this method from a "quit" item on a menu bar.
  25894. */
  25895. virtual void systemRequestedQuit();
  25896. /** If any unhandled exceptions make it through to the message dispatch loop, this
  25897. callback will be triggered, in case you want to log them or do some other
  25898. type of error-handling.
  25899. If the type of exception is derived from the std::exception class, the pointer
  25900. passed-in will be valid. If the exception is of unknown type, this pointer
  25901. will be null.
  25902. */
  25903. virtual void unhandledException (const std::exception* e,
  25904. const String& sourceFilename,
  25905. int lineNumber);
  25906. /** Signals that the main message loop should stop and the application should terminate.
  25907. This isn't synchronous, it just posts a quit message to the main queue, and
  25908. when this message arrives, the message loop will stop, the shutdown() method
  25909. will be called, and the app will exit.
  25910. Note that this will cause an unconditional quit to happen, so if you need an
  25911. extra level before this, e.g. to give the user the chance to save their work
  25912. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  25913. method - see that method's help for more info.
  25914. @see MessageManager
  25915. */
  25916. static void quit();
  25917. /** Sets the value that should be returned as the application's exit code when the
  25918. app quits.
  25919. This is the value that's returned by the main() function. Normally you'd leave this
  25920. as 0 unless you want to indicate an error code.
  25921. @see getApplicationReturnValue
  25922. */
  25923. void setApplicationReturnValue (int newReturnValue) noexcept;
  25924. /** Returns the value that has been set as the application's exit code.
  25925. @see setApplicationReturnValue
  25926. */
  25927. int getApplicationReturnValue() const noexcept { return appReturnValue; }
  25928. /** Returns the application's command line parameters. */
  25929. const String& getCommandLineParameters() const noexcept { return commandLineParameters; }
  25930. /** Returns true if this executable is running as an app (as opposed to being a plugin
  25931. or other kind of shared library. */
  25932. static inline bool isStandaloneApp() noexcept { return createInstance != 0; }
  25933. /** @internal */
  25934. ApplicationCommandTarget* getNextCommandTarget();
  25935. /** @internal */
  25936. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  25937. /** @internal */
  25938. void getAllCommands (Array <CommandID>& commands);
  25939. /** @internal */
  25940. bool perform (const InvocationInfo& info);
  25941. #ifndef DOXYGEN
  25942. // The following methods are internal calls - not for public use.
  25943. static int main (const String& commandLine);
  25944. static int main (int argc, const char* argv[]);
  25945. static void sendUnhandledException (const std::exception* e, const char* sourceFile, int lineNumber);
  25946. bool initialiseApp (const String& commandLine);
  25947. int shutdownApp();
  25948. static void appWillTerminateByForce();
  25949. typedef JUCEApplication* (*CreateInstanceFunction)();
  25950. static CreateInstanceFunction createInstance;
  25951. #endif
  25952. private:
  25953. static JUCEApplication* appInstance;
  25954. String commandLineParameters;
  25955. ScopedPointer<InterProcessLock> appLock;
  25956. ScopedPointer<ActionListener> broadcastCallback;
  25957. int appReturnValue;
  25958. bool stillInitialising;
  25959. JUCE_DECLARE_NON_COPYABLE (JUCEApplication);
  25960. };
  25961. #endif // __JUCE_APPLICATION_JUCEHEADER__
  25962. /*** End of inlined file: juce_Application.h ***/
  25963. #endif
  25964. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25965. #endif
  25966. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25967. #endif
  25968. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25969. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  25970. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25971. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25972. /*** Start of inlined file: juce_Desktop.h ***/
  25973. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  25974. #define __JUCE_DESKTOP_JUCEHEADER__
  25975. /*** Start of inlined file: juce_Timer.h ***/
  25976. #ifndef __JUCE_TIMER_JUCEHEADER__
  25977. #define __JUCE_TIMER_JUCEHEADER__
  25978. class InternalTimerThread;
  25979. /**
  25980. Makes repeated callbacks to a virtual method at a specified time interval.
  25981. A Timer's timerCallback() method will be repeatedly called at a given
  25982. interval. When you create a Timer object, it will do nothing until the
  25983. startTimer() method is called, which will cause the message thread to
  25984. start making callbacks at the specified interval, until stopTimer() is called
  25985. or the object is deleted.
  25986. The time interval isn't guaranteed to be precise to any more than maybe
  25987. 10-20ms, and the intervals may end up being much longer than requested if the
  25988. system is busy. Because the callbacks are made by the main message thread,
  25989. anything that blocks the message queue for a period of time will also prevent
  25990. any timers from running until it can carry on.
  25991. If you need to have a single callback that is shared by multiple timers with
  25992. different frequencies, then the MultiTimer class allows you to do that - its
  25993. structure is very similar to the Timer class, but contains multiple timers
  25994. internally, each one identified by an ID number.
  25995. @see MultiTimer
  25996. */
  25997. class JUCE_API Timer
  25998. {
  25999. protected:
  26000. /** Creates a Timer.
  26001. When created, the timer is stopped, so use startTimer() to get it going.
  26002. */
  26003. Timer() noexcept;
  26004. /** Creates a copy of another timer.
  26005. Note that this timer won't be started, even if the one you're copying
  26006. is running.
  26007. */
  26008. Timer (const Timer& other) noexcept;
  26009. public:
  26010. /** Destructor. */
  26011. virtual ~Timer();
  26012. /** The user-defined callback routine that actually gets called periodically.
  26013. It's perfectly ok to call startTimer() or stopTimer() from within this
  26014. callback to change the subsequent intervals.
  26015. */
  26016. virtual void timerCallback() = 0;
  26017. /** Starts the timer and sets the length of interval required.
  26018. If the timer is already started, this will reset it, so the
  26019. time between calling this method and the next timer callback
  26020. will not be less than the interval length passed in.
  26021. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  26022. rounded up to 1)
  26023. */
  26024. void startTimer (int intervalInMilliseconds) noexcept;
  26025. /** Stops the timer.
  26026. No more callbacks will be made after this method returns.
  26027. If this is called from a different thread, any callbacks that may
  26028. be currently executing may be allowed to finish before the method
  26029. returns.
  26030. */
  26031. void stopTimer() noexcept;
  26032. /** Checks if the timer has been started.
  26033. @returns true if the timer is running.
  26034. */
  26035. bool isTimerRunning() const noexcept { return periodMs > 0; }
  26036. /** Returns the timer's interval.
  26037. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  26038. */
  26039. int getTimerInterval() const noexcept { return periodMs; }
  26040. private:
  26041. friend class InternalTimerThread;
  26042. int countdownMs, periodMs;
  26043. Timer* previous;
  26044. Timer* next;
  26045. Timer& operator= (const Timer&);
  26046. };
  26047. #endif // __JUCE_TIMER_JUCEHEADER__
  26048. /*** End of inlined file: juce_Timer.h ***/
  26049. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  26050. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  26051. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  26052. /**
  26053. Animates a set of components, moving them to a new position and/or fading their
  26054. alpha levels.
  26055. To animate a component, create a ComponentAnimator instance or (preferably) use the
  26056. global animator object provided by Desktop::getAnimator(), and call its animateComponent()
  26057. method to commence the movement.
  26058. If you're using your own ComponentAnimator instance, you'll need to make sure it isn't
  26059. deleted before it finishes moving the components, or they'll be abandoned before reaching their
  26060. destinations.
  26061. It's ok to delete components while they're being animated - the animator will detect this
  26062. and safely stop using them.
  26063. The class is a ChangeBroadcaster and sends a notification when any components
  26064. start or finish being animated.
  26065. @see Desktop::getAnimator
  26066. */
  26067. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  26068. private Timer
  26069. {
  26070. public:
  26071. /** Creates a ComponentAnimator. */
  26072. ComponentAnimator();
  26073. /** Destructor. */
  26074. ~ComponentAnimator();
  26075. /** Starts a component moving from its current position to a specified position.
  26076. If the component is already in the middle of an animation, that will be abandoned,
  26077. and a new animation will begin, moving the component from its current location.
  26078. The start and end speed parameters let you apply some acceleration to the component's
  26079. movement.
  26080. @param component the component to move
  26081. @param finalBounds the destination bounds to which the component should move. To leave the
  26082. component in the same place, just pass component->getBounds() for this value
  26083. @param finalAlpha the alpha value that the component should have at the end of the animation
  26084. @param animationDurationMilliseconds how long the animation should last, in milliseconds
  26085. @param useProxyComponent if true, this means the component should be replaced by an internally
  26086. managed temporary component which is a snapshot of the original component.
  26087. This avoids the component having to paint itself as it moves, so may
  26088. be more efficient. This option also allows you to delete the original
  26089. component immediately after starting the animation, because the animation
  26090. can proceed without it. If you use a proxy, the original component will be
  26091. made invisible by this call, and then will become visible again at the end
  26092. of the animation. It'll also mean that the proxy component will be temporarily
  26093. added to the component's parent, so avoid it if this might confuse the parent
  26094. component, or if there's a chance the parent might decide to delete its children.
  26095. @param startSpeed a value to indicate the relative start speed of the animation. If this is 0,
  26096. the component will start by accelerating from rest; higher values mean that it
  26097. will have an initial speed greater than zero. If the value if greater than 1, it
  26098. will decelerate towards the middle of its journey. To move the component at a
  26099. constant rate for its entire animation, set both the start and end speeds to 1.0
  26100. @param endSpeed a relative speed at which the component should be moving when the animation finishes.
  26101. If this is 0, the component will decelerate to a standstill at its final position;
  26102. higher values mean the component will still be moving when it stops. To move the component
  26103. at a constant rate for its entire animation, set both the start and end speeds to 1.0
  26104. */
  26105. void animateComponent (Component* component,
  26106. const Rectangle<int>& finalBounds,
  26107. float finalAlpha,
  26108. int animationDurationMilliseconds,
  26109. bool useProxyComponent,
  26110. double startSpeed,
  26111. double endSpeed);
  26112. /** Begins a fade-out of this components alpha level.
  26113. This is a quick way of invoking animateComponent() with a target alpha value of 0.0f, using
  26114. a proxy. You're safe to delete the component after calling this method, and this won't
  26115. interfere with the animation's progress.
  26116. */
  26117. void fadeOut (Component* component, int millisecondsToTake);
  26118. /** Begins a fade-in of a component.
  26119. This is a quick way of invoking animateComponent() with a target alpha value of 1.0f.
  26120. */
  26121. void fadeIn (Component* component, int millisecondsToTake);
  26122. /** Stops a component if it's currently being animated.
  26123. If moveComponentToItsFinalPosition is true, then the component will
  26124. be immediately moved to its destination position and size. If false, it will be
  26125. left in whatever location it currently occupies.
  26126. */
  26127. void cancelAnimation (Component* component,
  26128. bool moveComponentToItsFinalPosition);
  26129. /** Clears all of the active animations.
  26130. If moveComponentsToTheirFinalPositions is true, all the components will
  26131. be immediately set to their final positions. If false, they will be
  26132. left in whatever locations they currently occupy.
  26133. */
  26134. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  26135. /** Returns the destination position for a component.
  26136. If the component is being animated, this will return the target position that
  26137. was specified when animateComponent() was called.
  26138. If the specified component isn't currently being animated, this method will just
  26139. return its current position.
  26140. */
  26141. const Rectangle<int> getComponentDestination (Component* component);
  26142. /** Returns true if the specified component is currently being animated. */
  26143. bool isAnimating (Component* component) const;
  26144. private:
  26145. class AnimationTask;
  26146. OwnedArray <AnimationTask> tasks;
  26147. uint32 lastTime;
  26148. AnimationTask* findTaskFor (Component* component) const;
  26149. void timerCallback();
  26150. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentAnimator);
  26151. };
  26152. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  26153. /*** End of inlined file: juce_ComponentAnimator.h ***/
  26154. class MouseInputSource;
  26155. class MouseInputSourceInternal;
  26156. class MouseListener;
  26157. /**
  26158. Classes can implement this interface and register themselves with the Desktop class
  26159. to receive callbacks when the currently focused component changes.
  26160. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  26161. */
  26162. class JUCE_API FocusChangeListener
  26163. {
  26164. public:
  26165. /** Destructor. */
  26166. virtual ~FocusChangeListener() {}
  26167. /** Callback to indicate that the currently focused component has changed. */
  26168. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  26169. };
  26170. /**
  26171. Describes and controls aspects of the computer's desktop.
  26172. */
  26173. class JUCE_API Desktop : private DeletedAtShutdown,
  26174. private Timer,
  26175. private AsyncUpdater
  26176. {
  26177. public:
  26178. /** There's only one dektop object, and this method will return it.
  26179. */
  26180. static Desktop& JUCE_CALLTYPE getInstance();
  26181. /** Returns a list of the positions of all the monitors available.
  26182. The first rectangle in the list will be the main monitor area.
  26183. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  26184. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  26185. */
  26186. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const;
  26187. /** Returns the position and size of the main monitor.
  26188. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  26189. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  26190. */
  26191. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const noexcept;
  26192. /** Returns the position and size of the monitor which contains this co-ordinate.
  26193. If none of the monitors contains the point, this will just return the
  26194. main monitor.
  26195. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  26196. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  26197. */
  26198. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  26199. /** Returns the mouse position.
  26200. The co-ordinates are relative to the top-left of the main monitor.
  26201. Note that this is just a shortcut for calling getMainMouseSource().getScreenPosition(), and
  26202. you should only resort to grabbing the global mouse position if there's really no
  26203. way to get the coordinates via a mouse event callback instead.
  26204. */
  26205. static const Point<int> getMousePosition();
  26206. /** Makes the mouse pointer jump to a given location.
  26207. The co-ordinates are relative to the top-left of the main monitor.
  26208. */
  26209. static void setMousePosition (const Point<int>& newPosition);
  26210. /** Returns the last position at which a mouse button was pressed.
  26211. Note that this is just a shortcut for calling getMainMouseSource().getLastMouseDownPosition(),
  26212. and in a multi-touch environment, it doesn't make much sense. ALWAYS prefer to
  26213. get this information via other means, such as MouseEvent::getMouseDownScreenPosition()
  26214. if possible, and only ever call this as a last resort.
  26215. */
  26216. static const Point<int> getLastMouseDownPosition();
  26217. /** Returns the number of times the mouse button has been clicked since the
  26218. app started.
  26219. Each mouse-down event increments this number by 1.
  26220. */
  26221. static int getMouseButtonClickCounter();
  26222. /** This lets you prevent the screensaver from becoming active.
  26223. Handy if you're running some sort of presentation app where having a screensaver
  26224. appear would be annoying.
  26225. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  26226. won't enable a screensaver unless the user has actually set one up).
  26227. The disablement will only happen while the Juce application is the foreground
  26228. process - if another task is running in front of it, then the screensaver will
  26229. be unaffected.
  26230. @see isScreenSaverEnabled
  26231. */
  26232. static void setScreenSaverEnabled (bool isEnabled);
  26233. /** Returns true if the screensaver has not been turned off.
  26234. This will return the last value passed into setScreenSaverEnabled(). Note that
  26235. it won't tell you whether the user is actually using a screen saver, just
  26236. whether this app is deliberately preventing one from running.
  26237. @see setScreenSaverEnabled
  26238. */
  26239. static bool isScreenSaverEnabled();
  26240. /** Registers a MouseListener that will receive all mouse events that occur on
  26241. any component.
  26242. @see removeGlobalMouseListener
  26243. */
  26244. void addGlobalMouseListener (MouseListener* listener);
  26245. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  26246. method.
  26247. @see addGlobalMouseListener
  26248. */
  26249. void removeGlobalMouseListener (MouseListener* listener);
  26250. /** Registers a MouseListener that will receive a callback whenever the focused
  26251. component changes.
  26252. */
  26253. void addFocusChangeListener (FocusChangeListener* listener);
  26254. /** Unregisters a listener that was added with addFocusChangeListener(). */
  26255. void removeFocusChangeListener (FocusChangeListener* listener);
  26256. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  26257. The component must already be on the desktop for this method to work. It will
  26258. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  26259. etc will be hidden.
  26260. To exit kiosk mode, just call setKioskModeComponent (nullptr). When this is called,
  26261. the component that's currently being used will be resized back to the size
  26262. and position it was in before being put into this mode.
  26263. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  26264. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  26265. to hide as much on-screen paraphenalia as possible.
  26266. */
  26267. void setKioskModeComponent (Component* componentToUse,
  26268. bool allowMenusAndBars = true);
  26269. /** Returns the component that is currently being used in kiosk-mode.
  26270. This is the component that was last set by setKioskModeComponent(). If none
  26271. has been set, this returns 0.
  26272. */
  26273. Component* getKioskModeComponent() const noexcept { return kioskModeComponent; }
  26274. /** Returns the number of components that are currently active as top-level
  26275. desktop windows.
  26276. @see getComponent, Component::addToDesktop
  26277. */
  26278. int getNumComponents() const noexcept;
  26279. /** Returns one of the top-level desktop window components.
  26280. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  26281. index is out-of-range.
  26282. @see getNumComponents, Component::addToDesktop
  26283. */
  26284. Component* getComponent (int index) const noexcept;
  26285. /** Finds the component at a given screen location.
  26286. This will drill down into top-level windows to find the child component at
  26287. the given position.
  26288. Returns 0 if the co-ordinates are inside a non-Juce window.
  26289. */
  26290. Component* findComponentAt (const Point<int>& screenPosition) const;
  26291. /** The Desktop object has a ComponentAnimator instance which can be used for performing
  26292. your animations.
  26293. Having a single shared ComponentAnimator object makes it more efficient when multiple
  26294. components are being moved around simultaneously. It's also more convenient than having
  26295. to manage your own instance of one.
  26296. @see ComponentAnimator
  26297. */
  26298. ComponentAnimator& getAnimator() noexcept { return animator; }
  26299. /** Returns the current default look-and-feel for components which don't have one
  26300. explicitly set.
  26301. @see setDefaultLookAndFeel
  26302. */
  26303. LookAndFeel& getDefaultLookAndFeel() noexcept;
  26304. /** Changes the default look-and-feel.
  26305. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  26306. set to nullptr, it will revert to using the system's
  26307. default one. The object passed-in must be deleted by the
  26308. caller when it's no longer needed.
  26309. @see getDefaultLookAndFeel
  26310. */
  26311. void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel);
  26312. /** Returns the number of MouseInputSource objects the system has at its disposal.
  26313. In a traditional single-mouse system, there might be only one object. On a multi-touch
  26314. system, there could be one input source per potential finger.
  26315. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  26316. @see getMouseSource
  26317. */
  26318. int getNumMouseSources() const noexcept { return mouseSources.size(); }
  26319. /** Returns one of the system's MouseInputSource objects.
  26320. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  26321. a null pointer.
  26322. In a traditional single-mouse system, there might be only one object. On a multi-touch
  26323. system, there could be one input source per potential finger.
  26324. */
  26325. MouseInputSource* getMouseSource (int index) const noexcept { return mouseSources [index]; }
  26326. /** Returns the main mouse input device that the system is using.
  26327. @see getNumMouseSources()
  26328. */
  26329. MouseInputSource& getMainMouseSource() const noexcept { return *mouseSources.getUnchecked(0); }
  26330. /** Returns the number of mouse-sources that are currently being dragged.
  26331. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  26332. juce component has the button down on it. In a multi-touch system, this could
  26333. be any number from 0 to the number of simultaneous touches that can be detected.
  26334. */
  26335. int getNumDraggingMouseSources() const noexcept;
  26336. /** Returns one of the mouse sources that's currently being dragged.
  26337. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  26338. out of range, or if no mice or fingers are down, this will return a null pointer.
  26339. */
  26340. MouseInputSource* getDraggingMouseSource (int index) const noexcept;
  26341. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  26342. current mouse-drag operation.
  26343. This allows you to make sure that mouseDrag() events are sent continuously, even
  26344. when the mouse isn't moving. This can be useful for things like auto-scrolling
  26345. components when the mouse is near an edge.
  26346. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  26347. minimum interval between consecutive mouse drag callbacks. The callbacks
  26348. will continue until the mouse is released, and then the interval will be reset,
  26349. so you need to make sure it's called every time you begin a drag event.
  26350. Passing an interval of 0 or less will cancel the auto-repeat.
  26351. @see mouseDrag
  26352. */
  26353. void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  26354. /** In a tablet device which can be turned around, this is used to inidicate the orientation. */
  26355. enum DisplayOrientation
  26356. {
  26357. upright = 1, /**< Indicates that the display is the normal way up. */
  26358. upsideDown = 2, /**< Indicates that the display is upside-down. */
  26359. rotatedClockwise = 4, /**< Indicates that the display is turned 90 degrees clockwise from its upright position. */
  26360. rotatedAntiClockwise = 8, /**< Indicates that the display is turned 90 degrees anti-clockwise from its upright position. */
  26361. allOrientations = 1 + 2 + 4 + 8 /**< A combination of all the orientation values */
  26362. };
  26363. /** In a tablet device which can be turned around, this returns the current orientation. */
  26364. DisplayOrientation getCurrentOrientation() const;
  26365. /** Sets which orientations the display is allowed to auto-rotate to.
  26366. For devices that support rotating desktops, this lets you specify which of the orientations your app can use.
  26367. The parameter is a bitwise or-ed combination of the values in DisplayOrientation, and must contain at least one
  26368. set bit.
  26369. */
  26370. void setOrientationsEnabled (int allowedOrientations);
  26371. /** Returns whether the display is allowed to auto-rotate to the given orientation.
  26372. Each orientation can be enabled using setOrientationEnabled(). By default, all orientations are allowed.
  26373. */
  26374. bool isOrientationEnabled (DisplayOrientation orientation) const noexcept;
  26375. /** Tells this object to refresh its idea of what the screen resolution is.
  26376. (Called internally by the native code).
  26377. */
  26378. void refreshMonitorSizes();
  26379. /** True if the OS supports semitransparent windows */
  26380. static bool canUseSemiTransparentWindows() noexcept;
  26381. private:
  26382. static Desktop* instance;
  26383. friend class Component;
  26384. friend class ComponentPeer;
  26385. friend class MouseInputSource;
  26386. friend class MouseInputSourceInternal;
  26387. friend class DeletedAtShutdown;
  26388. friend class TopLevelWindowManager;
  26389. OwnedArray <MouseInputSource> mouseSources;
  26390. void createMouseInputSources();
  26391. ListenerList <MouseListener> mouseListeners;
  26392. ListenerList <FocusChangeListener> focusListeners;
  26393. Array <Component*> desktopComponents;
  26394. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  26395. Point<int> lastFakeMouseMove;
  26396. void sendMouseMove();
  26397. int mouseClickCounter;
  26398. void incrementMouseClickCounter() noexcept;
  26399. ScopedPointer<Timer> dragRepeater;
  26400. ScopedPointer<LookAndFeel> defaultLookAndFeel;
  26401. WeakReference<LookAndFeel> currentLookAndFeel;
  26402. Component* kioskModeComponent;
  26403. Rectangle<int> kioskComponentOriginalBounds;
  26404. int allowedOrientations;
  26405. ComponentAnimator animator;
  26406. void timerCallback();
  26407. void resetTimer();
  26408. int getNumDisplayMonitors() const noexcept;
  26409. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const noexcept;
  26410. static void getCurrentMonitorPositions (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea);
  26411. void addDesktopComponent (Component* c);
  26412. void removeDesktopComponent (Component* c);
  26413. void componentBroughtToFront (Component* c);
  26414. static void setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  26415. void triggerFocusCallback();
  26416. void handleAsyncUpdate();
  26417. Desktop();
  26418. ~Desktop();
  26419. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Desktop);
  26420. };
  26421. #endif // __JUCE_DESKTOP_JUCEHEADER__
  26422. /*** End of inlined file: juce_Desktop.h ***/
  26423. class KeyPressMappingSet;
  26424. class ApplicationCommandManagerListener;
  26425. /**
  26426. One of these objects holds a list of all the commands your app can perform,
  26427. and despatches these commands when needed.
  26428. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  26429. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  26430. to invoke automatically, which means you don't have to handle the result of a menu
  26431. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  26432. which can choose which events they want to handle.
  26433. This architecture also allows for nested ApplicationCommandTargets, so that for example
  26434. you could have two different objects, one inside the other, both of which can respond to
  26435. a "delete" command. Depending on which one has focus, the command will be sent to the
  26436. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  26437. method.
  26438. To set up your app to use commands, you'll need to do the following:
  26439. - Create a global ApplicationCommandManager to hold the list of all possible
  26440. commands. (This will also manage a set of key-mappings for them).
  26441. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  26442. This allows the object to provide a list of commands that it can perform, and
  26443. to handle them.
  26444. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  26445. or ApplicationCommandManager::registerCommand().
  26446. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  26447. method to access the key-mapper object, which you will need to register as a key-listener
  26448. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  26449. about setting this up.
  26450. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  26451. cause these commands to be invoked automatically.
  26452. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  26453. When a command is invoked, the ApplicationCommandManager will try to choose the best
  26454. ApplicationCommandTarget to receive the specified command. To do this it will use the
  26455. current keyboard focus to see which component might be interested, and will search the
  26456. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  26457. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  26458. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  26459. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  26460. point if the command still hasn't been performed, it will be passed to the current
  26461. JUCEApplication object (which is itself an ApplicationCommandTarget).
  26462. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  26463. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  26464. the object yourself.
  26465. @see ApplicationCommandTarget, ApplicationCommandInfo
  26466. */
  26467. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  26468. private FocusChangeListener
  26469. {
  26470. public:
  26471. /** Creates an ApplicationCommandManager.
  26472. Once created, you'll need to register all your app's commands with it, using
  26473. ApplicationCommandManager::registerAllCommandsForTarget() or
  26474. ApplicationCommandManager::registerCommand().
  26475. */
  26476. ApplicationCommandManager();
  26477. /** Destructor.
  26478. Make sure that you don't delete this if pointers to it are still being used by
  26479. objects such as PopupMenus or Buttons.
  26480. */
  26481. virtual ~ApplicationCommandManager();
  26482. /** Clears the current list of all commands.
  26483. Note that this will also clear the contents of the KeyPressMappingSet.
  26484. */
  26485. void clearCommands();
  26486. /** Adds a command to the list of registered commands.
  26487. @see registerAllCommandsForTarget
  26488. */
  26489. void registerCommand (const ApplicationCommandInfo& newCommand);
  26490. /** Adds all the commands that this target publishes to the manager's list.
  26491. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  26492. to get details about all the commands that this target can do, and will call
  26493. registerCommand() to add each one to the manger's list.
  26494. @see registerCommand
  26495. */
  26496. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  26497. /** Removes the command with a specified ID.
  26498. Note that this will also remove any key mappings that are mapped to the command.
  26499. */
  26500. void removeCommand (CommandID commandID);
  26501. /** This should be called to tell the manager that one of its registered commands may have changed
  26502. its active status.
  26503. Because the command manager only finds out whether a command is active or inactive by querying
  26504. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  26505. allows things like buttons to update their enablement, etc.
  26506. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  26507. for any registered listeners.
  26508. */
  26509. void commandStatusChanged();
  26510. /** Returns the number of commands that have been registered.
  26511. @see registerCommand
  26512. */
  26513. int getNumCommands() const noexcept { return commands.size(); }
  26514. /** Returns the details about one of the registered commands.
  26515. The index is between 0 and (getNumCommands() - 1).
  26516. */
  26517. const ApplicationCommandInfo* getCommandForIndex (int index) const noexcept { return commands [index]; }
  26518. /** Returns the details about a given command ID.
  26519. This will search the list of registered commands for one with the given command
  26520. ID number, and return its associated info. If no matching command is found, this
  26521. will return 0.
  26522. */
  26523. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const noexcept;
  26524. /** Returns the name field for a command.
  26525. An empty string is returned if no command with this ID has been registered.
  26526. @see getDescriptionOfCommand
  26527. */
  26528. String getNameOfCommand (CommandID commandID) const noexcept;
  26529. /** Returns the description field for a command.
  26530. An empty string is returned if no command with this ID has been registered. If the
  26531. command has no description, this will return its short name field instead.
  26532. @see getNameOfCommand
  26533. */
  26534. String getDescriptionOfCommand (CommandID commandID) const noexcept;
  26535. /** Returns the list of categories.
  26536. This will go through all registered commands, and return a list of all the distict
  26537. categoryName values from their ApplicationCommandInfo structure.
  26538. @see getCommandsInCategory()
  26539. */
  26540. StringArray getCommandCategories() const;
  26541. /** Returns a list of all the command UIDs in a particular category.
  26542. @see getCommandCategories()
  26543. */
  26544. Array<CommandID> getCommandsInCategory (const String& categoryName) const;
  26545. /** Returns the manager's internal set of key mappings.
  26546. This object can be used to edit the keypresses. To actually link this object up
  26547. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  26548. class.
  26549. @see KeyPressMappingSet
  26550. */
  26551. KeyPressMappingSet* getKeyMappings() const noexcept { return keyMappings; }
  26552. /** Invokes the given command directly, sending it to the default target.
  26553. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  26554. structure.
  26555. */
  26556. bool invokeDirectly (CommandID commandID, bool asynchronously);
  26557. /** Sends a command to the default target.
  26558. This will choose a target using getFirstCommandTarget(), and send the specified command
  26559. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  26560. first target can't handle the command, it will be passed on to targets further down the
  26561. chain (see ApplicationCommandTarget::invoke() for more info).
  26562. @param invocationInfo this must be correctly filled-in, describing the context for
  26563. the invocation.
  26564. @param asynchronously if false, the command will be performed before this method returns.
  26565. If true, a message will be posted so that the command will be performed
  26566. later on the message thread, and this method will return immediately.
  26567. @see ApplicationCommandTarget::invoke
  26568. */
  26569. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  26570. bool asynchronously);
  26571. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  26572. Whenever the manager needs to know which target a command should be sent to, it calls
  26573. this method to determine the first one to try.
  26574. By default, this method will return the target that was set by calling setFirstCommandTarget().
  26575. If no target is set, it will return the result of findDefaultComponentTarget().
  26576. If you need to make sure all commands go via your own custom target, then you can
  26577. either use setFirstCommandTarget() to specify a single target, or override this method
  26578. if you need more complex logic to choose one.
  26579. It may return 0 if no targets are available.
  26580. @see getTargetForCommand, invoke, invokeDirectly
  26581. */
  26582. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  26583. /** Sets a target to be returned by getFirstCommandTarget().
  26584. If this is set to 0, then getFirstCommandTarget() will by default return the
  26585. result of findDefaultComponentTarget().
  26586. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  26587. deleting the target object.
  26588. */
  26589. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) noexcept;
  26590. /** Tries to find the best target to use to perform a given command.
  26591. This will call getFirstCommandTarget() to find the preferred target, and will
  26592. check whether that target can handle the given command. If it can't, then it'll use
  26593. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  26594. so on until no more are available.
  26595. If no targets are found that can perform the command, this method will return 0.
  26596. If a target is found, then it will get the target to fill-in the upToDateInfo
  26597. structure with the latest info about that command, so that the caller can see
  26598. whether the command is disabled, ticked, etc.
  26599. */
  26600. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  26601. ApplicationCommandInfo& upToDateInfo);
  26602. /** Registers a listener that will be called when various events occur. */
  26603. void addListener (ApplicationCommandManagerListener* listener);
  26604. /** Deregisters a previously-added listener. */
  26605. void removeListener (ApplicationCommandManagerListener* listener);
  26606. /** Looks for a suitable command target based on which Components have the keyboard focus.
  26607. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  26608. but is exposed here in case it's useful.
  26609. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  26610. windows, etc., and using the findTargetForComponent() method.
  26611. */
  26612. static ApplicationCommandTarget* findDefaultComponentTarget();
  26613. /** Examines this component and all its parents in turn, looking for the first one
  26614. which is a ApplicationCommandTarget.
  26615. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  26616. that class.
  26617. */
  26618. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  26619. private:
  26620. OwnedArray <ApplicationCommandInfo> commands;
  26621. ListenerList <ApplicationCommandManagerListener> listeners;
  26622. ScopedPointer <KeyPressMappingSet> keyMappings;
  26623. ApplicationCommandTarget* firstTarget;
  26624. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  26625. void handleAsyncUpdate();
  26626. void globalFocusChanged (Component*);
  26627. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  26628. // This is just here to cause a compile error in old code that hasn't been changed to use the new
  26629. // version of this method.
  26630. virtual short getFirstCommandTarget() { return 0; }
  26631. #endif
  26632. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandManager);
  26633. };
  26634. /**
  26635. A listener that receives callbacks from an ApplicationCommandManager when
  26636. commands are invoked or the command list is changed.
  26637. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  26638. */
  26639. class JUCE_API ApplicationCommandManagerListener
  26640. {
  26641. public:
  26642. /** Destructor. */
  26643. virtual ~ApplicationCommandManagerListener() {}
  26644. /** Called when an app command is about to be invoked. */
  26645. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  26646. /** Called when commands are registered or deregistered from the
  26647. command manager, or when commands are made active or inactive.
  26648. Note that if you're using this to watch for changes to whether a command is disabled,
  26649. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  26650. whenever the status of your command might have changed.
  26651. */
  26652. virtual void applicationCommandListChanged() = 0;
  26653. };
  26654. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  26655. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  26656. #endif
  26657. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  26658. #endif
  26659. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26660. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  26661. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26662. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26663. /*** Start of inlined file: juce_PropertiesFile.h ***/
  26664. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  26665. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  26666. /** Wrapper on a file that stores a list of key/value data pairs.
  26667. Useful for storing application settings, etc. See the PropertySet class for
  26668. the interfaces that read and write values.
  26669. Not designed for very large amounts of data, as it keeps all the values in
  26670. memory and writes them out to disk lazily when they are changed.
  26671. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  26672. with it, and these will be signalled when a value changes.
  26673. @see PropertySet
  26674. */
  26675. class JUCE_API PropertiesFile : public PropertySet,
  26676. public ChangeBroadcaster,
  26677. private Timer
  26678. {
  26679. public:
  26680. enum StorageFormat
  26681. {
  26682. storeAsBinary,
  26683. storeAsCompressedBinary,
  26684. storeAsXML
  26685. };
  26686. struct Options
  26687. {
  26688. /** Creates an empty Options structure.
  26689. You'll need to fill-in the data memebers appropriately before using this structure.
  26690. */
  26691. Options();
  26692. /** The name of your application - this is used to help generate the path and filename
  26693. at which the properties file will be stored. */
  26694. String applicationName;
  26695. /** The suffix to use for your properties file.
  26696. It doesn't really matter what this is - you may want to use ".settings" or
  26697. ".properties" or something.
  26698. */
  26699. String filenameSuffix;
  26700. /** The name of a subfolder in which you'd like your properties file to live.
  26701. See the getDefaultFile() method for more details about how this is used.
  26702. */
  26703. String folderName;
  26704. /** If you're using properties files on a Mac, you must set this value - failure to
  26705. do so will cause a runtime assertion.
  26706. The PropertiesFile class always used to put its settings files in "Library/Preferences", but Apple
  26707. have changed their advice, and now stipulate that settings should go in "Library/Application Support".
  26708. Because older apps would be broken by a silent change in this class's behaviour, you must now
  26709. explicitly set the osxLibrarySubFolder value to indicate which path you want to use.
  26710. In newer apps, you should always set this to "Application Support".
  26711. If your app needs to load settings files that were created by older versions of juce and
  26712. you want to maintain backwards-compatibility, then you can set this to "Preferences".
  26713. But.. for better Apple-compliance, the recommended approach would be to write some code that
  26714. finds your old settings files in ~/Library/Preferences, moves them to ~/Library/Application Support,
  26715. and then uses the new path.
  26716. */
  26717. String osxLibrarySubFolder;
  26718. /** If true, the file will be created in a location that's shared between users.
  26719. The default constructor initialises this value to false.
  26720. */
  26721. bool commonToAllUsers;
  26722. /** If true, this means that property names are matched in a case-insensitive manner.
  26723. See the PropertySet constructor for more info.
  26724. The default constructor initialises this value to false.
  26725. */
  26726. bool ignoreCaseOfKeyNames;
  26727. /** If this is zero or greater, then after a value is changed, the object will wait
  26728. for this amount of time and then save the file. If this zero, the file will be
  26729. written to disk immediately on being changed (which might be slow, as it'll re-write
  26730. synchronously each time a value-change method is called). If it is less than zero,
  26731. the file won't be saved until save() or saveIfNeeded() are explicitly called.
  26732. The default constructor sets this to a reasonable value of a few seconds, so you
  26733. only need to change it if you need a special case.
  26734. */
  26735. int millisecondsBeforeSaving;
  26736. /** Specifies whether the file should be written as XML, binary, etc.
  26737. The default constructor sets this to storeAsXML, so you only need to set it explicitly
  26738. if you want to use a different format.
  26739. */
  26740. StorageFormat storageFormat;
  26741. /** An optional InterprocessLock object that will be used to prevent multiple threads or
  26742. processes from writing to the file at the same time. The PropertiesFile will keep a
  26743. pointer to this object but will not take ownership of it - the caller is responsible for
  26744. making sure that the lock doesn't get deleted before the PropertiesFile has been deleted.
  26745. The default constructor initialises this value to nullptr, so you don't need to touch it
  26746. unless you want to use a lock.
  26747. */
  26748. InterProcessLock* processLock;
  26749. /** This can be called to suggest a file that should be used, based on the values
  26750. in this structure.
  26751. So on a Mac, this will return a file called:
  26752. ~/Library/[osxLibrarySubFolder]/[folderName]/[applicationName].[filenameSuffix]
  26753. On Windows it'll return something like:
  26754. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[filenameSuffix]
  26755. On Linux it'll return
  26756. ~/.[folderName]/[applicationName].[filenameSuffix]
  26757. If the folderName variable is empty, it'll use the app name for this (or omit the
  26758. folder name on the Mac).
  26759. The paths will also vary depending on whether commonToAllUsers is true.
  26760. */
  26761. File getDefaultFile() const;
  26762. };
  26763. /** Creates a PropertiesFile object.
  26764. The file used will be chosen by calling PropertiesFile::Options::getDefaultFile()
  26765. for the options provided. To set the file explicitly, use the other constructor.
  26766. */
  26767. explicit PropertiesFile (const Options& options);
  26768. /** Creates a PropertiesFile object.
  26769. Unlike the other constructor, this one allows you to explicitly set the file that you
  26770. want to be used, rather than using the default one.
  26771. */
  26772. PropertiesFile (const File& file,
  26773. const Options& options);
  26774. /** Destructor.
  26775. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  26776. */
  26777. ~PropertiesFile();
  26778. /** Returns true if this file was created from a valid (or non-existent) file.
  26779. If the file failed to load correctly because it was corrupt or had insufficient
  26780. access, this will be false.
  26781. */
  26782. bool isValidFile() const noexcept { return loadedOk; }
  26783. /** This will flush all the values to disk if they've changed since the last
  26784. time they were saved.
  26785. Returns false if it fails to write to the file for some reason (maybe because
  26786. it's read-only or the directory doesn't exist or something).
  26787. @see save
  26788. */
  26789. bool saveIfNeeded();
  26790. /** This will force a write-to-disk of the current values, regardless of whether
  26791. anything has changed since the last save.
  26792. Returns false if it fails to write to the file for some reason (maybe because
  26793. it's read-only or the directory doesn't exist or something).
  26794. @see saveIfNeeded
  26795. */
  26796. bool save();
  26797. /** Returns true if the properties have been altered since the last time they were saved.
  26798. The file is flagged as needing to be saved when you change a value, but you can
  26799. explicitly set this flag with setNeedsToBeSaved().
  26800. */
  26801. bool needsToBeSaved() const;
  26802. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  26803. @see needsToBeSaved
  26804. */
  26805. void setNeedsToBeSaved (bool needsToBeSaved);
  26806. /** Returns the file that's being used. */
  26807. File getFile() const { return file; }
  26808. protected:
  26809. /** @internal */
  26810. virtual void propertyChanged();
  26811. private:
  26812. File file;
  26813. Options options;
  26814. bool loadedOk, needsWriting;
  26815. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  26816. InterProcessLock::ScopedLockType* createProcessLock() const;
  26817. void timerCallback();
  26818. void initialise();
  26819. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertiesFile);
  26820. };
  26821. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  26822. /*** End of inlined file: juce_PropertiesFile.h ***/
  26823. /**
  26824. Manages a collection of properties.
  26825. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  26826. as a singleton.
  26827. It holds two different PropertiesFile objects internally, one for user-specific
  26828. settings (stored in your user directory), and one for settings that are common to
  26829. all users (stored in a folder accessible to all users).
  26830. The class manages the creation of these files on-demand, allowing access via the
  26831. getUserSettings() and getCommonSettings() methods. It also has a few handy
  26832. methods like testWriteAccess() to check that the files can be saved.
  26833. If you're using one of these as a singleton, then your app's start-up code should
  26834. first of all call setStorageParameters() to tell it the parameters to use to create
  26835. the properties files.
  26836. @see PropertiesFile
  26837. */
  26838. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  26839. {
  26840. public:
  26841. /**
  26842. Creates an ApplicationProperties object.
  26843. Before using it, you must call setStorageParameters() to give it the info
  26844. it needs to create the property files.
  26845. */
  26846. ApplicationProperties();
  26847. /** Destructor. */
  26848. ~ApplicationProperties();
  26849. juce_DeclareSingleton (ApplicationProperties, false);
  26850. /** Gives the object the information it needs to create the appropriate properties files.
  26851. See the PropertiesFile::Options class for details about what options you need to set.
  26852. */
  26853. void setStorageParameters (const PropertiesFile::Options& options);
  26854. /** Tests whether the files can be successfully written to, and can show
  26855. an error message if not.
  26856. Returns true if none of the tests fail.
  26857. @param testUserSettings if true, the user settings file will be tested
  26858. @param testCommonSettings if true, the common settings file will be tested
  26859. @param showWarningDialogOnFailure if true, the method will show a helpful error
  26860. message box if either of the tests fail
  26861. */
  26862. bool testWriteAccess (bool testUserSettings,
  26863. bool testCommonSettings,
  26864. bool showWarningDialogOnFailure);
  26865. /** Returns the user settings file.
  26866. The first time this is called, it will create and load the properties file.
  26867. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  26868. the common settings are used as a second-chance place to look. This is done via the
  26869. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  26870. to the fallback for the user settings.
  26871. @see getCommonSettings
  26872. */
  26873. PropertiesFile* getUserSettings();
  26874. /** Returns the common settings file.
  26875. The first time this is called, it will create and load the properties file.
  26876. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  26877. read-only (e.g. because the user doesn't have permission to write
  26878. to shared files), then this will return the user settings instead,
  26879. (like getUserSettings() would do). This is handy if you'd like to
  26880. write a value to the common settings, but if that's no possible,
  26881. then you'd rather write to the user settings than none at all.
  26882. If returnUserPropsIfReadOnly is false, this method will always return
  26883. the common settings, even if any changes to them can't be saved.
  26884. @see getUserSettings
  26885. */
  26886. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly);
  26887. /** Saves both files if they need to be saved.
  26888. @see PropertiesFile::saveIfNeeded
  26889. */
  26890. bool saveIfNeeded();
  26891. /** Flushes and closes both files if they are open.
  26892. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  26893. and closes both files. They will then be re-opened the next time getUserSettings()
  26894. or getCommonSettings() is called.
  26895. */
  26896. void closeFiles();
  26897. private:
  26898. PropertiesFile::Options options;
  26899. ScopedPointer <PropertiesFile> userProps, commonProps;
  26900. int commonSettingsAreReadOnly;
  26901. void openFiles();
  26902. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationProperties);
  26903. };
  26904. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26905. /*** End of inlined file: juce_ApplicationProperties.h ***/
  26906. #endif
  26907. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26908. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  26909. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26910. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26911. /*** Start of inlined file: juce_AudioFormat.h ***/
  26912. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26913. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  26914. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  26915. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26916. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26917. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  26918. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26919. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26920. /**
  26921. This class a container which holds all the classes pertaining to the AudioData::Pointer
  26922. audio sample format class.
  26923. @see AudioData::Pointer.
  26924. */
  26925. class JUCE_API AudioData
  26926. {
  26927. public:
  26928. // These types can be used as the SampleFormat template parameter for the AudioData::Pointer class.
  26929. class Int8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit integer packed data format. */
  26930. class UInt8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit unsigned integer packed data format. */
  26931. class Int16; /**< Used as a template parameter for AudioData::Pointer. Indicates an 16-bit integer packed data format. */
  26932. class Int24; /**< Used as a template parameter for AudioData::Pointer. Indicates an 24-bit integer packed data format. */
  26933. class Int32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit integer packed data format. */
  26934. class Float32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit float data format. */
  26935. // These types can be used as the Endianness template parameter for the AudioData::Pointer class.
  26936. class BigEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in big-endian order. */
  26937. class LittleEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in little-endian order. */
  26938. class NativeEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in the CPU's native endianness. */
  26939. // These types can be used as the InterleavingType template parameter for the AudioData::Pointer class.
  26940. class NonInterleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored contiguously. */
  26941. class Interleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are interleaved with a number of other channels. */
  26942. // These types can be used as the Constness template parameter for the AudioData::Pointer class.
  26943. class NonConst; /**< Used as a template parameter for AudioData::Pointer. Indicates that the pointer can be used for non-const data. */
  26944. class Const; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples can only be used for const data.. */
  26945. #ifndef DOXYGEN
  26946. class BigEndian
  26947. {
  26948. public:
  26949. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) noexcept { return s.getAsFloatBE(); }
  26950. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) noexcept { s.setAsFloatBE (newValue); }
  26951. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) noexcept { return s.getAsInt32BE(); }
  26952. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) noexcept { s.setAsInt32BE (newValue); }
  26953. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) noexcept { dest.copyFromBE (source); }
  26954. enum { isBigEndian = 1 };
  26955. };
  26956. class LittleEndian
  26957. {
  26958. public:
  26959. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) noexcept { return s.getAsFloatLE(); }
  26960. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) noexcept { s.setAsFloatLE (newValue); }
  26961. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) noexcept { return s.getAsInt32LE(); }
  26962. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) noexcept { s.setAsInt32LE (newValue); }
  26963. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) noexcept { dest.copyFromLE (source); }
  26964. enum { isBigEndian = 0 };
  26965. };
  26966. #if JUCE_BIG_ENDIAN
  26967. class NativeEndian : public BigEndian {};
  26968. #else
  26969. class NativeEndian : public LittleEndian {};
  26970. #endif
  26971. class Int8
  26972. {
  26973. public:
  26974. inline Int8 (void* data_) noexcept : data (static_cast <int8*> (data_)) {}
  26975. inline void advance() noexcept { ++data; }
  26976. inline void skip (int numSamples) noexcept { data += numSamples; }
  26977. inline float getAsFloatLE() const noexcept { return (float) (*data * (1.0 / (1.0 + maxValue))); }
  26978. inline float getAsFloatBE() const noexcept { return getAsFloatLE(); }
  26979. inline void setAsFloatLE (float newValue) noexcept { *data = (int8) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))); }
  26980. inline void setAsFloatBE (float newValue) noexcept { setAsFloatLE (newValue); }
  26981. inline int32 getAsInt32LE() const noexcept { return (int) (*data << 24); }
  26982. inline int32 getAsInt32BE() const noexcept { return getAsInt32LE(); }
  26983. inline void setAsInt32LE (int newValue) noexcept { *data = (int8) (newValue >> 24); }
  26984. inline void setAsInt32BE (int newValue) noexcept { setAsInt32LE (newValue); }
  26985. inline void clear() noexcept { *data = 0; }
  26986. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  26987. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  26988. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  26989. inline void copyFromSameType (Int8& source) noexcept { *data = *source.data; }
  26990. int8* data;
  26991. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26992. };
  26993. class UInt8
  26994. {
  26995. public:
  26996. inline UInt8 (void* data_) noexcept : data (static_cast <uint8*> (data_)) {}
  26997. inline void advance() noexcept { ++data; }
  26998. inline void skip (int numSamples) noexcept { data += numSamples; }
  26999. inline float getAsFloatLE() const noexcept { return (float) ((*data - 128) * (1.0 / (1.0 + maxValue))); }
  27000. inline float getAsFloatBE() const noexcept { return getAsFloatLE(); }
  27001. inline void setAsFloatLE (float newValue) noexcept { *data = (uint8) jlimit (0, 255, 128 + roundToInt (newValue * (1.0 + maxValue))); }
  27002. inline void setAsFloatBE (float newValue) noexcept { setAsFloatLE (newValue); }
  27003. inline int32 getAsInt32LE() const noexcept { return (int) ((*data - 128) << 24); }
  27004. inline int32 getAsInt32BE() const noexcept { return getAsInt32LE(); }
  27005. inline void setAsInt32LE (int newValue) noexcept { *data = (uint8) (128 + (newValue >> 24)); }
  27006. inline void setAsInt32BE (int newValue) noexcept { setAsInt32LE (newValue); }
  27007. inline void clear() noexcept { *data = 128; }
  27008. inline void clearMultiple (int num) noexcept { memset (data, 128, num) ;}
  27009. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  27010. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  27011. inline void copyFromSameType (UInt8& source) noexcept { *data = *source.data; }
  27012. uint8* data;
  27013. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  27014. };
  27015. class Int16
  27016. {
  27017. public:
  27018. inline Int16 (void* data_) noexcept : data (static_cast <uint16*> (data_)) {}
  27019. inline void advance() noexcept { ++data; }
  27020. inline void skip (int numSamples) noexcept { data += numSamples; }
  27021. inline float getAsFloatLE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfBigEndian (*data)); }
  27022. inline float getAsFloatBE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfLittleEndian (*data)); }
  27023. inline void setAsFloatLE (float newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  27024. inline void setAsFloatBE (float newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  27025. inline int32 getAsInt32LE() const noexcept { return (int32) (ByteOrder::swapIfBigEndian ((uint16) *data) << 16); }
  27026. inline int32 getAsInt32BE() const noexcept { return (int32) (ByteOrder::swapIfLittleEndian ((uint16) *data) << 16); }
  27027. inline void setAsInt32LE (int32 newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint16) (newValue >> 16)); }
  27028. inline void setAsInt32BE (int32 newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint16) (newValue >> 16)); }
  27029. inline void clear() noexcept { *data = 0; }
  27030. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  27031. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  27032. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  27033. inline void copyFromSameType (Int16& source) noexcept { *data = *source.data; }
  27034. uint16* data;
  27035. enum { bytesPerSample = 2, maxValue = 0x7fff, resolution = (1 << 16), isFloat = 0 };
  27036. };
  27037. class Int24
  27038. {
  27039. public:
  27040. inline Int24 (void* data_) noexcept : data (static_cast <char*> (data_)) {}
  27041. inline void advance() noexcept { data += 3; }
  27042. inline void skip (int numSamples) noexcept { data += 3 * numSamples; }
  27043. inline float getAsFloatLE() const noexcept { return (float) (ByteOrder::littleEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  27044. inline float getAsFloatBE() const noexcept { return (float) (ByteOrder::bigEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  27045. inline void setAsFloatLE (float newValue) noexcept { ByteOrder::littleEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  27046. inline void setAsFloatBE (float newValue) noexcept { ByteOrder::bigEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  27047. inline int32 getAsInt32LE() const noexcept { return (int32) ByteOrder::littleEndian24Bit (data) << 8; }
  27048. inline int32 getAsInt32BE() const noexcept { return (int32) ByteOrder::bigEndian24Bit (data) << 8; }
  27049. inline void setAsInt32LE (int32 newValue) noexcept { ByteOrder::littleEndian24BitToChars (newValue >> 8, data); }
  27050. inline void setAsInt32BE (int32 newValue) noexcept { ByteOrder::bigEndian24BitToChars (newValue >> 8, data); }
  27051. inline void clear() noexcept { data[0] = 0; data[1] = 0; data[2] = 0; }
  27052. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  27053. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  27054. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  27055. inline void copyFromSameType (Int24& source) noexcept { data[0] = source.data[0]; data[1] = source.data[1]; data[2] = source.data[2]; }
  27056. char* data;
  27057. enum { bytesPerSample = 3, maxValue = 0x7fffff, resolution = (1 << 8), isFloat = 0 };
  27058. };
  27059. class Int32
  27060. {
  27061. public:
  27062. inline Int32 (void* data_) noexcept : data (static_cast <uint32*> (data_)) {}
  27063. inline void advance() noexcept { ++data; }
  27064. inline void skip (int numSamples) noexcept { data += numSamples; }
  27065. inline float getAsFloatLE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfBigEndian (*data)); }
  27066. inline float getAsFloatBE() const noexcept { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfLittleEndian (*data)); }
  27067. inline void setAsFloatLE (float newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint32) (maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
  27068. inline void setAsFloatBE (float newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint32) (maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
  27069. inline int32 getAsInt32LE() const noexcept { return (int32) ByteOrder::swapIfBigEndian (*data); }
  27070. inline int32 getAsInt32BE() const noexcept { return (int32) ByteOrder::swapIfLittleEndian (*data); }
  27071. inline void setAsInt32LE (int32 newValue) noexcept { *data = ByteOrder::swapIfBigEndian ((uint32) newValue); }
  27072. inline void setAsInt32BE (int32 newValue) noexcept { *data = ByteOrder::swapIfLittleEndian ((uint32) newValue); }
  27073. inline void clear() noexcept { *data = 0; }
  27074. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  27075. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsInt32LE (source.getAsInt32()); }
  27076. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsInt32BE (source.getAsInt32()); }
  27077. inline void copyFromSameType (Int32& source) noexcept { *data = *source.data; }
  27078. uint32* data;
  27079. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = 1, isFloat = 0 };
  27080. };
  27081. class Float32
  27082. {
  27083. public:
  27084. inline Float32 (void* data_) noexcept : data (static_cast <float*> (data_)) {}
  27085. inline void advance() noexcept { ++data; }
  27086. inline void skip (int numSamples) noexcept { data += numSamples; }
  27087. #if JUCE_BIG_ENDIAN
  27088. inline float getAsFloatBE() const noexcept { return *data; }
  27089. inline void setAsFloatBE (float newValue) noexcept { *data = newValue; }
  27090. inline float getAsFloatLE() const noexcept { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  27091. inline void setAsFloatLE (float newValue) noexcept { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  27092. #else
  27093. inline float getAsFloatLE() const noexcept { return *data; }
  27094. inline void setAsFloatLE (float newValue) noexcept { *data = newValue; }
  27095. inline float getAsFloatBE() const noexcept { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  27096. inline void setAsFloatBE (float newValue) noexcept { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  27097. #endif
  27098. inline int32 getAsInt32LE() const noexcept { return (int32) roundToInt (jlimit (-1.0, 1.0, (double) getAsFloatLE()) * (double) maxValue); }
  27099. inline int32 getAsInt32BE() const noexcept { return (int32) roundToInt (jlimit (-1.0, 1.0, (double) getAsFloatBE()) * (double) maxValue); }
  27100. inline void setAsInt32LE (int32 newValue) noexcept { setAsFloatLE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  27101. inline void setAsInt32BE (int32 newValue) noexcept { setAsFloatBE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  27102. inline void clear() noexcept { *data = 0; }
  27103. inline void clearMultiple (int num) noexcept { zeromem (data, num * bytesPerSample) ;}
  27104. template <class SourceType> inline void copyFromLE (SourceType& source) noexcept { setAsFloatLE (source.getAsFloat()); }
  27105. template <class SourceType> inline void copyFromBE (SourceType& source) noexcept { setAsFloatBE (source.getAsFloat()); }
  27106. inline void copyFromSameType (Float32& source) noexcept { *data = *source.data; }
  27107. float* data;
  27108. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = (1 << 8), isFloat = 1 };
  27109. };
  27110. class NonInterleaved
  27111. {
  27112. public:
  27113. inline NonInterleaved() noexcept {}
  27114. inline NonInterleaved (const NonInterleaved&) noexcept {}
  27115. inline NonInterleaved (const int) noexcept {}
  27116. inline void copyFrom (const NonInterleaved&) noexcept {}
  27117. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) noexcept { s.advance(); }
  27118. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) noexcept { s.skip (numSamples); }
  27119. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) noexcept { s.clearMultiple (numSamples); }
  27120. template <class SampleFormatType> inline static int getNumBytesBetweenSamples (const SampleFormatType&) noexcept { return SampleFormatType::bytesPerSample; }
  27121. enum { isInterleavedType = 0, numInterleavedChannels = 1 };
  27122. };
  27123. class Interleaved
  27124. {
  27125. public:
  27126. inline Interleaved() noexcept : numInterleavedChannels (1) {}
  27127. inline Interleaved (const Interleaved& other) noexcept : numInterleavedChannels (other.numInterleavedChannels) {}
  27128. inline Interleaved (const int numInterleavedChannels_) noexcept : numInterleavedChannels (numInterleavedChannels_) {}
  27129. inline void copyFrom (const Interleaved& other) noexcept { numInterleavedChannels = other.numInterleavedChannels; }
  27130. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) noexcept { s.skip (numInterleavedChannels); }
  27131. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) noexcept { s.skip (numInterleavedChannels * numSamples); }
  27132. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) noexcept { while (--numSamples >= 0) { s.clear(); s.skip (numInterleavedChannels); } }
  27133. template <class SampleFormatType> inline int getNumBytesBetweenSamples (const SampleFormatType&) const noexcept { return numInterleavedChannels * SampleFormatType::bytesPerSample; }
  27134. int numInterleavedChannels;
  27135. enum { isInterleavedType = 1 };
  27136. };
  27137. class NonConst
  27138. {
  27139. public:
  27140. typedef void VoidType;
  27141. static inline void* toVoidPtr (VoidType* v) noexcept { return v; }
  27142. enum { isConst = 0 };
  27143. };
  27144. class Const
  27145. {
  27146. public:
  27147. typedef const void VoidType;
  27148. static inline void* toVoidPtr (VoidType* v) noexcept { return const_cast<void*> (v); }
  27149. enum { isConst = 1 };
  27150. };
  27151. #endif
  27152. /**
  27153. A pointer to a block of audio data with a particular encoding.
  27154. This object can be used to read and write from blocks of encoded audio samples. To create one, you specify
  27155. the audio format as a series of template parameters, e.g.
  27156. @code
  27157. // this creates a pointer for reading from a const array of 16-bit little-endian packed samples.
  27158. AudioData::Pointer <AudioData::Int16,
  27159. AudioData::LittleEndian,
  27160. AudioData::NonInterleaved,
  27161. AudioData::Const> pointer (someRawAudioData);
  27162. // These methods read the sample that is being pointed to
  27163. float firstSampleAsFloat = pointer.getAsFloat();
  27164. int32 firstSampleAsInt = pointer.getAsInt32();
  27165. ++pointer; // moves the pointer to the next sample.
  27166. pointer += 3; // skips the next 3 samples.
  27167. @endcode
  27168. The convertSamples() method lets you copy a range of samples from one format to another, automatically
  27169. converting its format.
  27170. @see AudioData::Converter
  27171. */
  27172. template <typename SampleFormat,
  27173. typename Endianness,
  27174. typename InterleavingType,
  27175. typename Constness>
  27176. class Pointer
  27177. {
  27178. public:
  27179. /** Creates a non-interleaved pointer from some raw data in the appropriate format.
  27180. This constructor is only used if you've specified the AudioData::NonInterleaved option -
  27181. for interleaved formats, use the constructor that also takes a number of channels.
  27182. */
  27183. Pointer (typename Constness::VoidType* sourceData) noexcept
  27184. : data (Constness::toVoidPtr (sourceData))
  27185. {
  27186. // If you're using interleaved data, call the other constructor! If you're using non-interleaved data,
  27187. // you should pass NonInterleaved as the template parameter for the interleaving type!
  27188. static_jassert (InterleavingType::isInterleavedType == 0);
  27189. }
  27190. /** Creates a pointer from some raw data in the appropriate format with the specified number of interleaved channels.
  27191. For non-interleaved data, use the other constructor.
  27192. */
  27193. Pointer (typename Constness::VoidType* sourceData, int numInterleavedChannels) noexcept
  27194. : data (Constness::toVoidPtr (sourceData)),
  27195. interleaving (numInterleavedChannels)
  27196. {
  27197. }
  27198. /** Creates a copy of another pointer. */
  27199. Pointer (const Pointer& other) noexcept
  27200. : data (other.data),
  27201. interleaving (other.interleaving)
  27202. {
  27203. }
  27204. Pointer& operator= (const Pointer& other) noexcept
  27205. {
  27206. data = other.data;
  27207. interleaving.copyFrom (other.interleaving);
  27208. return *this;
  27209. }
  27210. /** Returns the value of the first sample as a floating point value.
  27211. The value will be in the range -1.0 to 1.0 for integer formats. For floating point
  27212. formats, the value could be outside that range, although -1 to 1 is the standard range.
  27213. */
  27214. inline float getAsFloat() const noexcept { return Endianness::getAsFloat (data); }
  27215. /** Sets the value of the first sample as a floating point value.
  27216. (This method can only be used if the AudioData::NonConst option was used).
  27217. The value should be in the range -1.0 to 1.0 - for integer formats, values outside that
  27218. range will be clipped. For floating point formats, any value passed in here will be
  27219. written directly, although -1 to 1 is the standard range.
  27220. */
  27221. inline void setAsFloat (float newValue) noexcept
  27222. {
  27223. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27224. Endianness::setAsFloat (data, newValue);
  27225. }
  27226. /** Returns the value of the first sample as a 32-bit integer.
  27227. The value returned will be in the range 0x80000000 to 0x7fffffff, and shorter values will be
  27228. shifted to fill this range (e.g. if you're reading from 24-bit data, the values will be shifted up
  27229. by 8 bits when returned here). If the source data is floating point, values beyond -1.0 to 1.0 will
  27230. be clipped so that -1.0 maps onto -0x7fffffff and 1.0 maps to 0x7fffffff.
  27231. */
  27232. inline int32 getAsInt32() const noexcept { return Endianness::getAsInt32 (data); }
  27233. /** Sets the value of the first sample as a 32-bit integer.
  27234. This will be mapped to the range of the format that is being written - see getAsInt32().
  27235. */
  27236. inline void setAsInt32 (int32 newValue) noexcept
  27237. {
  27238. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27239. Endianness::setAsInt32 (data, newValue);
  27240. }
  27241. /** Moves the pointer along to the next sample. */
  27242. inline Pointer& operator++() noexcept { advance(); return *this; }
  27243. /** Moves the pointer back to the previous sample. */
  27244. inline Pointer& operator--() noexcept { interleaving.advanceDataBy (data, -1); return *this; }
  27245. /** Adds a number of samples to the pointer's position. */
  27246. Pointer& operator+= (int samplesToJump) noexcept { interleaving.advanceDataBy (data, samplesToJump); return *this; }
  27247. /** Writes a stream of samples into this pointer from another pointer.
  27248. This will copy the specified number of samples, converting between formats appropriately.
  27249. */
  27250. void convertSamples (Pointer source, int numSamples) const noexcept
  27251. {
  27252. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27253. Pointer dest (*this);
  27254. while (--numSamples >= 0)
  27255. {
  27256. dest.data.copyFromSameType (source.data);
  27257. dest.advance();
  27258. source.advance();
  27259. }
  27260. }
  27261. /** Writes a stream of samples into this pointer from another pointer.
  27262. This will copy the specified number of samples, converting between formats appropriately.
  27263. */
  27264. template <class OtherPointerType>
  27265. void convertSamples (OtherPointerType source, int numSamples) const noexcept
  27266. {
  27267. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  27268. Pointer dest (*this);
  27269. if (source.getRawData() != getRawData() || source.getNumBytesBetweenSamples() >= getNumBytesBetweenSamples())
  27270. {
  27271. while (--numSamples >= 0)
  27272. {
  27273. Endianness::copyFrom (dest.data, source);
  27274. dest.advance();
  27275. ++source;
  27276. }
  27277. }
  27278. else // copy backwards if we're increasing the sample width..
  27279. {
  27280. dest += numSamples;
  27281. source += numSamples;
  27282. while (--numSamples >= 0)
  27283. Endianness::copyFrom ((--dest).data, --source);
  27284. }
  27285. }
  27286. /** Sets a number of samples to zero. */
  27287. void clearSamples (int numSamples) const noexcept
  27288. {
  27289. Pointer dest (*this);
  27290. dest.interleaving.clear (dest.data, numSamples);
  27291. }
  27292. /** Returns true if the pointer is using a floating-point format. */
  27293. static bool isFloatingPoint() noexcept { return (bool) SampleFormat::isFloat; }
  27294. /** Returns true if the format is big-endian. */
  27295. static bool isBigEndian() noexcept { return (bool) Endianness::isBigEndian; }
  27296. /** Returns the number of bytes in each sample (ignoring the number of interleaved channels). */
  27297. static int getBytesPerSample() noexcept { return (int) SampleFormat::bytesPerSample; }
  27298. /** Returns the number of interleaved channels in the format. */
  27299. int getNumInterleavedChannels() const noexcept { return (int) this->numInterleavedChannels; }
  27300. /** Returns the number of bytes between the start address of each sample. */
  27301. int getNumBytesBetweenSamples() const noexcept { return interleaving.getNumBytesBetweenSamples (data); }
  27302. /** Returns the accuracy of this format when represented as a 32-bit integer.
  27303. This is the smallest number above 0 that can be represented in the sample format, converted to
  27304. a 32-bit range. E,g. if the format is 8-bit, its resolution is 0x01000000; if the format is 24-bit,
  27305. its resolution is 0x100.
  27306. */
  27307. static int get32BitResolution() noexcept { return (int) SampleFormat::resolution; }
  27308. /** Returns a pointer to the underlying data. */
  27309. const void* getRawData() const noexcept { return data.data; }
  27310. private:
  27311. SampleFormat data;
  27312. InterleavingType interleaving; // annoyingly, making the interleaving type a superclass to take
  27313. // advantage of EBCO causes an internal compiler error in VC6..
  27314. inline void advance() noexcept { interleaving.advanceData (data); }
  27315. Pointer operator++ (int); // private to force you to use the more efficient pre-increment!
  27316. Pointer operator-- (int);
  27317. };
  27318. /** A base class for objects that are used to convert between two different sample formats.
  27319. The AudioData::ConverterInstance implements this base class and can be templated, so
  27320. you can create an instance that converts between two particular formats, and then
  27321. store this in the abstract base class.
  27322. @see AudioData::ConverterInstance
  27323. */
  27324. class Converter
  27325. {
  27326. public:
  27327. virtual ~Converter() {}
  27328. /** Converts a sequence of samples from the converter's source format into the dest format. */
  27329. virtual void convertSamples (void* destSamples, const void* sourceSamples, int numSamples) const = 0;
  27330. /** Converts a sequence of samples from the converter's source format into the dest format.
  27331. This method takes sub-channel indexes, which can be used with interleaved formats in order to choose a
  27332. particular sub-channel of the data to be used.
  27333. */
  27334. virtual void convertSamples (void* destSamples, int destSubChannel,
  27335. const void* sourceSamples, int sourceSubChannel, int numSamples) const = 0;
  27336. };
  27337. /**
  27338. A class that converts between two templated AudioData::Pointer types, and which
  27339. implements the AudioData::Converter interface.
  27340. This can be used as a concrete instance of the AudioData::Converter abstract class.
  27341. @see AudioData::Converter
  27342. */
  27343. template <class SourceSampleType, class DestSampleType>
  27344. class ConverterInstance : public Converter
  27345. {
  27346. public:
  27347. ConverterInstance (int numSourceChannels = 1, int numDestChannels = 1)
  27348. : sourceChannels (numSourceChannels), destChannels (numDestChannels)
  27349. {}
  27350. ~ConverterInstance() {}
  27351. void convertSamples (void* dest, const void* source, int numSamples) const
  27352. {
  27353. SourceSampleType s (source, sourceChannels);
  27354. DestSampleType d (dest, destChannels);
  27355. d.convertSamples (s, numSamples);
  27356. }
  27357. void convertSamples (void* dest, int destSubChannel,
  27358. const void* source, int sourceSubChannel, int numSamples) const
  27359. {
  27360. jassert (destSubChannel < destChannels && sourceSubChannel < sourceChannels);
  27361. SourceSampleType s (addBytesToPointer (source, sourceSubChannel * SourceSampleType::getBytesPerSample()), sourceChannels);
  27362. DestSampleType d (addBytesToPointer (dest, destSubChannel * DestSampleType::getBytesPerSample()), destChannels);
  27363. d.convertSamples (s, numSamples);
  27364. }
  27365. private:
  27366. JUCE_DECLARE_NON_COPYABLE (ConverterInstance);
  27367. const int sourceChannels, destChannels;
  27368. };
  27369. };
  27370. /**
  27371. A set of routines to convert buffers of 32-bit floating point data to and from
  27372. various integer formats.
  27373. Note that these functions are deprecated - the AudioData class provides a much more
  27374. flexible set of conversion classes now.
  27375. */
  27376. class JUCE_API AudioDataConverters
  27377. {
  27378. public:
  27379. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27380. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27381. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27382. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27383. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27384. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27385. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27386. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27387. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27388. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27389. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27390. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27391. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27392. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27393. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27394. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27395. enum DataFormat
  27396. {
  27397. int16LE,
  27398. int16BE,
  27399. int24LE,
  27400. int24BE,
  27401. int32LE,
  27402. int32BE,
  27403. float32LE,
  27404. float32BE,
  27405. };
  27406. static void convertFloatToFormat (DataFormat destFormat,
  27407. const float* source, void* dest, int numSamples);
  27408. static void convertFormatToFloat (DataFormat sourceFormat,
  27409. const void* source, float* dest, int numSamples);
  27410. static void interleaveSamples (const float** source, float* dest,
  27411. int numSamples, int numChannels);
  27412. static void deinterleaveSamples (const float* source, float** dest,
  27413. int numSamples, int numChannels);
  27414. private:
  27415. AudioDataConverters();
  27416. JUCE_DECLARE_NON_COPYABLE (AudioDataConverters);
  27417. };
  27418. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27419. /*** End of inlined file: juce_AudioDataConverters.h ***/
  27420. class AudioFormat;
  27421. /**
  27422. Reads samples from an audio file stream.
  27423. A subclass that reads a specific type of audio format will be created by
  27424. an AudioFormat object.
  27425. @see AudioFormat, AudioFormatWriter
  27426. */
  27427. class JUCE_API AudioFormatReader
  27428. {
  27429. protected:
  27430. /** Creates an AudioFormatReader object.
  27431. @param sourceStream the stream to read from - this will be deleted
  27432. by this object when it is no longer needed. (Some
  27433. specialised readers might not use this parameter and
  27434. can leave it as 0).
  27435. @param formatName the description that will be returned by the getFormatName()
  27436. method
  27437. */
  27438. AudioFormatReader (InputStream* sourceStream,
  27439. const String& formatName);
  27440. public:
  27441. /** Destructor. */
  27442. virtual ~AudioFormatReader();
  27443. /** Returns a description of what type of format this is.
  27444. E.g. "AIFF"
  27445. */
  27446. const String& getFormatName() const noexcept { return formatName; }
  27447. /** Reads samples from the stream.
  27448. @param destSamples an array of buffers into which the sample data for each
  27449. channel will be written.
  27450. If the format is fixed-point, each channel will be written
  27451. as an array of 32-bit signed integers using the full
  27452. range -0x80000000 to 0x7fffffff, regardless of the source's
  27453. bit-depth. If it is a floating-point format, you should cast
  27454. the resulting array to a (float**) to get the values (in the
  27455. range -1.0 to 1.0 or beyond)
  27456. If the format is stereo, then destSamples[0] is the left channel
  27457. data, and destSamples[1] is the right channel.
  27458. The numDestChannels parameter indicates how many pointers this array
  27459. contains, but some of these pointers can be null if you don't want to
  27460. read data for some of the channels
  27461. @param numDestChannels the number of array elements in the destChannels array
  27462. @param startSampleInSource the position in the audio file or stream at which the samples
  27463. should be read, as a number of samples from the start of the
  27464. stream. It's ok for this to be beyond the start or end of the
  27465. available data - any samples that are out-of-range will be returned
  27466. as zeros.
  27467. @param numSamplesToRead the number of samples to read. If this is greater than the number
  27468. of samples that the file or stream contains. the result will be padded
  27469. with zeros
  27470. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  27471. for some of the channels that you pass in, then they should be filled with
  27472. copies of valid source channels.
  27473. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  27474. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  27475. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  27476. was false, then only the first channel would be filled with the file's contents, and
  27477. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  27478. from a stereo file, then the last 3 would all end up with copies of the same data.
  27479. @returns true if the operation succeeded, false if there was an error. Note
  27480. that reading sections of data beyond the extent of the stream isn't an
  27481. error - the reader should just return zeros for these regions
  27482. @see readMaxLevels
  27483. */
  27484. bool read (int* const* destSamples,
  27485. int numDestChannels,
  27486. int64 startSampleInSource,
  27487. int numSamplesToRead,
  27488. bool fillLeftoverChannelsWithCopies);
  27489. /** Finds the highest and lowest sample levels from a section of the audio stream.
  27490. This will read a block of samples from the stream, and measure the
  27491. highest and lowest sample levels from the channels in that section, returning
  27492. these as normalised floating-point levels.
  27493. @param startSample the offset into the audio stream to start reading from. It's
  27494. ok for this to be beyond the start or end of the stream.
  27495. @param numSamples how many samples to read
  27496. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  27497. @param highestLeft on return, this is the highest absolute sample from the left channel
  27498. @param lowestRight on return, this is the lowest absolute sample from the right
  27499. channel (if there is one)
  27500. @param highestRight on return, this is the highest absolute sample from the right
  27501. channel (if there is one)
  27502. @see read
  27503. */
  27504. virtual void readMaxLevels (int64 startSample,
  27505. int64 numSamples,
  27506. float& lowestLeft,
  27507. float& highestLeft,
  27508. float& lowestRight,
  27509. float& highestRight);
  27510. /** Scans the source looking for a sample whose magnitude is in a specified range.
  27511. This will read from the source, either forwards or backwards between two sample
  27512. positions, until it finds a sample whose magnitude lies between two specified levels.
  27513. If it finds a suitable sample, it returns its position; if not, it will return -1.
  27514. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  27515. points when you're searching for a continuous range of samples
  27516. @param startSample the first sample to look at
  27517. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  27518. the search will go backwards
  27519. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  27520. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  27521. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  27522. of this many consecutive samples, all of which lie
  27523. within the target range. When it finds such a sequence,
  27524. it returns the position of the first in-range sample
  27525. it found (i.e. the earliest one if scanning forwards, the
  27526. latest one if scanning backwards)
  27527. */
  27528. int64 searchForLevel (int64 startSample,
  27529. int64 numSamplesToSearch,
  27530. double magnitudeRangeMinimum,
  27531. double magnitudeRangeMaximum,
  27532. int minimumConsecutiveSamples);
  27533. /** The sample-rate of the stream. */
  27534. double sampleRate;
  27535. /** The number of bits per sample, e.g. 16, 24, 32. */
  27536. unsigned int bitsPerSample;
  27537. /** The total number of samples in the audio stream. */
  27538. int64 lengthInSamples;
  27539. /** The total number of channels in the audio stream. */
  27540. unsigned int numChannels;
  27541. /** Indicates whether the data is floating-point or fixed. */
  27542. bool usesFloatingPointData;
  27543. /** A set of metadata values that the reader has pulled out of the stream.
  27544. Exactly what these values are depends on the format, so you can
  27545. check out the format implementation code to see what kind of stuff
  27546. they understand.
  27547. */
  27548. StringPairArray metadataValues;
  27549. /** The input stream, for use by subclasses. */
  27550. InputStream* input;
  27551. /** Subclasses must implement this method to perform the low-level read operation.
  27552. Callers should use read() instead of calling this directly.
  27553. @param destSamples the array of destination buffers to fill. Some of these
  27554. pointers may be null
  27555. @param numDestChannels the number of items in the destSamples array. This
  27556. value is guaranteed not to be greater than the number of
  27557. channels that this reader object contains
  27558. @param startOffsetInDestBuffer the number of samples from the start of the
  27559. dest data at which to begin writing
  27560. @param startSampleInFile the number of samples into the source data at which
  27561. to begin reading. This value is guaranteed to be >= 0.
  27562. @param numSamples the number of samples to read
  27563. */
  27564. virtual bool readSamples (int** destSamples,
  27565. int numDestChannels,
  27566. int startOffsetInDestBuffer,
  27567. int64 startSampleInFile,
  27568. int numSamples) = 0;
  27569. protected:
  27570. /** Used by AudioFormatReader subclasses to copy data to different formats. */
  27571. template <class DestSampleType, class SourceSampleType, class SourceEndianness>
  27572. struct ReadHelper
  27573. {
  27574. typedef AudioData::Pointer <DestSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  27575. typedef AudioData::Pointer <SourceSampleType, SourceEndianness, AudioData::Interleaved, AudioData::Const> SourceType;
  27576. static void read (int** destData, int destOffset, int numDestChannels, const void* sourceData, int numSourceChannels, int numSamples) noexcept
  27577. {
  27578. for (int i = 0; i < numDestChannels; ++i)
  27579. {
  27580. if (destData[i] != nullptr)
  27581. {
  27582. DestType dest (destData[i]);
  27583. dest += destOffset;
  27584. if (i < numSourceChannels)
  27585. dest.convertSamples (SourceType (addBytesToPointer (sourceData, i * SourceType::getBytesPerSample()), numSourceChannels), numSamples);
  27586. else
  27587. dest.clearSamples (numSamples);
  27588. }
  27589. }
  27590. }
  27591. };
  27592. private:
  27593. String formatName;
  27594. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReader);
  27595. };
  27596. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27597. /*** End of inlined file: juce_AudioFormatReader.h ***/
  27598. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  27599. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27600. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27601. /*** Start of inlined file: juce_AudioSource.h ***/
  27602. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  27603. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  27604. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  27605. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27606. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27607. class AudioFormatReader;
  27608. class AudioFormatWriter;
  27609. /**
  27610. A multi-channel buffer of 32-bit floating point audio samples.
  27611. */
  27612. class JUCE_API AudioSampleBuffer
  27613. {
  27614. public:
  27615. /** Creates a buffer with a specified number of channels and samples.
  27616. The contents of the buffer will initially be undefined, so use clear() to
  27617. set all the samples to zero.
  27618. The buffer will allocate its memory internally, and this will be released
  27619. when the buffer is deleted.
  27620. */
  27621. AudioSampleBuffer (int numChannels,
  27622. int numSamples) noexcept;
  27623. /** Creates a buffer using a pre-allocated block of memory.
  27624. Note that if the buffer is resized or its number of channels is changed, it
  27625. will re-allocate memory internally and copy the existing data to this new area,
  27626. so it will then stop directly addressing this memory.
  27627. @param dataToReferTo a pre-allocated array containing pointers to the data
  27628. for each channel that should be used by this buffer. The
  27629. buffer will only refer to this memory, it won't try to delete
  27630. it when the buffer is deleted or resized.
  27631. @param numChannels the number of channels to use - this must correspond to the
  27632. number of elements in the array passed in
  27633. @param numSamples the number of samples to use - this must correspond to the
  27634. size of the arrays passed in
  27635. */
  27636. AudioSampleBuffer (float** dataToReferTo,
  27637. int numChannels,
  27638. int numSamples) noexcept;
  27639. /** Creates a buffer using a pre-allocated block of memory.
  27640. Note that if the buffer is resized or its number of channels is changed, it
  27641. will re-allocate memory internally and copy the existing data to this new area,
  27642. so it will then stop directly addressing this memory.
  27643. @param dataToReferTo a pre-allocated array containing pointers to the data
  27644. for each channel that should be used by this buffer. The
  27645. buffer will only refer to this memory, it won't try to delete
  27646. it when the buffer is deleted or resized.
  27647. @param numChannels the number of channels to use - this must correspond to the
  27648. number of elements in the array passed in
  27649. @param startSample the offset within the arrays at which the data begins
  27650. @param numSamples the number of samples to use - this must correspond to the
  27651. size of the arrays passed in
  27652. */
  27653. AudioSampleBuffer (float** dataToReferTo,
  27654. int numChannels,
  27655. int startSample,
  27656. int numSamples) noexcept;
  27657. /** Copies another buffer.
  27658. This buffer will make its own copy of the other's data, unless the buffer was created
  27659. using an external data buffer, in which case boths buffers will just point to the same
  27660. shared block of data.
  27661. */
  27662. AudioSampleBuffer (const AudioSampleBuffer& other) noexcept;
  27663. /** Copies another buffer onto this one.
  27664. This buffer's size will be changed to that of the other buffer.
  27665. */
  27666. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) noexcept;
  27667. /** Destructor.
  27668. This will free any memory allocated by the buffer.
  27669. */
  27670. virtual ~AudioSampleBuffer() noexcept;
  27671. /** Returns the number of channels of audio data that this buffer contains.
  27672. @see getSampleData
  27673. */
  27674. int getNumChannels() const noexcept { return numChannels; }
  27675. /** Returns the number of samples allocated in each of the buffer's channels.
  27676. @see getSampleData
  27677. */
  27678. int getNumSamples() const noexcept { return size; }
  27679. /** Returns a pointer one of the buffer's channels.
  27680. For speed, this doesn't check whether the channel number is out of range,
  27681. so be careful when using it!
  27682. */
  27683. float* getSampleData (const int channelNumber) const noexcept
  27684. {
  27685. jassert (isPositiveAndBelow (channelNumber, numChannels));
  27686. return channels [channelNumber];
  27687. }
  27688. /** Returns a pointer to a sample in one of the buffer's channels.
  27689. For speed, this doesn't check whether the channel and sample number
  27690. are out-of-range, so be careful when using it!
  27691. */
  27692. float* getSampleData (const int channelNumber,
  27693. const int sampleOffset) const noexcept
  27694. {
  27695. jassert (isPositiveAndBelow (channelNumber, numChannels));
  27696. jassert (isPositiveAndBelow (sampleOffset, size));
  27697. return channels [channelNumber] + sampleOffset;
  27698. }
  27699. /** Returns an array of pointers to the channels in the buffer.
  27700. Don't modify any of the pointers that are returned, and bear in mind that
  27701. these will become invalid if the buffer is resized.
  27702. */
  27703. float** getArrayOfChannels() const noexcept { return channels; }
  27704. /** Changes the buffer's size or number of channels.
  27705. This can expand or contract the buffer's length, and add or remove channels.
  27706. If keepExistingContent is true, it will try to preserve as much of the
  27707. old data as it can in the new buffer.
  27708. If clearExtraSpace is true, then any extra channels or space that is
  27709. allocated will be also be cleared. If false, then this space is left
  27710. uninitialised.
  27711. If avoidReallocating is true, then changing the buffer's size won't reduce the
  27712. amount of memory that is currently allocated (but it will still increase it if
  27713. the new size is bigger than the amount it currently has). If this is false, then
  27714. a new allocation will be done so that the buffer uses takes up the minimum amount
  27715. of memory that it needs.
  27716. */
  27717. void setSize (int newNumChannels,
  27718. int newNumSamples,
  27719. bool keepExistingContent = false,
  27720. bool clearExtraSpace = false,
  27721. bool avoidReallocating = false) noexcept;
  27722. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  27723. There's also a constructor that lets you specify arrays like this, but this
  27724. lets you change the channels dynamically.
  27725. Note that if the buffer is resized or its number of channels is changed, it
  27726. will re-allocate memory internally and copy the existing data to this new area,
  27727. so it will then stop directly addressing this memory.
  27728. @param dataToReferTo a pre-allocated array containing pointers to the data
  27729. for each channel that should be used by this buffer. The
  27730. buffer will only refer to this memory, it won't try to delete
  27731. it when the buffer is deleted or resized.
  27732. @param numChannels the number of channels to use - this must correspond to the
  27733. number of elements in the array passed in
  27734. @param numSamples the number of samples to use - this must correspond to the
  27735. size of the arrays passed in
  27736. */
  27737. void setDataToReferTo (float** dataToReferTo,
  27738. int numChannels,
  27739. int numSamples) noexcept;
  27740. /** Clears all the samples in all channels. */
  27741. void clear() noexcept;
  27742. /** Clears a specified region of all the channels.
  27743. For speed, this doesn't check whether the channel and sample number
  27744. are in-range, so be careful!
  27745. */
  27746. void clear (int startSample,
  27747. int numSamples) noexcept;
  27748. /** Clears a specified region of just one channel.
  27749. For speed, this doesn't check whether the channel and sample number
  27750. are in-range, so be careful!
  27751. */
  27752. void clear (int channel,
  27753. int startSample,
  27754. int numSamples) noexcept;
  27755. /** Applies a gain multiple to a region of one channel.
  27756. For speed, this doesn't check whether the channel and sample number
  27757. are in-range, so be careful!
  27758. */
  27759. void applyGain (int channel,
  27760. int startSample,
  27761. int numSamples,
  27762. float gain) noexcept;
  27763. /** Applies a gain multiple to a region of all the channels.
  27764. For speed, this doesn't check whether the sample numbers
  27765. are in-range, so be careful!
  27766. */
  27767. void applyGain (int startSample,
  27768. int numSamples,
  27769. float gain) noexcept;
  27770. /** Applies a range of gains to a region of a channel.
  27771. The gain that is applied to each sample will vary from
  27772. startGain on the first sample to endGain on the last Sample,
  27773. so it can be used to do basic fades.
  27774. For speed, this doesn't check whether the sample numbers
  27775. are in-range, so be careful!
  27776. */
  27777. void applyGainRamp (int channel,
  27778. int startSample,
  27779. int numSamples,
  27780. float startGain,
  27781. float endGain) noexcept;
  27782. /** Adds samples from another buffer to this one.
  27783. @param destChannel the channel within this buffer to add the samples to
  27784. @param destStartSample the start sample within this buffer's channel
  27785. @param source the source buffer to add from
  27786. @param sourceChannel the channel within the source buffer to read from
  27787. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  27788. @param numSamples the number of samples to process
  27789. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  27790. added to this buffer's samples
  27791. @see copyFrom
  27792. */
  27793. void addFrom (int destChannel,
  27794. int destStartSample,
  27795. const AudioSampleBuffer& source,
  27796. int sourceChannel,
  27797. int sourceStartSample,
  27798. int numSamples,
  27799. float gainToApplyToSource = 1.0f) noexcept;
  27800. /** Adds samples from an array of floats to one of the channels.
  27801. @param destChannel the channel within this buffer to add the samples to
  27802. @param destStartSample the start sample within this buffer's channel
  27803. @param source the source data to use
  27804. @param numSamples the number of samples to process
  27805. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  27806. added to this buffer's samples
  27807. @see copyFrom
  27808. */
  27809. void addFrom (int destChannel,
  27810. int destStartSample,
  27811. const float* source,
  27812. int numSamples,
  27813. float gainToApplyToSource = 1.0f) noexcept;
  27814. /** Adds samples from an array of floats, applying a gain ramp to them.
  27815. @param destChannel the channel within this buffer to add the samples to
  27816. @param destStartSample the start sample within this buffer's channel
  27817. @param source the source data to use
  27818. @param numSamples the number of samples to process
  27819. @param startGain the gain to apply to the first sample (this is multiplied with
  27820. the source samples before they are added to this buffer)
  27821. @param endGain the gain to apply to the final sample. The gain is linearly
  27822. interpolated between the first and last samples.
  27823. */
  27824. void addFromWithRamp (int destChannel,
  27825. int destStartSample,
  27826. const float* source,
  27827. int numSamples,
  27828. float startGain,
  27829. float endGain) noexcept;
  27830. /** Copies samples from another buffer to this one.
  27831. @param destChannel the channel within this buffer to copy the samples to
  27832. @param destStartSample the start sample within this buffer's channel
  27833. @param source the source buffer to read from
  27834. @param sourceChannel the channel within the source buffer to read from
  27835. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  27836. @param numSamples the number of samples to process
  27837. @see addFrom
  27838. */
  27839. void copyFrom (int destChannel,
  27840. int destStartSample,
  27841. const AudioSampleBuffer& source,
  27842. int sourceChannel,
  27843. int sourceStartSample,
  27844. int numSamples) noexcept;
  27845. /** Copies samples from an array of floats into one of the channels.
  27846. @param destChannel the channel within this buffer to copy the samples to
  27847. @param destStartSample the start sample within this buffer's channel
  27848. @param source the source buffer to read from
  27849. @param numSamples the number of samples to process
  27850. @see addFrom
  27851. */
  27852. void copyFrom (int destChannel,
  27853. int destStartSample,
  27854. const float* source,
  27855. int numSamples) noexcept;
  27856. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  27857. @param destChannel the channel within this buffer to copy the samples to
  27858. @param destStartSample the start sample within this buffer's channel
  27859. @param source the source buffer to read from
  27860. @param numSamples the number of samples to process
  27861. @param gain the gain to apply
  27862. @see addFrom
  27863. */
  27864. void copyFrom (int destChannel,
  27865. int destStartSample,
  27866. const float* source,
  27867. int numSamples,
  27868. float gain) noexcept;
  27869. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  27870. @param destChannel the channel within this buffer to copy the samples to
  27871. @param destStartSample the start sample within this buffer's channel
  27872. @param source the source buffer to read from
  27873. @param numSamples the number of samples to process
  27874. @param startGain the gain to apply to the first sample (this is multiplied with
  27875. the source samples before they are copied to this buffer)
  27876. @param endGain the gain to apply to the final sample. The gain is linearly
  27877. interpolated between the first and last samples.
  27878. @see addFrom
  27879. */
  27880. void copyFromWithRamp (int destChannel,
  27881. int destStartSample,
  27882. const float* source,
  27883. int numSamples,
  27884. float startGain,
  27885. float endGain) noexcept;
  27886. /** Finds the highest and lowest sample values in a given range.
  27887. @param channel the channel to read from
  27888. @param startSample the start sample within the channel
  27889. @param numSamples the number of samples to check
  27890. @param minVal on return, the lowest value that was found
  27891. @param maxVal on return, the highest value that was found
  27892. */
  27893. void findMinMax (int channel,
  27894. int startSample,
  27895. int numSamples,
  27896. float& minVal,
  27897. float& maxVal) const noexcept;
  27898. /** Finds the highest absolute sample value within a region of a channel.
  27899. */
  27900. float getMagnitude (int channel,
  27901. int startSample,
  27902. int numSamples) const noexcept;
  27903. /** Finds the highest absolute sample value within a region on all channels.
  27904. */
  27905. float getMagnitude (int startSample,
  27906. int numSamples) const noexcept;
  27907. /** Returns the root mean squared level for a region of a channel.
  27908. */
  27909. float getRMSLevel (int channel,
  27910. int startSample,
  27911. int numSamples) const noexcept;
  27912. /** Fills a section of the buffer using an AudioReader as its source.
  27913. This will convert the reader's fixed- or floating-point data to
  27914. the buffer's floating-point format, and will try to intelligently
  27915. cope with mismatches between the number of channels in the reader
  27916. and the buffer.
  27917. @see writeToAudioWriter
  27918. */
  27919. void readFromAudioReader (AudioFormatReader* reader,
  27920. int startSample,
  27921. int numSamples,
  27922. int64 readerStartSample,
  27923. bool useReaderLeftChan,
  27924. bool useReaderRightChan);
  27925. /** Writes a section of this buffer to an audio writer.
  27926. This saves you having to mess about with channels or floating/fixed
  27927. point conversion.
  27928. @see readFromAudioReader
  27929. */
  27930. void writeToAudioWriter (AudioFormatWriter* writer,
  27931. int startSample,
  27932. int numSamples) const;
  27933. private:
  27934. int numChannels, size;
  27935. size_t allocatedBytes;
  27936. float** channels;
  27937. HeapBlock <char> allocatedData;
  27938. float* preallocatedChannelSpace [32];
  27939. void allocateData();
  27940. void allocateChannels (float** dataToReferTo, int offset);
  27941. JUCE_LEAK_DETECTOR (AudioSampleBuffer);
  27942. };
  27943. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27944. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  27945. /**
  27946. Used by AudioSource::getNextAudioBlock().
  27947. */
  27948. struct JUCE_API AudioSourceChannelInfo
  27949. {
  27950. /** The destination buffer to fill with audio data.
  27951. When the AudioSource::getNextAudioBlock() method is called, the active section
  27952. of this buffer should be filled with whatever output the source produces.
  27953. Only the samples specified by the startSample and numSamples members of this structure
  27954. should be affected by the call.
  27955. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  27956. method can be treated as the input if the source is performing some kind of filter operation,
  27957. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  27958. a handy way of doing this.
  27959. The number of channels in the buffer could be anything, so the AudioSource
  27960. must cope with this in whatever way is appropriate for its function.
  27961. */
  27962. AudioSampleBuffer* buffer;
  27963. /** The first sample in the buffer from which the callback is expected
  27964. to write data. */
  27965. int startSample;
  27966. /** The number of samples in the buffer which the callback is expected to
  27967. fill with data. */
  27968. int numSamples;
  27969. /** Convenient method to clear the buffer if the source is not producing any data. */
  27970. void clearActiveBufferRegion() const
  27971. {
  27972. if (buffer != nullptr)
  27973. buffer->clear (startSample, numSamples);
  27974. }
  27975. };
  27976. /**
  27977. Base class for objects that can produce a continuous stream of audio.
  27978. An AudioSource has two states: 'prepared' and 'unprepared'.
  27979. When a source needs to be played, it is first put into a 'prepared' state by a call to
  27980. prepareToPlay(), and then repeated calls will be made to its getNextAudioBlock() method to
  27981. process the audio data.
  27982. Once playback has finished, the releaseResources() method is called to put the stream
  27983. back into an 'unprepared' state.
  27984. @see AudioFormatReaderSource, ResamplingAudioSource
  27985. */
  27986. class JUCE_API AudioSource
  27987. {
  27988. protected:
  27989. /** Creates an AudioSource. */
  27990. AudioSource() noexcept {}
  27991. public:
  27992. /** Destructor. */
  27993. virtual ~AudioSource() {}
  27994. /** Tells the source to prepare for playing.
  27995. An AudioSource has two states: prepared and unprepared.
  27996. The prepareToPlay() method is guaranteed to be called at least once on an 'unpreprared'
  27997. source to put it into a 'prepared' state before any calls will be made to getNextAudioBlock().
  27998. This callback allows the source to initialise any resources it might need when playing.
  27999. Once playback has finished, the releaseResources() method is called to put the stream
  28000. back into an 'unprepared' state.
  28001. Note that this method could be called more than once in succession without
  28002. a matching call to releaseResources(), so make sure your code is robust and
  28003. can handle that kind of situation.
  28004. @param samplesPerBlockExpected the number of samples that the source
  28005. will be expected to supply each time its
  28006. getNextAudioBlock() method is called. This
  28007. number may vary slightly, because it will be dependent
  28008. on audio hardware callbacks, and these aren't
  28009. guaranteed to always use a constant block size, so
  28010. the source should be able to cope with small variations.
  28011. @param sampleRate the sample rate that the output will be used at - this
  28012. is needed by sources such as tone generators.
  28013. @see releaseResources, getNextAudioBlock
  28014. */
  28015. virtual void prepareToPlay (int samplesPerBlockExpected,
  28016. double sampleRate) = 0;
  28017. /** Allows the source to release anything it no longer needs after playback has stopped.
  28018. This will be called when the source is no longer going to have its getNextAudioBlock()
  28019. method called, so it should release any spare memory, etc. that it might have
  28020. allocated during the prepareToPlay() call.
  28021. Note that there's no guarantee that prepareToPlay() will actually have been called before
  28022. releaseResources(), and it may be called more than once in succession, so make sure your
  28023. code is robust and doesn't make any assumptions about when it will be called.
  28024. @see prepareToPlay, getNextAudioBlock
  28025. */
  28026. virtual void releaseResources() = 0;
  28027. /** Called repeatedly to fetch subsequent blocks of audio data.
  28028. After calling the prepareToPlay() method, this callback will be made each
  28029. time the audio playback hardware (or whatever other destination the audio
  28030. data is going to) needs another block of data.
  28031. It will generally be called on a high-priority system thread, or possibly even
  28032. an interrupt, so be careful not to do too much work here, as that will cause
  28033. audio glitches!
  28034. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  28035. */
  28036. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  28037. };
  28038. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  28039. /*** End of inlined file: juce_AudioSource.h ***/
  28040. class AudioThumbnail;
  28041. /**
  28042. Writes samples to an audio file stream.
  28043. A subclass that writes a specific type of audio format will be created by
  28044. an AudioFormat object.
  28045. After creating one of these with the AudioFormat::createWriterFor() method
  28046. you can call its write() method to store the samples, and then delete it.
  28047. @see AudioFormat, AudioFormatReader
  28048. */
  28049. class JUCE_API AudioFormatWriter
  28050. {
  28051. protected:
  28052. /** Creates an AudioFormatWriter object.
  28053. @param destStream the stream to write to - this will be deleted
  28054. by this object when it is no longer needed
  28055. @param formatName the description that will be returned by the getFormatName()
  28056. method
  28057. @param sampleRate the sample rate to use - the base class just stores
  28058. this value, it doesn't do anything with it
  28059. @param numberOfChannels the number of channels to write - the base class just stores
  28060. this value, it doesn't do anything with it
  28061. @param bitsPerSample the bit depth of the stream - the base class just stores
  28062. this value, it doesn't do anything with it
  28063. */
  28064. AudioFormatWriter (OutputStream* destStream,
  28065. const String& formatName,
  28066. double sampleRate,
  28067. unsigned int numberOfChannels,
  28068. unsigned int bitsPerSample);
  28069. public:
  28070. /** Destructor. */
  28071. virtual ~AudioFormatWriter();
  28072. /** Returns a description of what type of format this is.
  28073. E.g. "AIFF file"
  28074. */
  28075. const String& getFormatName() const noexcept { return formatName; }
  28076. /** Writes a set of samples to the audio stream.
  28077. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  28078. can use AudioSampleBuffer::writeToAudioWriter().
  28079. @param samplesToWrite an array of arrays containing the sample data for
  28080. each channel to write. This is a zero-terminated
  28081. array of arrays, and can contain a different number
  28082. of channels than the actual stream uses, and the
  28083. writer should do its best to cope with this.
  28084. If the format is fixed-point, each channel will be formatted
  28085. as an array of signed integers using the full 32-bit
  28086. range -0x80000000 to 0x7fffffff, regardless of the source's
  28087. bit-depth. If it is a floating-point format, you should treat
  28088. the arrays as arrays of floats, and just cast it to an (int**)
  28089. to pass it into the method.
  28090. @param numSamples the number of samples to write
  28091. */
  28092. virtual bool write (const int** samplesToWrite,
  28093. int numSamples) = 0;
  28094. /** Reads a section of samples from an AudioFormatReader, and writes these to
  28095. the output.
  28096. This will take care of any floating-point conversion that's required to convert
  28097. between the two formats. It won't deal with sample-rate conversion, though.
  28098. If numSamplesToRead < 0, it will write the entire length of the reader.
  28099. @returns false if it can't read or write properly during the operation
  28100. */
  28101. bool writeFromAudioReader (AudioFormatReader& reader,
  28102. int64 startSample,
  28103. int64 numSamplesToRead);
  28104. /** Reads some samples from an AudioSource, and writes these to the output.
  28105. The source must already have been initialised with the AudioSource::prepareToPlay() method
  28106. @param source the source to read from
  28107. @param numSamplesToRead total number of samples to read and write
  28108. @param samplesPerBlock the maximum number of samples to fetch from the source
  28109. @returns false if it can't read or write properly during the operation
  28110. */
  28111. bool writeFromAudioSource (AudioSource& source,
  28112. int numSamplesToRead,
  28113. int samplesPerBlock = 2048);
  28114. /** Writes some samples from an AudioSampleBuffer.
  28115. */
  28116. bool writeFromAudioSampleBuffer (const AudioSampleBuffer& source,
  28117. int startSample, int numSamples);
  28118. /** Returns the sample rate being used. */
  28119. double getSampleRate() const noexcept { return sampleRate; }
  28120. /** Returns the number of channels being written. */
  28121. int getNumChannels() const noexcept { return numChannels; }
  28122. /** Returns the bit-depth of the data being written. */
  28123. int getBitsPerSample() const noexcept { return bitsPerSample; }
  28124. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  28125. bool isFloatingPoint() const noexcept { return usesFloatingPointData; }
  28126. /**
  28127. Provides a FIFO for an AudioFormatWriter, allowing you to push incoming
  28128. data into a buffer which will be flushed to disk by a background thread.
  28129. */
  28130. class ThreadedWriter
  28131. {
  28132. public:
  28133. /** Creates a ThreadedWriter for a given writer and a thread.
  28134. The writer object which is passed in here will be owned and deleted by
  28135. the ThreadedWriter when it is no longer needed.
  28136. To stop the writer and flush the buffer to disk, simply delete this object.
  28137. */
  28138. ThreadedWriter (AudioFormatWriter* writer,
  28139. TimeSliceThread& backgroundThread,
  28140. int numSamplesToBuffer);
  28141. /** Destructor. */
  28142. ~ThreadedWriter();
  28143. /** Pushes some incoming audio data into the FIFO.
  28144. If there's enough free space in the buffer, this will add the data to it,
  28145. If the FIFO is too full to accept this many samples, the method will return
  28146. false - then you could either wait until the background thread has had time to
  28147. consume some of the buffered data and try again, or you can give up
  28148. and lost this block.
  28149. The data must be an array containing the same number of channels as the
  28150. AudioFormatWriter object is using. None of these channels can be null.
  28151. */
  28152. bool write (const float** data, int numSamples);
  28153. /** Allows you to specify a thumbnail that this writer should update with the
  28154. incoming data.
  28155. The thumbnail will be cleared and will the writer will begin adding data to
  28156. it as it arrives. Pass a null pointer to stop the writer updating any thumbnails.
  28157. */
  28158. void setThumbnailToUpdate (AudioThumbnail* thumbnailToUpdate);
  28159. #ifndef DOXYGEN
  28160. class Buffer; // (only public for VC6 compatibility)
  28161. #endif
  28162. private:
  28163. friend class ScopedPointer<Buffer>;
  28164. ScopedPointer<Buffer> buffer;
  28165. };
  28166. protected:
  28167. /** The sample rate of the stream. */
  28168. double sampleRate;
  28169. /** The number of channels being written to the stream. */
  28170. unsigned int numChannels;
  28171. /** The bit depth of the file. */
  28172. unsigned int bitsPerSample;
  28173. /** True if it's a floating-point format, false if it's fixed-point. */
  28174. bool usesFloatingPointData;
  28175. /** The output stream for Use by subclasses. */
  28176. OutputStream* output;
  28177. /** Used by AudioFormatWriter subclasses to copy data to different formats. */
  28178. template <class DestSampleType, class SourceSampleType, class DestEndianness>
  28179. struct WriteHelper
  28180. {
  28181. typedef AudioData::Pointer <DestSampleType, DestEndianness, AudioData::Interleaved, AudioData::NonConst> DestType;
  28182. typedef AudioData::Pointer <SourceSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  28183. static void write (void* destData, int numDestChannels, const int** source,
  28184. int numSamples, const int sourceOffset = 0) noexcept
  28185. {
  28186. for (int i = 0; i < numDestChannels; ++i)
  28187. {
  28188. const DestType dest (addBytesToPointer (destData, i * DestType::getBytesPerSample()), numDestChannels);
  28189. if (*source != nullptr)
  28190. {
  28191. dest.convertSamples (SourceType (*source + sourceOffset), numSamples);
  28192. ++source;
  28193. }
  28194. else
  28195. {
  28196. dest.clearSamples (numSamples);
  28197. }
  28198. }
  28199. }
  28200. };
  28201. private:
  28202. String formatName;
  28203. friend class ThreadedWriter;
  28204. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatWriter);
  28205. };
  28206. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28207. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  28208. /**
  28209. Subclasses of AudioFormat are used to read and write different audio
  28210. file formats.
  28211. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  28212. */
  28213. class JUCE_API AudioFormat
  28214. {
  28215. public:
  28216. /** Destructor. */
  28217. virtual ~AudioFormat();
  28218. /** Returns the name of this format.
  28219. e.g. "WAV file" or "AIFF file"
  28220. */
  28221. const String& getFormatName() const;
  28222. /** Returns all the file extensions that might apply to a file of this format.
  28223. The first item will be the one that's preferred when creating a new file.
  28224. So for a wav file this might just return ".wav"; for an AIFF file it might
  28225. return two items, ".aif" and ".aiff"
  28226. */
  28227. const StringArray& getFileExtensions() const;
  28228. /** Returns true if this the given file can be read by this format.
  28229. Subclasses shouldn't do too much work here, just check the extension or
  28230. file type. The base class implementation just checks the file's extension
  28231. against one of the ones that was registered in the constructor.
  28232. */
  28233. virtual bool canHandleFile (const File& fileToTest);
  28234. /** Returns a set of sample rates that the format can read and write. */
  28235. virtual const Array <int> getPossibleSampleRates() = 0;
  28236. /** Returns a set of bit depths that the format can read and write. */
  28237. virtual const Array <int> getPossibleBitDepths() = 0;
  28238. /** Returns true if the format can do 2-channel audio. */
  28239. virtual bool canDoStereo() = 0;
  28240. /** Returns true if the format can do 1-channel audio. */
  28241. virtual bool canDoMono() = 0;
  28242. /** Returns true if the format uses compressed data. */
  28243. virtual bool isCompressed();
  28244. /** Returns a list of different qualities that can be used when writing.
  28245. Non-compressed formats will just return an empty array, but for something
  28246. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  28247. When calling createWriterFor(), an index from this array is passed in to
  28248. tell the format which option is required.
  28249. */
  28250. virtual StringArray getQualityOptions();
  28251. /** Tries to create an object that can read from a stream containing audio
  28252. data in this format.
  28253. The reader object that is returned can be used to read from the stream, and
  28254. should then be deleted by the caller.
  28255. @param sourceStream the stream to read from - the AudioFormatReader object
  28256. that is returned will delete this stream when it no longer
  28257. needs it.
  28258. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  28259. should delete the stream object that was passed-in. (If a valid
  28260. reader is returned, it will always be in charge of deleting the
  28261. stream, so this parameter is ignored)
  28262. @see AudioFormatReader
  28263. */
  28264. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28265. bool deleteStreamIfOpeningFails) = 0;
  28266. /** Tries to create an object that can write to a stream with this audio format.
  28267. The writer object that is returned can be used to write to the stream, and
  28268. should then be deleted by the caller.
  28269. If the stream can't be created for some reason (e.g. the parameters passed in
  28270. here aren't suitable), this will return 0.
  28271. @param streamToWriteTo the stream that the data will go to - this will be
  28272. deleted by the AudioFormatWriter object when it's no longer
  28273. needed. If no AudioFormatWriter can be created by this method,
  28274. the stream will NOT be deleted, so that the caller can re-use it
  28275. to try to open a different format, etc
  28276. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  28277. returned by getPossibleSampleRates()
  28278. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  28279. the choice will depend on the results of canDoMono() and
  28280. canDoStereo()
  28281. @param bitsPerSample the bits per sample to use - this must be one of the values
  28282. returned by getPossibleBitDepths()
  28283. @param metadataValues a set of metadata values that the writer should try to write
  28284. to the stream. Exactly what these are depends on the format,
  28285. and the subclass doesn't actually have to do anything with
  28286. them if it doesn't want to. Have a look at the specific format
  28287. implementation classes to see possible values that can be
  28288. used
  28289. @param qualityOptionIndex the index of one of compression qualities returned by the
  28290. getQualityOptions() method. If there aren't any quality options
  28291. for this format, just pass 0 in this parameter, as it'll be
  28292. ignored
  28293. @see AudioFormatWriter
  28294. */
  28295. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28296. double sampleRateToUse,
  28297. unsigned int numberOfChannels,
  28298. int bitsPerSample,
  28299. const StringPairArray& metadataValues,
  28300. int qualityOptionIndex) = 0;
  28301. protected:
  28302. /** Creates an AudioFormat object.
  28303. @param formatName this sets the value that will be returned by getFormatName()
  28304. @param fileExtensions a zero-terminated list of file extensions - this is what will
  28305. be returned by getFileExtension()
  28306. */
  28307. AudioFormat (const String& formatName,
  28308. const StringArray& fileExtensions);
  28309. private:
  28310. String formatName;
  28311. StringArray fileExtensions;
  28312. };
  28313. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  28314. /*** End of inlined file: juce_AudioFormat.h ***/
  28315. /**
  28316. Reads and Writes AIFF format audio files.
  28317. @see AudioFormat
  28318. */
  28319. class JUCE_API AiffAudioFormat : public AudioFormat
  28320. {
  28321. public:
  28322. /** Creates an format object. */
  28323. AiffAudioFormat();
  28324. /** Destructor. */
  28325. ~AiffAudioFormat();
  28326. const Array <int> getPossibleSampleRates();
  28327. const Array <int> getPossibleBitDepths();
  28328. bool canDoStereo();
  28329. bool canDoMono();
  28330. #if JUCE_MAC
  28331. bool canHandleFile (const File& fileToTest);
  28332. #endif
  28333. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28334. bool deleteStreamIfOpeningFails);
  28335. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28336. double sampleRateToUse,
  28337. unsigned int numberOfChannels,
  28338. int bitsPerSample,
  28339. const StringPairArray& metadataValues,
  28340. int qualityOptionIndex);
  28341. private:
  28342. JUCE_LEAK_DETECTOR (AiffAudioFormat);
  28343. };
  28344. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  28345. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  28346. #endif
  28347. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28348. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  28349. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28350. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28351. #if JUCE_USE_CDBURNER || DOXYGEN
  28352. /**
  28353. */
  28354. class AudioCDBurner : public ChangeBroadcaster
  28355. {
  28356. public:
  28357. /** Returns a list of available optical drives.
  28358. Use openDevice() to open one of the items from this list.
  28359. */
  28360. static StringArray findAvailableDevices();
  28361. /** Tries to open one of the optical drives.
  28362. The deviceIndex is an index into the array returned by findAvailableDevices().
  28363. */
  28364. static AudioCDBurner* openDevice (const int deviceIndex);
  28365. /** Destructor. */
  28366. ~AudioCDBurner();
  28367. enum DiskState
  28368. {
  28369. unknown, /**< An error condition, if the device isn't responding. */
  28370. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  28371. may seem to be permanently open. */
  28372. noDisc, /**< The drive has no disk in it. */
  28373. writableDiskPresent, /**< The drive contains a writeable disk. */
  28374. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  28375. };
  28376. /** Returns the current status of the device.
  28377. To get informed when the drive's status changes, attach a ChangeListener to
  28378. the AudioCDBurner.
  28379. */
  28380. DiskState getDiskState() const;
  28381. /** Returns true if there's a writable disk in the drive. */
  28382. bool isDiskPresent() const;
  28383. /** Sends an eject signal to the drive.
  28384. The eject will happen asynchronously, so you can use getDiskState() and
  28385. waitUntilStateChange() to monitor its progress.
  28386. */
  28387. bool openTray();
  28388. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  28389. @returns the device's new state
  28390. */
  28391. DiskState waitUntilStateChange (int timeOutMilliseconds);
  28392. /** Returns the set of possible write speeds that the device can handle.
  28393. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  28394. Note that if there's no media present in the drive, this value may be unavailable!
  28395. @see setWriteSpeed, getWriteSpeed
  28396. */
  28397. Array<int> getAvailableWriteSpeeds() const;
  28398. /** Tries to enable or disable buffer underrun safety on devices that support it.
  28399. @returns true if it's now enabled. If the device doesn't support it, this
  28400. will always return false.
  28401. */
  28402. bool setBufferUnderrunProtection (bool shouldBeEnabled);
  28403. /** Returns the number of free blocks on the disk.
  28404. There are 75 blocks per second, at 44100Hz.
  28405. */
  28406. int getNumAvailableAudioBlocks() const;
  28407. /** Adds a track to be written.
  28408. The source passed-in here will be kept by this object, and it will
  28409. be used and deleted at some point in the future, either during the
  28410. burn() method or when this AudioCDBurner object is deleted. Your caller
  28411. method shouldn't keep a reference to it or use it again after passing
  28412. it in here.
  28413. */
  28414. bool addAudioTrack (AudioSource* source, int numSamples);
  28415. /** Receives progress callbacks during a cd-burn operation.
  28416. @see AudioCDBurner::burn()
  28417. */
  28418. class BurnProgressListener
  28419. {
  28420. public:
  28421. BurnProgressListener() noexcept {}
  28422. virtual ~BurnProgressListener() {}
  28423. /** Called at intervals to report on the progress of the AudioCDBurner.
  28424. To cancel the burn, return true from this method.
  28425. */
  28426. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  28427. };
  28428. /** Runs the burn process.
  28429. This method will block until the operation is complete.
  28430. @param listener the object to receive callbacks about progress
  28431. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  28432. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  28433. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  28434. 0 or less to mean the fastest speed.
  28435. */
  28436. String burn (BurnProgressListener* listener,
  28437. bool ejectDiscAfterwards,
  28438. bool performFakeBurnForTesting,
  28439. int writeSpeed);
  28440. /** If a burn operation is currently in progress, this tells it to stop
  28441. as soon as possible.
  28442. It's also possible to stop the burn process by returning true from
  28443. BurnProgressListener::audioCDBurnProgress()
  28444. */
  28445. void abortBurn();
  28446. private:
  28447. AudioCDBurner (const int deviceIndex);
  28448. class Pimpl;
  28449. friend class ScopedPointer<Pimpl>;
  28450. ScopedPointer<Pimpl> pimpl;
  28451. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDBurner);
  28452. };
  28453. #endif
  28454. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28455. /*** End of inlined file: juce_AudioCDBurner.h ***/
  28456. #endif
  28457. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28458. /*** Start of inlined file: juce_AudioCDReader.h ***/
  28459. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28460. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  28461. #if JUCE_USE_CDREADER || DOXYGEN
  28462. #if JUCE_MAC
  28463. #endif
  28464. /**
  28465. A type of AudioFormatReader that reads from an audio CD.
  28466. One of these can be used to read a CD as if it's one big audio stream. Use the
  28467. getPositionOfTrackStart() method to find where the individual tracks are
  28468. within the stream.
  28469. @see AudioFormatReader
  28470. */
  28471. class JUCE_API AudioCDReader : public AudioFormatReader
  28472. {
  28473. public:
  28474. /** Returns a list of names of Audio CDs currently available for reading.
  28475. If there's a CD drive but no CD in it, this might return an empty list, or
  28476. possibly a device that can be opened but which has no tracks, depending
  28477. on the platform.
  28478. @see createReaderForCD
  28479. */
  28480. static StringArray getAvailableCDNames();
  28481. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  28482. @param index the index of one of the available CDs - use getAvailableCDNames()
  28483. to find out how many there are.
  28484. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  28485. caller will be responsible for deleting the object returned.
  28486. */
  28487. static AudioCDReader* createReaderForCD (const int index);
  28488. /** Destructor. */
  28489. ~AudioCDReader();
  28490. /** Implementation of the AudioFormatReader method. */
  28491. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28492. int64 startSampleInFile, int numSamples);
  28493. /** Checks whether the CD has been removed from the drive.
  28494. */
  28495. bool isCDStillPresent() const;
  28496. /** Returns the total number of tracks (audio + data).
  28497. */
  28498. int getNumTracks() const;
  28499. /** Finds the sample offset of the start of a track.
  28500. @param trackNum the track number, where trackNum = 0 is the first track
  28501. and trackNum = getNumTracks() means the end of the CD.
  28502. */
  28503. int getPositionOfTrackStart (int trackNum) const;
  28504. /** Returns true if a given track is an audio track.
  28505. @param trackNum the track number, where 0 is the first track.
  28506. */
  28507. bool isTrackAudio (int trackNum) const;
  28508. /** Returns an array of sample offsets for the start of each track, followed by
  28509. the sample position of the end of the CD.
  28510. */
  28511. const Array<int>& getTrackOffsets() const;
  28512. /** Refreshes the object's table of contents.
  28513. If the disc has been ejected and a different one put in since this
  28514. object was created, this will cause it to update its idea of how many tracks
  28515. there are, etc.
  28516. */
  28517. void refreshTrackLengths();
  28518. /** Enables scanning for indexes within tracks.
  28519. @see getLastIndex
  28520. */
  28521. void enableIndexScanning (bool enabled);
  28522. /** Returns the index number found during the last read() call.
  28523. Index scanning is turned off by default - turn it on with enableIndexScanning().
  28524. Then when the read() method is called, if it comes across an index within that
  28525. block, the index number is stored and returned by this method.
  28526. Some devices might not support indexes, of course.
  28527. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  28528. @see enableIndexScanning
  28529. */
  28530. int getLastIndex() const;
  28531. /** Scans a track to find the position of any indexes within it.
  28532. @param trackNumber the track to look in, where 0 is the first track on the disc
  28533. @returns an array of sample positions of any index points found (not including
  28534. the index that marks the start of the track)
  28535. */
  28536. const Array <int> findIndexesInTrack (const int trackNumber);
  28537. /** Returns the CDDB id number for the CD.
  28538. It's not a great way of identifying a disc, but it's traditional.
  28539. */
  28540. int getCDDBId();
  28541. /** Tries to eject the disk.
  28542. Of course this might not be possible, if some other process is using it.
  28543. */
  28544. void ejectDisk();
  28545. enum
  28546. {
  28547. framesPerSecond = 75,
  28548. samplesPerFrame = 44100 / framesPerSecond
  28549. };
  28550. private:
  28551. Array<int> trackStartSamples;
  28552. #if JUCE_MAC
  28553. File volumeDir;
  28554. Array<File> tracks;
  28555. int currentReaderTrack;
  28556. ScopedPointer <AudioFormatReader> reader;
  28557. AudioCDReader (const File& volume);
  28558. #elif JUCE_WINDOWS
  28559. bool audioTracks [100];
  28560. void* handle;
  28561. MemoryBlock buffer;
  28562. bool indexingEnabled;
  28563. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  28564. AudioCDReader (void* handle);
  28565. int getIndexAt (int samplePos);
  28566. #elif JUCE_LINUX
  28567. AudioCDReader();
  28568. #endif
  28569. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDReader);
  28570. };
  28571. #endif
  28572. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  28573. /*** End of inlined file: juce_AudioCDReader.h ***/
  28574. #endif
  28575. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  28576. #endif
  28577. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28578. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  28579. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28580. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28581. /**
  28582. A class for keeping a list of available audio formats, and for deciding which
  28583. one to use to open a given file.
  28584. You can either use this class as a singleton object, or create instances of it
  28585. yourself. Once created, use its registerFormat() method to tell it which
  28586. formats it should use.
  28587. @see AudioFormat
  28588. */
  28589. class JUCE_API AudioFormatManager
  28590. {
  28591. public:
  28592. /** Creates an empty format manager.
  28593. Before it'll be any use, you'll need to call registerFormat() with all the
  28594. formats you want it to be able to recognise.
  28595. */
  28596. AudioFormatManager();
  28597. /** Destructor. */
  28598. ~AudioFormatManager();
  28599. /** Adds a format to the manager's list of available file types.
  28600. The object passed-in will be deleted by this object, so don't keep a pointer
  28601. to it!
  28602. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  28603. return this one when called.
  28604. */
  28605. void registerFormat (AudioFormat* newFormat,
  28606. bool makeThisTheDefaultFormat);
  28607. /** Handy method to make it easy to register the formats that come with Juce.
  28608. Currently, this will add WAV and AIFF to the list.
  28609. */
  28610. void registerBasicFormats();
  28611. /** Clears the list of known formats. */
  28612. void clearFormats();
  28613. /** Returns the number of currently registered file formats. */
  28614. int getNumKnownFormats() const;
  28615. /** Returns one of the registered file formats. */
  28616. AudioFormat* getKnownFormat (int index) const;
  28617. /** Looks for which of the known formats is listed as being for a given file
  28618. extension.
  28619. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  28620. */
  28621. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  28622. /** Returns the format which has been set as the default one.
  28623. You can set a format as being the default when it is registered. It's useful
  28624. when you want to write to a file, because the best format may change between
  28625. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  28626. If none has been set as the default, this method will just return the first
  28627. one in the list.
  28628. */
  28629. AudioFormat* getDefaultFormat() const;
  28630. /** Returns a set of wildcards for file-matching that contains the extensions for
  28631. all known formats.
  28632. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  28633. */
  28634. String getWildcardForAllFormats() const;
  28635. /** Searches through the known formats to try to create a suitable reader for
  28636. this file.
  28637. If none of the registered formats can open the file, it'll return 0. If it
  28638. returns a reader, it's the caller's responsibility to delete the reader.
  28639. */
  28640. AudioFormatReader* createReaderFor (const File& audioFile);
  28641. /** Searches through the known formats to try to create a suitable reader for
  28642. this stream.
  28643. The stream object that is passed-in will be deleted by this method or by the
  28644. reader that is returned, so the caller should not keep any references to it.
  28645. The stream that is passed-in must be capable of being repositioned so
  28646. that all the formats can have a go at opening it.
  28647. If none of the registered formats can open the stream, it'll return 0. If it
  28648. returns a reader, it's the caller's responsibility to delete the reader.
  28649. */
  28650. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  28651. private:
  28652. OwnedArray<AudioFormat> knownFormats;
  28653. int defaultFormatIndex;
  28654. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatManager);
  28655. };
  28656. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28657. /*** End of inlined file: juce_AudioFormatManager.h ***/
  28658. #endif
  28659. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  28660. #endif
  28661. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28662. #endif
  28663. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28664. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  28665. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28666. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28667. /**
  28668. This class is used to wrap an AudioFormatReader and only read from a
  28669. subsection of the file.
  28670. So if you have a reader which can read a 1000 sample file, you could wrap it
  28671. in one of these to only access, e.g. samples 100 to 200, and any samples
  28672. outside that will come back as 0. Accessing sample 0 from this reader will
  28673. actually read the first sample from the other's subsection, which might
  28674. be at a non-zero position.
  28675. @see AudioFormatReader
  28676. */
  28677. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  28678. {
  28679. public:
  28680. /** Creates a AudioSubsectionReader for a given data source.
  28681. @param sourceReader the source reader from which we'll be taking data
  28682. @param subsectionStartSample the sample within the source reader which will be
  28683. mapped onto sample 0 for this reader.
  28684. @param subsectionLength the number of samples from the source that will
  28685. make up the subsection. If this reader is asked for
  28686. any samples beyond this region, it will return zero.
  28687. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  28688. this object is deleted.
  28689. */
  28690. AudioSubsectionReader (AudioFormatReader* sourceReader,
  28691. int64 subsectionStartSample,
  28692. int64 subsectionLength,
  28693. bool deleteSourceWhenDeleted);
  28694. /** Destructor. */
  28695. ~AudioSubsectionReader();
  28696. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28697. int64 startSampleInFile, int numSamples);
  28698. void readMaxLevels (int64 startSample,
  28699. int64 numSamples,
  28700. float& lowestLeft,
  28701. float& highestLeft,
  28702. float& lowestRight,
  28703. float& highestRight);
  28704. private:
  28705. AudioFormatReader* const source;
  28706. int64 startSample, length;
  28707. const bool deleteSourceWhenDeleted;
  28708. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSubsectionReader);
  28709. };
  28710. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28711. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  28712. #endif
  28713. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28714. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  28715. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28716. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28717. class AudioThumbnailCache;
  28718. /**
  28719. Makes it easy to quickly draw scaled views of the waveform shape of an
  28720. audio file.
  28721. To use this class, just create an AudioThumbNail class for the file you want
  28722. to draw, call setSource to tell it which file or resource to use, then call
  28723. drawChannel() to draw it.
  28724. The class will asynchronously scan the wavefile to create its scaled-down view,
  28725. so you should make your UI repaint itself as this data comes in. To do this, the
  28726. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  28727. listeners should repaint themselves.
  28728. The thumbnail stores an internal low-res version of the wave data, and this can
  28729. be loaded and saved to avoid having to scan the file again.
  28730. @see AudioThumbnailCache
  28731. */
  28732. class JUCE_API AudioThumbnail : public ChangeBroadcaster
  28733. {
  28734. public:
  28735. /** Creates an audio thumbnail.
  28736. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  28737. of the audio data, this is the scale at which it should be done. (This
  28738. number is the number of original samples that will be averaged for each
  28739. low-res sample)
  28740. @param formatManagerToUse the audio format manager that is used to open the file
  28741. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  28742. thread and storage that is used to by the thumbnail, and the cache
  28743. object can be shared between multiple thumbnails
  28744. */
  28745. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  28746. AudioFormatManager& formatManagerToUse,
  28747. AudioThumbnailCache& cacheToUse);
  28748. /** Destructor. */
  28749. ~AudioThumbnail();
  28750. /** Clears and resets the thumbnail. */
  28751. void clear();
  28752. /** Specifies the file or stream that contains the audio file.
  28753. For a file, just call
  28754. @code
  28755. setSource (new FileInputSource (file))
  28756. @endcode
  28757. You can pass a zero in here to clear the thumbnail.
  28758. The source that is passed in will be deleted by this object when it is no longer needed.
  28759. @returns true if the source could be opened as a valid audio file, false if this failed for
  28760. some reason.
  28761. */
  28762. bool setSource (InputSource* newSource);
  28763. /** Gives the thumbnail an AudioFormatReader to use directly.
  28764. This will start parsing the audio in a background thread (unless the hash code
  28765. can be looked-up successfully in the thumbnail cache). Note that the reader
  28766. object will be held by the thumbnail and deleted later when no longer needed.
  28767. The thumbnail will actually keep hold of this reader until you clear the thumbnail
  28768. or change the input source, so the file will be held open for all this time. If
  28769. you don't want the thumbnail to keep a file handle open continuously, you
  28770. should use the setSource() method instead, which will only open the file when
  28771. it needs to.
  28772. */
  28773. void setReader (AudioFormatReader* newReader, int64 hashCode);
  28774. /** Resets the thumbnail, ready for adding data with the specified format.
  28775. If you're going to generate a thumbnail yourself, call this before using addBlock()
  28776. to add the data.
  28777. */
  28778. void reset (int numChannels, double sampleRate, int64 totalSamplesInSource = 0);
  28779. /** Adds a block of level data to the thumbnail.
  28780. Call reset() before using this, to tell the thumbnail about the data format.
  28781. */
  28782. void addBlock (int64 sampleNumberInSource, const AudioSampleBuffer& newData,
  28783. int startOffsetInBuffer, int numSamples);
  28784. /** Reloads the low res thumbnail data from an input stream.
  28785. This is not an audio file stream! It takes a stream of thumbnail data that would
  28786. previously have been created by the saveTo() method.
  28787. @see saveTo
  28788. */
  28789. void loadFrom (InputStream& input);
  28790. /** Saves the low res thumbnail data to an output stream.
  28791. The data that is written can later be reloaded using loadFrom().
  28792. @see loadFrom
  28793. */
  28794. void saveTo (OutputStream& output) const;
  28795. /** Returns the number of channels in the file. */
  28796. int getNumChannels() const noexcept;
  28797. /** Returns the length of the audio file, in seconds. */
  28798. double getTotalLength() const noexcept;
  28799. /** Draws the waveform for a channel.
  28800. The waveform will be drawn within the specified rectangle, where startTime
  28801. and endTime specify the times within the audio file that should be positioned
  28802. at the left and right edges of the rectangle.
  28803. The waveform will be scaled vertically so that a full-volume sample will fill
  28804. the rectangle vertically, but you can also specify an extra vertical scale factor
  28805. with the verticalZoomFactor parameter.
  28806. */
  28807. void drawChannel (Graphics& g,
  28808. const Rectangle<int>& area,
  28809. double startTimeSeconds,
  28810. double endTimeSeconds,
  28811. int channelNum,
  28812. float verticalZoomFactor);
  28813. /** Draws the waveforms for all channels in the thumbnail.
  28814. This will call drawChannel() to render each of the thumbnail's channels, stacked
  28815. above each other within the specified area.
  28816. @see drawChannel
  28817. */
  28818. void drawChannels (Graphics& g,
  28819. const Rectangle<int>& area,
  28820. double startTimeSeconds,
  28821. double endTimeSeconds,
  28822. float verticalZoomFactor);
  28823. /** Returns true if the low res preview is fully generated. */
  28824. bool isFullyLoaded() const noexcept;
  28825. /** Returns the number of samples that have been set in the thumbnail. */
  28826. int64 getNumSamplesFinished() const noexcept;
  28827. /** Returns the highest level in the thumbnail.
  28828. Note that because the thumb only stores low-resolution data, this isn't
  28829. an accurate representation of the highest value, it's only a rough approximation.
  28830. */
  28831. float getApproximatePeak() const;
  28832. /** Reads the approximate min and max levels from a section of the thumbnail.
  28833. The lowest and highest samples are returned in minValue and maxValue, but obviously
  28834. because the thumb only stores low-resolution data, these numbers will only be a rough
  28835. approximation of the true values.
  28836. */
  28837. void getApproximateMinMax (double startTime, double endTime, int channelIndex,
  28838. float& minValue, float& maxValue) const noexcept;
  28839. /** Returns the hash code that was set by setSource() or setReader(). */
  28840. int64 getHashCode() const;
  28841. #ifndef DOXYGEN
  28842. class LevelDataSource; // (this is only public to avoid a VC6 bug)
  28843. #endif
  28844. private:
  28845. AudioFormatManager& formatManagerToUse;
  28846. AudioThumbnailCache& cache;
  28847. struct MinMaxValue;
  28848. class ThumbData;
  28849. class CachedWindow;
  28850. friend class LevelDataSource;
  28851. friend class ScopedPointer<LevelDataSource>;
  28852. friend class ThumbData;
  28853. friend class OwnedArray<ThumbData>;
  28854. friend class CachedWindow;
  28855. friend class ScopedPointer<CachedWindow>;
  28856. ScopedPointer<LevelDataSource> source;
  28857. ScopedPointer<CachedWindow> window;
  28858. OwnedArray<ThumbData> channels;
  28859. int32 samplesPerThumbSample;
  28860. int64 totalSamples, numSamplesFinished;
  28861. int32 numChannels;
  28862. double sampleRate;
  28863. CriticalSection lock;
  28864. void clearChannelData();
  28865. bool setDataSource (LevelDataSource* newSource);
  28866. void setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues);
  28867. void createChannels (int length);
  28868. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnail);
  28869. };
  28870. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28871. /*** End of inlined file: juce_AudioThumbnail.h ***/
  28872. #endif
  28873. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28874. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  28875. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28876. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28877. struct ThumbnailCacheEntry;
  28878. /**
  28879. An instance of this class is used to manage multiple AudioThumbnail objects.
  28880. The cache runs a single background thread that is shared by all the thumbnails
  28881. that need it, and it maintains a set of low-res previews in memory, to avoid
  28882. having to re-scan audio files too often.
  28883. @see AudioThumbnail
  28884. */
  28885. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  28886. {
  28887. public:
  28888. /** Creates a cache object.
  28889. The maxNumThumbsToStore parameter lets you specify how many previews should
  28890. be kept in memory at once.
  28891. */
  28892. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  28893. /** Destructor. */
  28894. ~AudioThumbnailCache();
  28895. /** Clears out any stored thumbnails.
  28896. */
  28897. void clear();
  28898. /** Reloads the specified thumb if this cache contains the appropriate stored
  28899. data.
  28900. This is called automatically by the AudioThumbnail class, so you shouldn't
  28901. normally need to call it directly.
  28902. */
  28903. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  28904. /** Stores the cachable data from the specified thumb in this cache.
  28905. This is called automatically by the AudioThumbnail class, so you shouldn't
  28906. normally need to call it directly.
  28907. */
  28908. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  28909. private:
  28910. OwnedArray <ThumbnailCacheEntry> thumbs;
  28911. int maxNumThumbsToStore;
  28912. ThumbnailCacheEntry* findThumbFor (int64 hash) const;
  28913. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnailCache);
  28914. };
  28915. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28916. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  28917. #endif
  28918. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28919. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  28920. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28921. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28922. #if JUCE_USE_FLAC || defined (DOXYGEN)
  28923. /**
  28924. Reads and writes the lossless-compression FLAC audio format.
  28925. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  28926. and make sure your include search path and library search path are set up to find
  28927. the FLAC header files and static libraries.
  28928. @see AudioFormat
  28929. */
  28930. class JUCE_API FlacAudioFormat : public AudioFormat
  28931. {
  28932. public:
  28933. FlacAudioFormat();
  28934. ~FlacAudioFormat();
  28935. const Array <int> getPossibleSampleRates();
  28936. const Array <int> getPossibleBitDepths();
  28937. bool canDoStereo();
  28938. bool canDoMono();
  28939. bool isCompressed();
  28940. StringArray getQualityOptions();
  28941. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28942. bool deleteStreamIfOpeningFails);
  28943. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28944. double sampleRateToUse,
  28945. unsigned int numberOfChannels,
  28946. int bitsPerSample,
  28947. const StringPairArray& metadataValues,
  28948. int qualityOptionIndex);
  28949. private:
  28950. JUCE_LEAK_DETECTOR (FlacAudioFormat);
  28951. };
  28952. #endif
  28953. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28954. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  28955. #endif
  28956. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28957. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  28958. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28959. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28960. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  28961. /**
  28962. Reads and writes the Ogg-Vorbis audio format.
  28963. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  28964. and make sure your include search path and library search path are set up to find
  28965. the Vorbis and Ogg header files and static libraries.
  28966. @see AudioFormat,
  28967. */
  28968. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  28969. {
  28970. public:
  28971. OggVorbisAudioFormat();
  28972. ~OggVorbisAudioFormat();
  28973. const Array<int> getPossibleSampleRates();
  28974. const Array<int> getPossibleBitDepths();
  28975. bool canDoStereo();
  28976. bool canDoMono();
  28977. bool isCompressed();
  28978. StringArray getQualityOptions();
  28979. /** Tries to estimate the quality level of an ogg file based on its size.
  28980. If it can't read the file for some reason, this will just return 1 (medium quality),
  28981. otherwise it will return the approximate quality setting that would have been used
  28982. to create the file.
  28983. @see getQualityOptions
  28984. */
  28985. int estimateOggFileQuality (const File& source);
  28986. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28987. bool deleteStreamIfOpeningFails);
  28988. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28989. double sampleRateToUse,
  28990. unsigned int numberOfChannels,
  28991. int bitsPerSample,
  28992. const StringPairArray& metadataValues,
  28993. int qualityOptionIndex);
  28994. private:
  28995. JUCE_LEAK_DETECTOR (OggVorbisAudioFormat);
  28996. };
  28997. #endif
  28998. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28999. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  29000. #endif
  29001. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  29002. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  29003. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  29004. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  29005. #if JUCE_QUICKTIME
  29006. /**
  29007. Uses QuickTime to read the audio track a movie or media file.
  29008. As well as QuickTime movies, this should also manage to open other audio
  29009. files that quicktime can understand, like mp3, m4a, etc.
  29010. @see AudioFormat
  29011. */
  29012. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  29013. {
  29014. public:
  29015. /** Creates a format object. */
  29016. QuickTimeAudioFormat();
  29017. /** Destructor. */
  29018. ~QuickTimeAudioFormat();
  29019. const Array <int> getPossibleSampleRates();
  29020. const Array <int> getPossibleBitDepths();
  29021. bool canDoStereo();
  29022. bool canDoMono();
  29023. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  29024. bool deleteStreamIfOpeningFails);
  29025. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  29026. double sampleRateToUse,
  29027. unsigned int numberOfChannels,
  29028. int bitsPerSample,
  29029. const StringPairArray& metadataValues,
  29030. int qualityOptionIndex);
  29031. private:
  29032. JUCE_LEAK_DETECTOR (QuickTimeAudioFormat);
  29033. };
  29034. #endif
  29035. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  29036. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  29037. #endif
  29038. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  29039. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  29040. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  29041. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  29042. /**
  29043. Reads and Writes WAV format audio files.
  29044. @see AudioFormat
  29045. */
  29046. class JUCE_API WavAudioFormat : public AudioFormat
  29047. {
  29048. public:
  29049. /** Creates a format object. */
  29050. WavAudioFormat();
  29051. /** Destructor. */
  29052. ~WavAudioFormat();
  29053. /** Metadata property name used by wav readers and writers for adding
  29054. a BWAV chunk to the file.
  29055. @see AudioFormatReader::metadataValues, createWriterFor
  29056. */
  29057. static const char* const bwavDescription;
  29058. /** Metadata property name used by wav readers and writers for adding
  29059. a BWAV chunk to the file.
  29060. @see AudioFormatReader::metadataValues, createWriterFor
  29061. */
  29062. static const char* const bwavOriginator;
  29063. /** Metadata property name used by wav readers and writers for adding
  29064. a BWAV chunk to the file.
  29065. @see AudioFormatReader::metadataValues, createWriterFor
  29066. */
  29067. static const char* const bwavOriginatorRef;
  29068. /** Metadata property name used by wav readers and writers for adding
  29069. a BWAV chunk to the file.
  29070. Date format is: yyyy-mm-dd
  29071. @see AudioFormatReader::metadataValues, createWriterFor
  29072. */
  29073. static const char* const bwavOriginationDate;
  29074. /** Metadata property name used by wav readers and writers for adding
  29075. a BWAV chunk to the file.
  29076. Time format is: hh-mm-ss
  29077. @see AudioFormatReader::metadataValues, createWriterFor
  29078. */
  29079. static const char* const bwavOriginationTime;
  29080. /** Metadata property name used by wav readers and writers for adding
  29081. a BWAV chunk to the file.
  29082. This is the number of samples from the start of an edit that the
  29083. file is supposed to begin at. Seems like an obvious mistake to
  29084. only allow a file to occur in an edit once, but that's the way
  29085. it is..
  29086. @see AudioFormatReader::metadataValues, createWriterFor
  29087. */
  29088. static const char* const bwavTimeReference;
  29089. /** Metadata property name used by wav readers and writers for adding
  29090. a BWAV chunk to the file.
  29091. This is a
  29092. @see AudioFormatReader::metadataValues, createWriterFor
  29093. */
  29094. static const char* const bwavCodingHistory;
  29095. /** Utility function to fill out the appropriate metadata for a BWAV file.
  29096. This just makes it easier than using the property names directly, and it
  29097. fills out the time and date in the right format.
  29098. */
  29099. static StringPairArray createBWAVMetadata (const String& description,
  29100. const String& originator,
  29101. const String& originatorRef,
  29102. const Time& dateAndTime,
  29103. const int64 timeReferenceSamples,
  29104. const String& codingHistory);
  29105. const Array <int> getPossibleSampleRates();
  29106. const Array <int> getPossibleBitDepths();
  29107. bool canDoStereo();
  29108. bool canDoMono();
  29109. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  29110. bool deleteStreamIfOpeningFails);
  29111. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  29112. double sampleRateToUse,
  29113. unsigned int numberOfChannels,
  29114. int bitsPerSample,
  29115. const StringPairArray& metadataValues,
  29116. int qualityOptionIndex);
  29117. /** Utility function to replace the metadata in a wav file with a new set of values.
  29118. If possible, this cheats by overwriting just the metadata region of the file, rather
  29119. than by copying the whole file again.
  29120. */
  29121. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  29122. private:
  29123. JUCE_LEAK_DETECTOR (WavAudioFormat);
  29124. };
  29125. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  29126. /*** End of inlined file: juce_WavAudioFormat.h ***/
  29127. #endif
  29128. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  29129. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  29130. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  29131. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  29132. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  29133. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29134. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29135. /**
  29136. A type of AudioSource which can be repositioned.
  29137. The basic AudioSource just streams continuously with no idea of a current
  29138. time or length, so the PositionableAudioSource is used for a finite stream
  29139. that has a current read position.
  29140. @see AudioSource, AudioTransportSource
  29141. */
  29142. class JUCE_API PositionableAudioSource : public AudioSource
  29143. {
  29144. protected:
  29145. /** Creates the PositionableAudioSource. */
  29146. PositionableAudioSource() noexcept {}
  29147. public:
  29148. /** Destructor */
  29149. ~PositionableAudioSource() {}
  29150. /** Tells the stream to move to a new position.
  29151. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  29152. should return samples from this position.
  29153. Note that this may be called on a different thread to getNextAudioBlock(),
  29154. so the subclass should make sure it's synchronised.
  29155. */
  29156. virtual void setNextReadPosition (int64 newPosition) = 0;
  29157. /** Returns the position from which the next block will be returned.
  29158. @see setNextReadPosition
  29159. */
  29160. virtual int64 getNextReadPosition() const = 0;
  29161. /** Returns the total length of the stream (in samples). */
  29162. virtual int64 getTotalLength() const = 0;
  29163. /** Returns true if this source is actually playing in a loop. */
  29164. virtual bool isLooping() const = 0;
  29165. /** Tells the source whether you'd like it to play in a loop. */
  29166. virtual void setLooping (bool shouldLoop) { (void) shouldLoop; }
  29167. };
  29168. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29169. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  29170. /**
  29171. A type of AudioSource that will read from an AudioFormatReader.
  29172. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  29173. */
  29174. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  29175. {
  29176. public:
  29177. /** Creates an AudioFormatReaderSource for a given reader.
  29178. @param sourceReader the reader to use as the data source - this must
  29179. not be null
  29180. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  29181. when this object is deleted; if false it will be
  29182. left up to the caller to manage its lifetime
  29183. */
  29184. AudioFormatReaderSource (AudioFormatReader* sourceReader,
  29185. bool deleteReaderWhenThisIsDeleted);
  29186. /** Destructor. */
  29187. ~AudioFormatReaderSource();
  29188. /** Toggles loop-mode.
  29189. If set to true, it will continuously loop the input source. If false,
  29190. it will just emit silence after the source has finished.
  29191. @see isLooping
  29192. */
  29193. void setLooping (bool shouldLoop);
  29194. /** Returns whether loop-mode is turned on or not. */
  29195. bool isLooping() const { return looping; }
  29196. /** Returns the reader that's being used. */
  29197. AudioFormatReader* getAudioFormatReader() const noexcept { return reader; }
  29198. /** Implementation of the AudioSource method. */
  29199. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29200. /** Implementation of the AudioSource method. */
  29201. void releaseResources();
  29202. /** Implementation of the AudioSource method. */
  29203. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29204. /** Implements the PositionableAudioSource method. */
  29205. void setNextReadPosition (int64 newPosition);
  29206. /** Implements the PositionableAudioSource method. */
  29207. int64 getNextReadPosition() const;
  29208. /** Implements the PositionableAudioSource method. */
  29209. int64 getTotalLength() const;
  29210. private:
  29211. OptionalScopedPointer<AudioFormatReader> reader;
  29212. int64 volatile nextPlayPos;
  29213. bool volatile looping;
  29214. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  29215. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReaderSource);
  29216. };
  29217. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  29218. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  29219. #endif
  29220. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  29221. #endif
  29222. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29223. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  29224. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29225. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29226. /*** Start of inlined file: juce_AudioIODevice.h ***/
  29227. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  29228. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  29229. class AudioIODevice;
  29230. /**
  29231. One of these is passed to an AudioIODevice object to stream the audio data
  29232. in and out.
  29233. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  29234. method on its own high-priority audio thread, when it needs to send or receive
  29235. the next block of data.
  29236. @see AudioIODevice, AudioDeviceManager
  29237. */
  29238. class JUCE_API AudioIODeviceCallback
  29239. {
  29240. public:
  29241. /** Destructor. */
  29242. virtual ~AudioIODeviceCallback() {}
  29243. /** Processes a block of incoming and outgoing audio data.
  29244. The subclass's implementation should use the incoming audio for whatever
  29245. purposes it needs to, and must fill all the output channels with the next
  29246. block of output data before returning.
  29247. The channel data is arranged with the same array indices as the channel name
  29248. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  29249. that aren't specified in AudioIODevice::open() will have a null pointer for their
  29250. associated channel, so remember to check for this.
  29251. @param inputChannelData a set of arrays containing the audio data for each
  29252. incoming channel - this data is valid until the function
  29253. returns. There will be one channel of data for each input
  29254. channel that was enabled when the audio device was opened
  29255. (see AudioIODevice::open())
  29256. @param numInputChannels the number of pointers to channel data in the
  29257. inputChannelData array.
  29258. @param outputChannelData a set of arrays which need to be filled with the data
  29259. that should be sent to each outgoing channel of the device.
  29260. There will be one channel of data for each output channel
  29261. that was enabled when the audio device was opened (see
  29262. AudioIODevice::open())
  29263. The initial contents of the array is undefined, so the
  29264. callback function must fill all the channels with zeros if
  29265. its output is silence. Failing to do this could cause quite
  29266. an unpleasant noise!
  29267. @param numOutputChannels the number of pointers to channel data in the
  29268. outputChannelData array.
  29269. @param numSamples the number of samples in each channel of the input and
  29270. output arrays. The number of samples will depend on the
  29271. audio device's buffer size and will usually remain constant,
  29272. although this isn't guaranteed, so make sure your code can
  29273. cope with reasonable changes in the buffer size from one
  29274. callback to the next.
  29275. */
  29276. virtual void audioDeviceIOCallback (const float** inputChannelData,
  29277. int numInputChannels,
  29278. float** outputChannelData,
  29279. int numOutputChannels,
  29280. int numSamples) = 0;
  29281. /** Called to indicate that the device is about to start calling back.
  29282. This will be called just before the audio callbacks begin, either when this
  29283. callback has just been added to an audio device, or after the device has been
  29284. restarted because of a sample-rate or block-size change.
  29285. You can use this opportunity to find out the sample rate and block size
  29286. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  29287. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  29288. @param device the audio IO device that will be used to drive the callback.
  29289. Note that if you're going to store this this pointer, it is
  29290. only valid until the next time that audioDeviceStopped is called.
  29291. */
  29292. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  29293. /** Called to indicate that the device has stopped. */
  29294. virtual void audioDeviceStopped() = 0;
  29295. /** This can be overridden to be told if the device generates an error while operating.
  29296. Be aware that this could be called by any thread! And not all devices perform
  29297. this callback.
  29298. */
  29299. virtual void audioDeviceError (const String& errorMessage);
  29300. };
  29301. /**
  29302. Base class for an audio device with synchronised input and output channels.
  29303. Subclasses of this are used to implement different protocols such as DirectSound,
  29304. ASIO, CoreAudio, etc.
  29305. To create one of these, you'll need to use the AudioIODeviceType class - see the
  29306. documentation for that class for more info.
  29307. For an easier way of managing audio devices and their settings, have a look at the
  29308. AudioDeviceManager class.
  29309. @see AudioIODeviceType, AudioDeviceManager
  29310. */
  29311. class JUCE_API AudioIODevice
  29312. {
  29313. public:
  29314. /** Destructor. */
  29315. virtual ~AudioIODevice();
  29316. /** Returns the device's name, (as set in the constructor). */
  29317. const String& getName() const noexcept { return name; }
  29318. /** Returns the type of the device.
  29319. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  29320. */
  29321. const String& getTypeName() const noexcept { return typeName; }
  29322. /** Returns the names of all the available output channels on this device.
  29323. To find out which of these are currently in use, call getActiveOutputChannels().
  29324. */
  29325. virtual StringArray getOutputChannelNames() = 0;
  29326. /** Returns the names of all the available input channels on this device.
  29327. To find out which of these are currently in use, call getActiveInputChannels().
  29328. */
  29329. virtual StringArray getInputChannelNames() = 0;
  29330. /** Returns the number of sample-rates this device supports.
  29331. To find out which rates are available on this device, use this method to
  29332. find out how many there are, and getSampleRate() to get the rates.
  29333. @see getSampleRate
  29334. */
  29335. virtual int getNumSampleRates() = 0;
  29336. /** Returns one of the sample-rates this device supports.
  29337. To find out which rates are available on this device, use getNumSampleRates() to
  29338. find out how many there are, and getSampleRate() to get the individual rates.
  29339. The sample rate is set by the open() method.
  29340. (Note that for DirectSound some rates might not work, depending on combinations
  29341. of i/o channels that are being opened).
  29342. @see getNumSampleRates
  29343. */
  29344. virtual double getSampleRate (int index) = 0;
  29345. /** Returns the number of sizes of buffer that are available.
  29346. @see getBufferSizeSamples, getDefaultBufferSize
  29347. */
  29348. virtual int getNumBufferSizesAvailable() = 0;
  29349. /** Returns one of the possible buffer-sizes.
  29350. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  29351. @returns a number of samples
  29352. @see getNumBufferSizesAvailable, getDefaultBufferSize
  29353. */
  29354. virtual int getBufferSizeSamples (int index) = 0;
  29355. /** Returns the default buffer-size to use.
  29356. @returns a number of samples
  29357. @see getNumBufferSizesAvailable, getBufferSizeSamples
  29358. */
  29359. virtual int getDefaultBufferSize() = 0;
  29360. /** Tries to open the device ready to play.
  29361. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  29362. input channel should be enabled
  29363. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  29364. output channel should be enabled
  29365. @param sampleRate the sample rate to try to use - to find out which rates are
  29366. available, see getNumSampleRates() and getSampleRate()
  29367. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  29368. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  29369. @returns an error description if there's a problem, or an empty string if it succeeds in
  29370. opening the device
  29371. @see close
  29372. */
  29373. virtual const String open (const BigInteger& inputChannels,
  29374. const BigInteger& outputChannels,
  29375. double sampleRate,
  29376. int bufferSizeSamples) = 0;
  29377. /** Closes and releases the device if it's open. */
  29378. virtual void close() = 0;
  29379. /** Returns true if the device is still open.
  29380. A device might spontaneously close itself if something goes wrong, so this checks if
  29381. it's still open.
  29382. */
  29383. virtual bool isOpen() = 0;
  29384. /** Starts the device actually playing.
  29385. This must be called after the device has been opened.
  29386. @param callback the callback to use for streaming the data.
  29387. @see AudioIODeviceCallback, open
  29388. */
  29389. virtual void start (AudioIODeviceCallback* callback) = 0;
  29390. /** Stops the device playing.
  29391. Once a device has been started, this will stop it. Any pending calls to the
  29392. callback class will be flushed before this method returns.
  29393. */
  29394. virtual void stop() = 0;
  29395. /** Returns true if the device is still calling back.
  29396. The device might mysteriously stop, so this checks whether it's
  29397. still playing.
  29398. */
  29399. virtual bool isPlaying() = 0;
  29400. /** Returns the last error that happened if anything went wrong. */
  29401. virtual const String getLastError() = 0;
  29402. /** Returns the buffer size that the device is currently using.
  29403. If the device isn't actually open, this value doesn't really mean much.
  29404. */
  29405. virtual int getCurrentBufferSizeSamples() = 0;
  29406. /** Returns the sample rate that the device is currently using.
  29407. If the device isn't actually open, this value doesn't really mean much.
  29408. */
  29409. virtual double getCurrentSampleRate() = 0;
  29410. /** Returns the device's current physical bit-depth.
  29411. If the device isn't actually open, this value doesn't really mean much.
  29412. */
  29413. virtual int getCurrentBitDepth() = 0;
  29414. /** Returns a mask showing which of the available output channels are currently
  29415. enabled.
  29416. @see getOutputChannelNames
  29417. */
  29418. virtual const BigInteger getActiveOutputChannels() const = 0;
  29419. /** Returns a mask showing which of the available input channels are currently
  29420. enabled.
  29421. @see getInputChannelNames
  29422. */
  29423. virtual const BigInteger getActiveInputChannels() const = 0;
  29424. /** Returns the device's output latency.
  29425. This is the delay in samples between a callback getting a block of data, and
  29426. that data actually getting played.
  29427. */
  29428. virtual int getOutputLatencyInSamples() = 0;
  29429. /** Returns the device's input latency.
  29430. This is the delay in samples between some audio actually arriving at the soundcard,
  29431. and the callback getting passed this block of data.
  29432. */
  29433. virtual int getInputLatencyInSamples() = 0;
  29434. /** True if this device can show a pop-up control panel for editing its settings.
  29435. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  29436. to display it.
  29437. */
  29438. virtual bool hasControlPanel() const;
  29439. /** Shows a device-specific control panel if there is one.
  29440. This should only be called for devices which return true from hasControlPanel().
  29441. */
  29442. virtual bool showControlPanel();
  29443. protected:
  29444. /** Creates a device, setting its name and type member variables. */
  29445. AudioIODevice (const String& deviceName,
  29446. const String& typeName);
  29447. /** @internal */
  29448. String name, typeName;
  29449. };
  29450. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  29451. /*** End of inlined file: juce_AudioIODevice.h ***/
  29452. /**
  29453. Wrapper class to continuously stream audio from an audio source to an
  29454. AudioIODevice.
  29455. This object acts as an AudioIODeviceCallback, so can be attached to an
  29456. output device, and will stream audio from an AudioSource.
  29457. */
  29458. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  29459. {
  29460. public:
  29461. /** Creates an empty AudioSourcePlayer. */
  29462. AudioSourcePlayer();
  29463. /** Destructor.
  29464. Make sure this object isn't still being used by an AudioIODevice before
  29465. deleting it!
  29466. */
  29467. virtual ~AudioSourcePlayer();
  29468. /** Changes the current audio source to play from.
  29469. If the source passed in is already being used, this method will do nothing.
  29470. If the source is not null, its prepareToPlay() method will be called
  29471. before it starts being used for playback.
  29472. If there's another source currently playing, its releaseResources() method
  29473. will be called after it has been swapped for the new one.
  29474. @param newSource the new source to use - this will NOT be deleted
  29475. by this object when no longer needed, so it's the
  29476. caller's responsibility to manage it.
  29477. */
  29478. void setSource (AudioSource* newSource);
  29479. /** Returns the source that's playing.
  29480. May return 0 if there's no source.
  29481. */
  29482. AudioSource* getCurrentSource() const noexcept { return source; }
  29483. /** Sets a gain to apply to the audio data.
  29484. @see getGain
  29485. */
  29486. void setGain (float newGain) noexcept;
  29487. /** Returns the current gain.
  29488. @see setGain
  29489. */
  29490. float getGain() const noexcept { return gain; }
  29491. /** Implementation of the AudioIODeviceCallback method. */
  29492. void audioDeviceIOCallback (const float** inputChannelData,
  29493. int totalNumInputChannels,
  29494. float** outputChannelData,
  29495. int totalNumOutputChannels,
  29496. int numSamples);
  29497. /** Implementation of the AudioIODeviceCallback method. */
  29498. void audioDeviceAboutToStart (AudioIODevice* device);
  29499. /** Implementation of the AudioIODeviceCallback method. */
  29500. void audioDeviceStopped();
  29501. private:
  29502. CriticalSection readLock;
  29503. AudioSource* source;
  29504. double sampleRate;
  29505. int bufferSize;
  29506. float* channels [128];
  29507. float* outputChans [128];
  29508. const float* inputChans [128];
  29509. AudioSampleBuffer tempBuffer;
  29510. float lastGain, gain;
  29511. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSourcePlayer);
  29512. };
  29513. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29514. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  29515. #endif
  29516. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29517. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  29518. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29519. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29520. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  29521. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29522. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29523. /**
  29524. An AudioSource which takes another source as input, and buffers it using a thread.
  29525. Create this as a wrapper around another thread, and it will read-ahead with
  29526. a background thread to smooth out playback. You can either create one of these
  29527. directly, or use it indirectly using an AudioTransportSource.
  29528. @see PositionableAudioSource, AudioTransportSource
  29529. */
  29530. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  29531. {
  29532. public:
  29533. /** Creates a BufferingAudioSource.
  29534. @param source the input source to read from
  29535. @param deleteSourceWhenDeleted if true, then the input source object will
  29536. be deleted when this object is deleted
  29537. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  29538. @param numberOfChannels the number of channels that will be played
  29539. */
  29540. BufferingAudioSource (PositionableAudioSource* source,
  29541. bool deleteSourceWhenDeleted,
  29542. int numberOfSamplesToBuffer,
  29543. int numberOfChannels = 2);
  29544. /** Destructor.
  29545. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  29546. flag was set in the constructor.
  29547. */
  29548. ~BufferingAudioSource();
  29549. /** Implementation of the AudioSource method. */
  29550. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29551. /** Implementation of the AudioSource method. */
  29552. void releaseResources();
  29553. /** Implementation of the AudioSource method. */
  29554. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29555. /** Implements the PositionableAudioSource method. */
  29556. void setNextReadPosition (int64 newPosition);
  29557. /** Implements the PositionableAudioSource method. */
  29558. int64 getNextReadPosition() const;
  29559. /** Implements the PositionableAudioSource method. */
  29560. int64 getTotalLength() const { return source->getTotalLength(); }
  29561. /** Implements the PositionableAudioSource method. */
  29562. bool isLooping() const { return source->isLooping(); }
  29563. private:
  29564. OptionalScopedPointer<PositionableAudioSource> source;
  29565. int numberOfSamplesToBuffer, numberOfChannels;
  29566. AudioSampleBuffer buffer;
  29567. CriticalSection bufferStartPosLock;
  29568. int64 volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  29569. double volatile sampleRate;
  29570. bool wasSourceLooping;
  29571. friend class SharedBufferingAudioSourceThread;
  29572. bool readNextBufferChunk();
  29573. void readBufferSection (int64 start, int length, int bufferOffset);
  29574. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferingAudioSource);
  29575. };
  29576. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29577. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  29578. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  29579. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29580. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29581. /**
  29582. A type of AudioSource that takes an input source and changes its sample rate.
  29583. @see AudioSource
  29584. */
  29585. class JUCE_API ResamplingAudioSource : public AudioSource
  29586. {
  29587. public:
  29588. /** Creates a ResamplingAudioSource for a given input source.
  29589. @param inputSource the input source to read from
  29590. @param deleteInputWhenDeleted if true, the input source will be deleted when
  29591. this object is deleted
  29592. @param numChannels the number of channels to process
  29593. */
  29594. ResamplingAudioSource (AudioSource* inputSource,
  29595. bool deleteInputWhenDeleted,
  29596. int numChannels = 2);
  29597. /** Destructor. */
  29598. ~ResamplingAudioSource();
  29599. /** Changes the resampling ratio.
  29600. (This value can be changed at any time, even while the source is running).
  29601. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  29602. values will speed it up; lower values will slow it
  29603. down. The ratio must be greater than 0
  29604. */
  29605. void setResamplingRatio (double samplesInPerOutputSample);
  29606. /** Returns the current resampling ratio.
  29607. This is the value that was set by setResamplingRatio().
  29608. */
  29609. double getResamplingRatio() const noexcept { return ratio; }
  29610. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29611. void releaseResources();
  29612. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29613. private:
  29614. OptionalScopedPointer<AudioSource> input;
  29615. double ratio, lastRatio;
  29616. AudioSampleBuffer buffer;
  29617. int bufferPos, sampsInBuffer;
  29618. double subSampleOffset;
  29619. double coefficients[6];
  29620. SpinLock ratioLock;
  29621. const int numChannels;
  29622. HeapBlock<float*> destBuffers, srcBuffers;
  29623. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  29624. void createLowPass (double proportionalRate);
  29625. struct FilterState
  29626. {
  29627. double x1, x2, y1, y2;
  29628. };
  29629. HeapBlock<FilterState> filterStates;
  29630. void resetFilters();
  29631. void applyFilter (float* samples, int num, FilterState& fs);
  29632. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResamplingAudioSource);
  29633. };
  29634. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29635. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  29636. /**
  29637. An AudioSource that takes a PositionableAudioSource and allows it to be
  29638. played, stopped, started, etc.
  29639. This can also be told use a buffer and background thread to read ahead, and
  29640. if can correct for different sample-rates.
  29641. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  29642. to control playback of an audio file.
  29643. @see AudioSource, AudioSourcePlayer
  29644. */
  29645. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  29646. public ChangeBroadcaster
  29647. {
  29648. public:
  29649. /** Creates an AudioTransportSource.
  29650. After creating one of these, use the setSource() method to select an input source.
  29651. */
  29652. AudioTransportSource();
  29653. /** Destructor. */
  29654. ~AudioTransportSource();
  29655. /** Sets the reader that is being used as the input source.
  29656. This will stop playback, reset the position to 0 and change to the new reader.
  29657. The source passed in will not be deleted by this object, so must be managed by
  29658. the caller.
  29659. @param newSource the new input source to use. This may be zero
  29660. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  29661. is zero, no reading ahead will be done; if it's
  29662. greater than zero, a BufferingAudioSource will be used
  29663. to do the reading-ahead
  29664. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  29665. rate of the source, and playback will be sample-rate
  29666. adjusted to maintain playback at the correct pitch. If
  29667. this is 0, no sample-rate adjustment will be performed
  29668. @param maxNumChannels the maximum number of channels that may need to be played
  29669. */
  29670. void setSource (PositionableAudioSource* newSource,
  29671. int readAheadBufferSize = 0,
  29672. double sourceSampleRateToCorrectFor = 0.0,
  29673. int maxNumChannels = 2);
  29674. /** Changes the current playback position in the source stream.
  29675. The next time the getNextAudioBlock() method is called, this
  29676. is the time from which it'll read data.
  29677. @see getPosition
  29678. */
  29679. void setPosition (double newPosition);
  29680. /** Returns the position that the next data block will be read from
  29681. This is a time in seconds.
  29682. */
  29683. double getCurrentPosition() const;
  29684. /** Returns the stream's length in seconds. */
  29685. double getLengthInSeconds() const;
  29686. /** Returns true if the player has stopped because its input stream ran out of data.
  29687. */
  29688. bool hasStreamFinished() const noexcept { return inputStreamEOF; }
  29689. /** Starts playing (if a source has been selected).
  29690. If it starts playing, this will send a message to any ChangeListeners
  29691. that are registered with this object.
  29692. */
  29693. void start();
  29694. /** Stops playing.
  29695. If it's actually playing, this will send a message to any ChangeListeners
  29696. that are registered with this object.
  29697. */
  29698. void stop();
  29699. /** Returns true if it's currently playing. */
  29700. bool isPlaying() const noexcept { return playing; }
  29701. /** Changes the gain to apply to the output.
  29702. @param newGain a factor by which to multiply the outgoing samples,
  29703. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  29704. */
  29705. void setGain (float newGain) noexcept;
  29706. /** Returns the current gain setting.
  29707. @see setGain
  29708. */
  29709. float getGain() const noexcept { return gain; }
  29710. /** Implementation of the AudioSource method. */
  29711. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29712. /** Implementation of the AudioSource method. */
  29713. void releaseResources();
  29714. /** Implementation of the AudioSource method. */
  29715. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29716. /** Implements the PositionableAudioSource method. */
  29717. void setNextReadPosition (int64 newPosition);
  29718. /** Implements the PositionableAudioSource method. */
  29719. int64 getNextReadPosition() const;
  29720. /** Implements the PositionableAudioSource method. */
  29721. int64 getTotalLength() const;
  29722. /** Implements the PositionableAudioSource method. */
  29723. bool isLooping() const;
  29724. private:
  29725. PositionableAudioSource* source;
  29726. ResamplingAudioSource* resamplerSource;
  29727. BufferingAudioSource* bufferingSource;
  29728. PositionableAudioSource* positionableSource;
  29729. AudioSource* masterSource;
  29730. CriticalSection callbackLock;
  29731. float volatile gain, lastGain;
  29732. bool volatile playing, stopped;
  29733. double sampleRate, sourceSampleRate;
  29734. int blockSize, readAheadBufferSize;
  29735. bool isPrepared, inputStreamEOF;
  29736. void releaseMasterResources();
  29737. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioTransportSource);
  29738. };
  29739. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29740. /*** End of inlined file: juce_AudioTransportSource.h ***/
  29741. #endif
  29742. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29743. #endif
  29744. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29745. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  29746. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29747. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29748. /**
  29749. An AudioSource that takes the audio from another source, and re-maps its
  29750. input and output channels to a different arrangement.
  29751. You can use this to increase or decrease the number of channels that an
  29752. audio source uses, or to re-order those channels.
  29753. Call the reset() method before using it to set up a default mapping, and then
  29754. the setInputChannelMapping() and setOutputChannelMapping() methods to
  29755. create an appropriate mapping, otherwise no channels will be connected and
  29756. it'll produce silence.
  29757. @see AudioSource
  29758. */
  29759. class ChannelRemappingAudioSource : public AudioSource
  29760. {
  29761. public:
  29762. /** Creates a remapping source that will pass on audio from the given input.
  29763. @param source the input source to use. Make sure that this doesn't
  29764. get deleted before the ChannelRemappingAudioSource object
  29765. @param deleteSourceWhenDeleted if true, the input source will be deleted
  29766. when this object is deleted, if false, the caller is
  29767. responsible for its deletion
  29768. */
  29769. ChannelRemappingAudioSource (AudioSource* source,
  29770. bool deleteSourceWhenDeleted);
  29771. /** Destructor. */
  29772. ~ChannelRemappingAudioSource();
  29773. /** Specifies a number of channels that this audio source must produce from its
  29774. getNextAudioBlock() callback.
  29775. */
  29776. void setNumberOfChannelsToProduce (int requiredNumberOfChannels);
  29777. /** Clears any mapped channels.
  29778. After this, no channels are mapped, so this object will produce silence. Create
  29779. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  29780. */
  29781. void clearAllMappings();
  29782. /** Creates an input channel mapping.
  29783. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  29784. data will be sent to destChannelIndex of our input source.
  29785. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  29786. source specified when this object was created).
  29787. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  29788. during our getNextAudioBlock() callback
  29789. */
  29790. void setInputChannelMapping (int destChannelIndex,
  29791. int sourceChannelIndex);
  29792. /** Creates an output channel mapping.
  29793. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  29794. our input audio source will be copied to channel destChannelIndex of the final buffer.
  29795. @param sourceChannelIndex the index of an output channel coming from our input audio source
  29796. (i.e. the source specified when this object was created).
  29797. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  29798. during our getNextAudioBlock() callback
  29799. */
  29800. void setOutputChannelMapping (int sourceChannelIndex,
  29801. int destChannelIndex);
  29802. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  29803. our input audio source.
  29804. */
  29805. int getRemappedInputChannel (int inputChannelIndex) const;
  29806. /** Returns the output channel to which channel outputChannelIndex of our input audio
  29807. source will be sent to.
  29808. */
  29809. int getRemappedOutputChannel (int outputChannelIndex) const;
  29810. /** Returns an XML object to encapsulate the state of the mappings.
  29811. @see restoreFromXml
  29812. */
  29813. XmlElement* createXml() const;
  29814. /** Restores the mappings from an XML object created by createXML().
  29815. @see createXml
  29816. */
  29817. void restoreFromXml (const XmlElement& e);
  29818. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29819. void releaseResources();
  29820. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29821. private:
  29822. OptionalScopedPointer<AudioSource> source;
  29823. Array <int> remappedInputs, remappedOutputs;
  29824. int requiredNumberOfChannels;
  29825. AudioSampleBuffer buffer;
  29826. AudioSourceChannelInfo remappedInfo;
  29827. CriticalSection lock;
  29828. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelRemappingAudioSource);
  29829. };
  29830. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29831. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  29832. #endif
  29833. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29834. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  29835. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29836. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29837. /*** Start of inlined file: juce_IIRFilter.h ***/
  29838. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  29839. #define __JUCE_IIRFILTER_JUCEHEADER__
  29840. /**
  29841. An IIR filter that can perform low, high, or band-pass filtering on an
  29842. audio signal.
  29843. @see IIRFilterAudioSource
  29844. */
  29845. class JUCE_API IIRFilter
  29846. {
  29847. public:
  29848. /** Creates a filter.
  29849. Initially the filter is inactive, so will have no effect on samples that
  29850. you process with it. Use the appropriate method to turn it into the type
  29851. of filter needed.
  29852. */
  29853. IIRFilter();
  29854. /** Creates a copy of another filter. */
  29855. IIRFilter (const IIRFilter& other);
  29856. /** Destructor. */
  29857. ~IIRFilter();
  29858. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  29859. Note that this clears the processing state, but the type of filter and
  29860. its coefficients aren't changed. To put a filter into an inactive state, use
  29861. the makeInactive() method.
  29862. */
  29863. void reset() noexcept;
  29864. /** Performs the filter operation on the given set of samples.
  29865. */
  29866. void processSamples (float* samples,
  29867. int numSamples) noexcept;
  29868. /** Processes a single sample, without any locking or checking.
  29869. Use this if you need fast processing of a single value, but be aware that
  29870. this isn't thread-safe in the way that processSamples() is.
  29871. */
  29872. float processSingleSampleRaw (float sample) noexcept;
  29873. /** Sets the filter up to act as a low-pass filter.
  29874. */
  29875. void makeLowPass (double sampleRate,
  29876. double frequency) noexcept;
  29877. /** Sets the filter up to act as a high-pass filter.
  29878. */
  29879. void makeHighPass (double sampleRate,
  29880. double frequency) noexcept;
  29881. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  29882. The gain is a scale factor that the low frequencies are multiplied by, so values
  29883. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  29884. attenuate them.
  29885. */
  29886. void makeLowShelf (double sampleRate,
  29887. double cutOffFrequency,
  29888. double Q,
  29889. float gainFactor) noexcept;
  29890. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  29891. The gain is a scale factor that the high frequencies are multiplied by, so values
  29892. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  29893. attenuate them.
  29894. */
  29895. void makeHighShelf (double sampleRate,
  29896. double cutOffFrequency,
  29897. double Q,
  29898. float gainFactor) noexcept;
  29899. /** Sets the filter up to act as a band pass filter centred around a
  29900. frequency, with a variable Q and gain.
  29901. The gain is a scale factor that the centre frequencies are multiplied by, so
  29902. values greater than 1.0 will boost the centre frequencies, values less than
  29903. 1.0 will attenuate them.
  29904. */
  29905. void makeBandPass (double sampleRate,
  29906. double centreFrequency,
  29907. double Q,
  29908. float gainFactor) noexcept;
  29909. /** Clears the filter's coefficients so that it becomes inactive.
  29910. */
  29911. void makeInactive() noexcept;
  29912. /** Makes this filter duplicate the set-up of another one.
  29913. */
  29914. void copyCoefficientsFrom (const IIRFilter& other) noexcept;
  29915. protected:
  29916. CriticalSection processLock;
  29917. void setCoefficients (double c1, double c2, double c3,
  29918. double c4, double c5, double c6) noexcept;
  29919. bool active;
  29920. float coefficients[6];
  29921. float x1, x2, y1, y2;
  29922. // (use the copyCoefficientsFrom() method instead of this operator)
  29923. IIRFilter& operator= (const IIRFilter&);
  29924. JUCE_LEAK_DETECTOR (IIRFilter);
  29925. };
  29926. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  29927. /*** End of inlined file: juce_IIRFilter.h ***/
  29928. /**
  29929. An AudioSource that performs an IIR filter on another source.
  29930. */
  29931. class JUCE_API IIRFilterAudioSource : public AudioSource
  29932. {
  29933. public:
  29934. /** Creates a IIRFilterAudioSource for a given input source.
  29935. @param inputSource the input source to read from - this must not be null
  29936. @param deleteInputWhenDeleted if true, the input source will be deleted when
  29937. this object is deleted
  29938. */
  29939. IIRFilterAudioSource (AudioSource* inputSource,
  29940. bool deleteInputWhenDeleted);
  29941. /** Destructor. */
  29942. ~IIRFilterAudioSource();
  29943. /** Changes the filter to use the same parameters as the one being passed in. */
  29944. void setFilterParameters (const IIRFilter& newSettings);
  29945. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29946. void releaseResources();
  29947. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29948. private:
  29949. OptionalScopedPointer<AudioSource> input;
  29950. OwnedArray <IIRFilter> iirFilters;
  29951. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IIRFilterAudioSource);
  29952. };
  29953. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29954. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  29955. #endif
  29956. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29957. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  29958. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29959. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29960. /**
  29961. An AudioSource that mixes together the output of a set of other AudioSources.
  29962. Input sources can be added and removed while the mixer is running as long as their
  29963. prepareToPlay() and releaseResources() methods are called before and after adding
  29964. them to the mixer.
  29965. */
  29966. class JUCE_API MixerAudioSource : public AudioSource
  29967. {
  29968. public:
  29969. /** Creates a MixerAudioSource.
  29970. */
  29971. MixerAudioSource();
  29972. /** Destructor. */
  29973. ~MixerAudioSource();
  29974. /** Adds an input source to the mixer.
  29975. If the mixer is running you'll need to make sure that the input source
  29976. is ready to play by calling its prepareToPlay() method before adding it.
  29977. If the mixer is stopped, then its input sources will be automatically
  29978. prepared when the mixer's prepareToPlay() method is called.
  29979. @param newInput the source to add to the mixer
  29980. @param deleteWhenRemoved if true, then this source will be deleted when
  29981. the mixer is deleted or when removeAllInputs() is
  29982. called (unless the source is previously removed
  29983. with the removeInputSource method)
  29984. */
  29985. void addInputSource (AudioSource* newInput, bool deleteWhenRemoved);
  29986. /** Removes an input source.
  29987. If the mixer is running, this will remove the source but not call its
  29988. releaseResources() method, so the caller might want to do this manually.
  29989. @param input the source to remove
  29990. @param deleteSource whether to delete this source after it's been removed
  29991. */
  29992. void removeInputSource (AudioSource* input, bool deleteSource);
  29993. /** Removes all the input sources.
  29994. If the mixer is running, this will remove the sources but not call their
  29995. releaseResources() method, so the caller might want to do this manually.
  29996. Any sources which were added with the deleteWhenRemoved flag set will be
  29997. deleted by this method.
  29998. */
  29999. void removeAllInputs();
  30000. /** Implementation of the AudioSource method.
  30001. This will call prepareToPlay() on all its input sources.
  30002. */
  30003. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  30004. /** Implementation of the AudioSource method.
  30005. This will call releaseResources() on all its input sources.
  30006. */
  30007. void releaseResources();
  30008. /** Implementation of the AudioSource method. */
  30009. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  30010. private:
  30011. Array <AudioSource*> inputs;
  30012. BigInteger inputsToDelete;
  30013. CriticalSection lock;
  30014. AudioSampleBuffer tempBuffer;
  30015. double currentSampleRate;
  30016. int bufferSizeExpected;
  30017. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MixerAudioSource);
  30018. };
  30019. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  30020. /*** End of inlined file: juce_MixerAudioSource.h ***/
  30021. #endif
  30022. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  30023. #endif
  30024. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  30025. #endif
  30026. #ifndef __JUCE_REVERBAUDIOSOURCE_JUCEHEADER__
  30027. /*** Start of inlined file: juce_ReverbAudioSource.h ***/
  30028. #ifndef __JUCE_REVERBAUDIOSOURCE_JUCEHEADER__
  30029. #define __JUCE_REVERBAUDIOSOURCE_JUCEHEADER__
  30030. /*** Start of inlined file: juce_Reverb.h ***/
  30031. #ifndef __JUCE_REVERB_JUCEHEADER__
  30032. #define __JUCE_REVERB_JUCEHEADER__
  30033. /**
  30034. Performs a simple reverb effect on a stream of audio data.
  30035. This is a simple stereo reverb, based on the technique and tunings used in FreeVerb.
  30036. Use setSampleRate() to prepare it, and then call processStereo() or processMono() to
  30037. apply the reverb to your audio data.
  30038. @see ReverbAudioSource
  30039. */
  30040. class Reverb
  30041. {
  30042. public:
  30043. Reverb()
  30044. {
  30045. setParameters (Parameters());
  30046. setSampleRate (44100.0);
  30047. }
  30048. /** Holds the parameters being used by a Reverb object. */
  30049. struct Parameters
  30050. {
  30051. Parameters() noexcept
  30052. : roomSize (0.5f),
  30053. damping (0.5f),
  30054. wetLevel (0.33f),
  30055. dryLevel (0.4f),
  30056. width (1.0f),
  30057. freezeMode (0)
  30058. {}
  30059. float roomSize; /**< Room size, 0 to 1.0, where 1.0 is big, 0 is small. */
  30060. float damping; /**< Damping, 0 to 1.0, where 0 is not damped, 1.0 is fully damped. */
  30061. float wetLevel; /**< Wet level, 0 to 1.0 */
  30062. float dryLevel; /**< Dry level, 0 to 1.0 */
  30063. float width; /**< Reverb width, 0 to 1.0, where 1.0 is very wide. */
  30064. float freezeMode; /**< Freeze mode - values < 0.5 are "normal" mode, values > 0.5
  30065. put the reverb into a continuous feedback loop. */
  30066. };
  30067. /** Returns the reverb's current parameters. */
  30068. const Parameters& getParameters() const noexcept { return parameters; }
  30069. /** Applies a new set of parameters to the reverb.
  30070. Note that this doesn't attempt to lock the reverb, so if you call this in parallel with
  30071. the process method, you may get artifacts.
  30072. */
  30073. void setParameters (const Parameters& newParams)
  30074. {
  30075. const float wetScaleFactor = 3.0f;
  30076. const float dryScaleFactor = 2.0f;
  30077. const float wet = newParams.wetLevel * wetScaleFactor;
  30078. wet1 = wet * (newParams.width * 0.5f + 0.5f);
  30079. wet2 = wet * (1.0f - newParams.width) * 0.5f;
  30080. dry = newParams.dryLevel * dryScaleFactor;
  30081. gain = isFrozen (newParams.freezeMode) ? 0.0f : 0.015f;
  30082. parameters = newParams;
  30083. shouldUpdateDamping = true;
  30084. }
  30085. /** Sets the sample rate that will be used for the reverb.
  30086. You must call this before the process methods, in order to tell it the correct sample rate.
  30087. */
  30088. void setSampleRate (const double sampleRate)
  30089. {
  30090. jassert (sampleRate > 0);
  30091. static const short combTunings[] = { 1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617 }; // (at 44100Hz)
  30092. static const short allPassTunings[] = { 556, 441, 341, 225 };
  30093. const int stereoSpread = 23;
  30094. const int intSampleRate = (int) sampleRate;
  30095. int i;
  30096. for (i = 0; i < numCombs; ++i)
  30097. {
  30098. comb[0][i].setSize ((intSampleRate * combTunings[i]) / 44100);
  30099. comb[1][i].setSize ((intSampleRate * (combTunings[i] + stereoSpread)) / 44100);
  30100. }
  30101. for (i = 0; i < numAllPasses; ++i)
  30102. {
  30103. allPass[0][i].setSize ((intSampleRate * allPassTunings[i]) / 44100);
  30104. allPass[1][i].setSize ((intSampleRate * (allPassTunings[i] + stereoSpread)) / 44100);
  30105. }
  30106. shouldUpdateDamping = true;
  30107. }
  30108. /** Clears the reverb's buffers. */
  30109. void reset()
  30110. {
  30111. for (int j = 0; j < numChannels; ++j)
  30112. {
  30113. int i;
  30114. for (i = 0; i < numCombs; ++i)
  30115. comb[j][i].clear();
  30116. for (i = 0; i < numAllPasses; ++i)
  30117. allPass[j][i].clear();
  30118. }
  30119. }
  30120. /** Applies the reverb to two stereo channels of audio data. */
  30121. void processStereo (float* const left, float* const right, const int numSamples) noexcept
  30122. {
  30123. jassert (left != nullptr && right != nullptr);
  30124. if (shouldUpdateDamping)
  30125. updateDamping();
  30126. for (int i = 0; i < numSamples; ++i)
  30127. {
  30128. const float input = (left[i] + right[i]) * gain;
  30129. float outL = 0, outR = 0;
  30130. int j;
  30131. for (j = 0; j < numCombs; ++j) // accumulate the comb filters in parallel
  30132. {
  30133. outL += comb[0][j].process (input);
  30134. outR += comb[1][j].process (input);
  30135. }
  30136. for (j = 0; j < numAllPasses; ++j) // run the allpass filters in series
  30137. {
  30138. outL = allPass[0][j].process (outL);
  30139. outR = allPass[1][j].process (outR);
  30140. }
  30141. left[i] = outL * wet1 + outR * wet2 + left[i] * dry;
  30142. right[i] = outR * wet1 + outL * wet2 + right[i] * dry;
  30143. }
  30144. }
  30145. /** Applies the reverb to a single mono channel of audio data. */
  30146. void processMono (float* const samples, const int numSamples) noexcept
  30147. {
  30148. jassert (samples != nullptr);
  30149. if (shouldUpdateDamping)
  30150. updateDamping();
  30151. for (int i = 0; i < numSamples; ++i)
  30152. {
  30153. const float input = samples[i] * gain;
  30154. float output = 0;
  30155. int j;
  30156. for (j = 0; j < numCombs; ++j) // accumulate the comb filters in parallel
  30157. output += comb[0][j].process (input);
  30158. for (j = 0; j < numAllPasses; ++j) // run the allpass filters in series
  30159. output = allPass[0][j].process (output);
  30160. samples[i] = output * wet1 + input * dry;
  30161. }
  30162. }
  30163. private:
  30164. Parameters parameters;
  30165. volatile bool shouldUpdateDamping;
  30166. float gain, wet1, wet2, dry;
  30167. inline static bool isFrozen (const float freezeMode) noexcept { return freezeMode >= 0.5f; }
  30168. void updateDamping() noexcept
  30169. {
  30170. const float roomScaleFactor = 0.28f;
  30171. const float roomOffset = 0.7f;
  30172. const float dampScaleFactor = 0.4f;
  30173. shouldUpdateDamping = false;
  30174. if (isFrozen (parameters.freezeMode))
  30175. setDamping (1.0f, 0.0f);
  30176. else
  30177. setDamping (parameters.damping * dampScaleFactor,
  30178. parameters.roomSize * roomScaleFactor + roomOffset);
  30179. }
  30180. void setDamping (const float dampingToUse, const float roomSizeToUse) noexcept
  30181. {
  30182. for (int j = 0; j < numChannels; ++j)
  30183. for (int i = numCombs; --i >= 0;)
  30184. comb[j][i].setFeedbackAndDamp (roomSizeToUse, dampingToUse);
  30185. }
  30186. class CombFilter
  30187. {
  30188. public:
  30189. CombFilter() noexcept : bufferSize (0), bufferIndex (0) {}
  30190. void setSize (const int size)
  30191. {
  30192. if (size != bufferSize)
  30193. {
  30194. bufferIndex = 0;
  30195. buffer.malloc (size);
  30196. bufferSize = size;
  30197. }
  30198. clear();
  30199. }
  30200. void clear() noexcept
  30201. {
  30202. last = 0;
  30203. buffer.clear (bufferSize);
  30204. }
  30205. void setFeedbackAndDamp (const float f, const float d) noexcept
  30206. {
  30207. damp1 = d;
  30208. damp2 = 1.0f - d;
  30209. feedback = f;
  30210. }
  30211. inline float process (const float input) noexcept
  30212. {
  30213. const float output = buffer [bufferIndex];
  30214. last = (output * damp2) + (last * damp1);
  30215. JUCE_UNDENORMALISE (last);
  30216. float temp = input + (last * feedback);
  30217. JUCE_UNDENORMALISE (temp);
  30218. buffer [bufferIndex] = temp;
  30219. bufferIndex = (bufferIndex + 1) % bufferSize;
  30220. return output;
  30221. }
  30222. private:
  30223. HeapBlock<float> buffer;
  30224. int bufferSize, bufferIndex;
  30225. float feedback, last, damp1, damp2;
  30226. JUCE_DECLARE_NON_COPYABLE (CombFilter);
  30227. };
  30228. class AllPassFilter
  30229. {
  30230. public:
  30231. AllPassFilter() noexcept : bufferSize (0), bufferIndex (0) {}
  30232. void setSize (const int size)
  30233. {
  30234. if (size != bufferSize)
  30235. {
  30236. bufferIndex = 0;
  30237. buffer.malloc (size);
  30238. bufferSize = size;
  30239. }
  30240. clear();
  30241. }
  30242. void clear() noexcept
  30243. {
  30244. buffer.clear (bufferSize);
  30245. }
  30246. inline float process (const float input) noexcept
  30247. {
  30248. const float bufferedValue = buffer [bufferIndex];
  30249. float temp = input + (bufferedValue * 0.5f);
  30250. JUCE_UNDENORMALISE (temp);
  30251. buffer [bufferIndex] = temp;
  30252. bufferIndex = (bufferIndex + 1) % bufferSize;
  30253. return bufferedValue - input;
  30254. }
  30255. private:
  30256. HeapBlock<float> buffer;
  30257. int bufferSize, bufferIndex;
  30258. JUCE_DECLARE_NON_COPYABLE (AllPassFilter);
  30259. };
  30260. enum { numCombs = 8, numAllPasses = 4, numChannels = 2 };
  30261. CombFilter comb [numChannels][numCombs];
  30262. AllPassFilter allPass [numChannels][numAllPasses];
  30263. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Reverb);
  30264. };
  30265. #endif // __JUCE_REVERB_JUCEHEADER__
  30266. /*** End of inlined file: juce_Reverb.h ***/
  30267. /**
  30268. An AudioSource that uses the Reverb class to apply a reverb to another AudioSource.
  30269. @see Reverb
  30270. */
  30271. class JUCE_API ReverbAudioSource : public AudioSource
  30272. {
  30273. public:
  30274. /** Creates a ReverbAudioSource to process a given input source.
  30275. @param inputSource the input source to read from - this must not be null
  30276. @param deleteInputWhenDeleted if true, the input source will be deleted when
  30277. this object is deleted
  30278. */
  30279. ReverbAudioSource (AudioSource* inputSource,
  30280. bool deleteInputWhenDeleted);
  30281. /** Destructor. */
  30282. ~ReverbAudioSource();
  30283. /** Returns the parameters from the reverb. */
  30284. const Reverb::Parameters& getParameters() const noexcept { return reverb.getParameters(); }
  30285. /** Changes the reverb's parameters. */
  30286. void setParameters (const Reverb::Parameters& newParams);
  30287. void setBypassed (bool isBypassed) noexcept;
  30288. bool isBypassed() const noexcept { return bypass; }
  30289. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  30290. void releaseResources();
  30291. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  30292. private:
  30293. CriticalSection lock;
  30294. OptionalScopedPointer<AudioSource> input;
  30295. Reverb reverb;
  30296. volatile bool bypass;
  30297. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ReverbAudioSource);
  30298. };
  30299. #endif // __JUCE_REVERBAUDIOSOURCE_JUCEHEADER__
  30300. /*** End of inlined file: juce_ReverbAudioSource.h ***/
  30301. #endif
  30302. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  30303. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  30304. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  30305. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  30306. /**
  30307. A simple AudioSource that generates a sine wave.
  30308. */
  30309. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  30310. {
  30311. public:
  30312. /** Creates a ToneGeneratorAudioSource. */
  30313. ToneGeneratorAudioSource();
  30314. /** Destructor. */
  30315. ~ToneGeneratorAudioSource();
  30316. /** Sets the signal's amplitude. */
  30317. void setAmplitude (float newAmplitude);
  30318. /** Sets the signal's frequency. */
  30319. void setFrequency (double newFrequencyHz);
  30320. /** Implementation of the AudioSource method. */
  30321. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  30322. /** Implementation of the AudioSource method. */
  30323. void releaseResources();
  30324. /** Implementation of the AudioSource method. */
  30325. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  30326. private:
  30327. double frequency, sampleRate;
  30328. double currentPhase, phasePerSample;
  30329. float amplitude;
  30330. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToneGeneratorAudioSource);
  30331. };
  30332. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  30333. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  30334. #endif
  30335. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  30336. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  30337. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  30338. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  30339. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  30340. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  30341. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  30342. class AudioDeviceManager;
  30343. /**
  30344. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  30345. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  30346. method. Each of the objects returned can then be used to list the available
  30347. devices of that type. E.g.
  30348. @code
  30349. OwnedArray <AudioIODeviceType> types;
  30350. myAudioDeviceManager.createAudioDeviceTypes (types);
  30351. for (int i = 0; i < types.size(); ++i)
  30352. {
  30353. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  30354. types[i]->scanForDevices(); // This must be called before getting the list of devices
  30355. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  30356. for (int j = 0; j < deviceNames.size(); ++j)
  30357. {
  30358. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  30359. ...
  30360. }
  30361. }
  30362. @endcode
  30363. For an easier way of managing audio devices and their settings, have a look at the
  30364. AudioDeviceManager class.
  30365. @see AudioIODevice, AudioDeviceManager
  30366. */
  30367. class JUCE_API AudioIODeviceType
  30368. {
  30369. public:
  30370. /** Returns the name of this type of driver that this object manages.
  30371. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  30372. */
  30373. const String& getTypeName() const noexcept { return typeName; }
  30374. /** Refreshes the object's cached list of known devices.
  30375. This must be called at least once before calling getDeviceNames() or any of
  30376. the other device creation methods.
  30377. */
  30378. virtual void scanForDevices() = 0;
  30379. /** Returns the list of available devices of this type.
  30380. The scanForDevices() method must have been called to create this list.
  30381. @param wantInputNames only really used by DirectSound where devices are split up
  30382. into inputs and outputs, this indicates whether to use
  30383. the input or output name to refer to a pair of devices.
  30384. */
  30385. virtual StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  30386. /** Returns the name of the default device.
  30387. This will be one of the names from the getDeviceNames() list.
  30388. @param forInput if true, this means that a default input device should be
  30389. returned; if false, it should return the default output
  30390. */
  30391. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  30392. /** Returns the index of a given device in the list of device names.
  30393. If asInput is true, it shows the index in the inputs list, otherwise it
  30394. looks for it in the outputs list.
  30395. */
  30396. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  30397. /** Returns true if two different devices can be used for the input and output.
  30398. */
  30399. virtual bool hasSeparateInputsAndOutputs() const = 0;
  30400. /** Creates one of the devices of this type.
  30401. The deviceName must be one of the strings returned by getDeviceNames(), and
  30402. scanForDevices() must have been called before this method is used.
  30403. */
  30404. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  30405. const String& inputDeviceName) = 0;
  30406. /**
  30407. A class for receiving events when audio devices are inserted or removed.
  30408. You can register a AudioIODeviceType::Listener with an~AudioIODeviceType object
  30409. using the AudioIODeviceType::addListener() method, and it will be called when
  30410. devices of that type are added or removed.
  30411. @see AudioIODeviceType::addListener, AudioIODeviceType::removeListener
  30412. */
  30413. class Listener
  30414. {
  30415. public:
  30416. virtual ~Listener() {}
  30417. /** Called when the list of available audio devices changes. */
  30418. virtual void audioDeviceListChanged() = 0;
  30419. };
  30420. /** Adds a listener that will be called when this type of device is added or
  30421. removed from the system.
  30422. */
  30423. void addListener (Listener* listener);
  30424. /** Removes a listener that was previously added with addListener(). */
  30425. void removeListener (Listener* listener);
  30426. /** Destructor. */
  30427. virtual ~AudioIODeviceType();
  30428. /** Creates a CoreAudio device type if it's available on this platform, or returns null. */
  30429. static AudioIODeviceType* createAudioIODeviceType_CoreAudio();
  30430. /** Creates an iOS device type if it's available on this platform, or returns null. */
  30431. static AudioIODeviceType* createAudioIODeviceType_iOSAudio();
  30432. /** Creates a WASAPI device type if it's available on this platform, or returns null. */
  30433. static AudioIODeviceType* createAudioIODeviceType_WASAPI();
  30434. /** Creates a DirectSound device type if it's available on this platform, or returns null. */
  30435. static AudioIODeviceType* createAudioIODeviceType_DirectSound();
  30436. /** Creates an ASIO device type if it's available on this platform, or returns null. */
  30437. static AudioIODeviceType* createAudioIODeviceType_ASIO();
  30438. /** Creates an ALSA device type if it's available on this platform, or returns null. */
  30439. static AudioIODeviceType* createAudioIODeviceType_ALSA();
  30440. /** Creates a JACK device type if it's available on this platform, or returns null. */
  30441. static AudioIODeviceType* createAudioIODeviceType_JACK();
  30442. /** Creates an Android device type if it's available on this platform, or returns null. */
  30443. static AudioIODeviceType* createAudioIODeviceType_Android();
  30444. protected:
  30445. explicit AudioIODeviceType (const String& typeName);
  30446. /** Synchronously calls all the registered device list change listeners. */
  30447. void callDeviceChangeListeners();
  30448. private:
  30449. String typeName;
  30450. ListenerList<Listener> listeners;
  30451. JUCE_DECLARE_NON_COPYABLE (AudioIODeviceType);
  30452. };
  30453. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  30454. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  30455. /*** Start of inlined file: juce_MidiInput.h ***/
  30456. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  30457. #define __JUCE_MIDIINPUT_JUCEHEADER__
  30458. /*** Start of inlined file: juce_MidiMessage.h ***/
  30459. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  30460. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  30461. /**
  30462. Encapsulates a MIDI message.
  30463. @see MidiMessageSequence, MidiOutput, MidiInput
  30464. */
  30465. class JUCE_API MidiMessage
  30466. {
  30467. public:
  30468. /** Creates a 3-byte short midi message.
  30469. @param byte1 message byte 1
  30470. @param byte2 message byte 2
  30471. @param byte3 message byte 3
  30472. @param timeStamp the time to give the midi message - this value doesn't
  30473. use any particular units, so will be application-specific
  30474. */
  30475. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) noexcept;
  30476. /** Creates a 2-byte short midi message.
  30477. @param byte1 message byte 1
  30478. @param byte2 message byte 2
  30479. @param timeStamp the time to give the midi message - this value doesn't
  30480. use any particular units, so will be application-specific
  30481. */
  30482. MidiMessage (int byte1, int byte2, double timeStamp = 0) noexcept;
  30483. /** Creates a 1-byte short midi message.
  30484. @param byte1 message byte 1
  30485. @param timeStamp the time to give the midi message - this value doesn't
  30486. use any particular units, so will be application-specific
  30487. */
  30488. MidiMessage (int byte1, double timeStamp = 0) noexcept;
  30489. /** Creates a midi message from a block of data. */
  30490. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  30491. /** Reads the next midi message from some data.
  30492. This will read as many bytes from a data stream as it needs to make a
  30493. complete message, and will return the number of bytes it used. This lets
  30494. you read a sequence of midi messages from a file or stream.
  30495. @param data the data to read from
  30496. @param maxBytesToUse the maximum number of bytes it's allowed to read
  30497. @param numBytesUsed returns the number of bytes that were actually needed
  30498. @param lastStatusByte in a sequence of midi messages, the initial byte
  30499. can be dropped from a message if it's the same as the
  30500. first byte of the previous message, so this lets you
  30501. supply the byte to use if the first byte of the message
  30502. has in fact been dropped.
  30503. @param timeStamp the time to give the midi message - this value doesn't
  30504. use any particular units, so will be application-specific
  30505. */
  30506. MidiMessage (const void* data, int maxBytesToUse,
  30507. int& numBytesUsed, uint8 lastStatusByte,
  30508. double timeStamp = 0);
  30509. /** Creates an active-sense message.
  30510. Since the MidiMessage has to contain a valid message, this default constructor
  30511. just initialises it with an empty sysex message.
  30512. */
  30513. MidiMessage() noexcept;
  30514. /** Creates a copy of another midi message. */
  30515. MidiMessage (const MidiMessage& other);
  30516. /** Creates a copy of another midi message, with a different timestamp. */
  30517. MidiMessage (const MidiMessage& other, double newTimeStamp);
  30518. /** Destructor. */
  30519. ~MidiMessage();
  30520. /** Copies this message from another one. */
  30521. MidiMessage& operator= (const MidiMessage& other);
  30522. /** Returns a pointer to the raw midi data.
  30523. @see getRawDataSize
  30524. */
  30525. uint8* getRawData() const noexcept { return data; }
  30526. /** Returns the number of bytes of data in the message.
  30527. @see getRawData
  30528. */
  30529. int getRawDataSize() const noexcept { return size; }
  30530. /** Returns the timestamp associated with this message.
  30531. The exact meaning of this time and its units will vary, as messages are used in
  30532. a variety of different contexts.
  30533. If you're getting the message from a midi file, this could be a time in seconds, or
  30534. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  30535. If the message is being used in a MidiBuffer, it might indicate the number of
  30536. audio samples from the start of the buffer.
  30537. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  30538. for details of the way that it initialises this value.
  30539. @see setTimeStamp, addToTimeStamp
  30540. */
  30541. double getTimeStamp() const noexcept { return timeStamp; }
  30542. /** Changes the message's associated timestamp.
  30543. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  30544. @see addToTimeStamp, getTimeStamp
  30545. */
  30546. void setTimeStamp (double newTimestamp) noexcept { timeStamp = newTimestamp; }
  30547. /** Adds a value to the message's timestamp.
  30548. The units for the timestamp will be application-specific.
  30549. */
  30550. void addToTimeStamp (double delta) noexcept { timeStamp += delta; }
  30551. /** Returns the midi channel associated with the message.
  30552. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  30553. if it's a sysex)
  30554. @see isForChannel, setChannel
  30555. */
  30556. int getChannel() const noexcept;
  30557. /** Returns true if the message applies to the given midi channel.
  30558. @param channelNumber the channel number to look for, in the range 1 to 16
  30559. @see getChannel, setChannel
  30560. */
  30561. bool isForChannel (int channelNumber) const noexcept;
  30562. /** Changes the message's midi channel.
  30563. This won't do anything for non-channel messages like sysexes.
  30564. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  30565. */
  30566. void setChannel (int newChannelNumber) noexcept;
  30567. /** Returns true if this is a system-exclusive message.
  30568. */
  30569. bool isSysEx() const noexcept;
  30570. /** Returns a pointer to the sysex data inside the message.
  30571. If this event isn't a sysex event, it'll return 0.
  30572. @see getSysExDataSize
  30573. */
  30574. const uint8* getSysExData() const noexcept;
  30575. /** Returns the size of the sysex data.
  30576. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  30577. @see getSysExData
  30578. */
  30579. int getSysExDataSize() const noexcept;
  30580. /** Returns true if this message is a 'key-down' event.
  30581. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  30582. velocity 0, it will still be considered to be a note-on and the
  30583. method will return true. If returnTrueForVelocity0 is false, then
  30584. if this is a note-on event with velocity 0, it'll be regarded as
  30585. a note-off, and the method will return false
  30586. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  30587. */
  30588. bool isNoteOn (bool returnTrueForVelocity0 = false) const noexcept;
  30589. /** Creates a key-down message (using a floating-point velocity).
  30590. @param channel the midi channel, in the range 1 to 16
  30591. @param noteNumber the key number, 0 to 127
  30592. @param velocity in the range 0 to 1.0
  30593. @see isNoteOn
  30594. */
  30595. static MidiMessage noteOn (int channel, int noteNumber, float velocity) noexcept;
  30596. /** Creates a key-down message (using an integer velocity).
  30597. @param channel the midi channel, in the range 1 to 16
  30598. @param noteNumber the key number, 0 to 127
  30599. @param velocity in the range 0 to 127
  30600. @see isNoteOn
  30601. */
  30602. static MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) noexcept;
  30603. /** Returns true if this message is a 'key-up' event.
  30604. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  30605. for a note-on event with a velocity of 0.
  30606. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  30607. */
  30608. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const noexcept;
  30609. /** Creates a key-up message.
  30610. @param channel the midi channel, in the range 1 to 16
  30611. @param noteNumber the key number, 0 to 127
  30612. @param velocity in the range 0 to 127
  30613. @see isNoteOff
  30614. */
  30615. static MidiMessage noteOff (int channel, int noteNumber, uint8 velocity = 0) noexcept;
  30616. /** Returns true if this message is a 'key-down' or 'key-up' event.
  30617. @see isNoteOn, isNoteOff
  30618. */
  30619. bool isNoteOnOrOff() const noexcept;
  30620. /** Returns the midi note number for note-on and note-off messages.
  30621. If the message isn't a note-on or off, the value returned is undefined.
  30622. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  30623. */
  30624. int getNoteNumber() const noexcept;
  30625. /** Changes the midi note number of a note-on or note-off message.
  30626. If the message isn't a note on or off, this will do nothing.
  30627. */
  30628. void setNoteNumber (int newNoteNumber) noexcept;
  30629. /** Returns the velocity of a note-on or note-off message.
  30630. The value returned will be in the range 0 to 127.
  30631. If the message isn't a note-on or off event, it will return 0.
  30632. @see getFloatVelocity
  30633. */
  30634. uint8 getVelocity() const noexcept;
  30635. /** Returns the velocity of a note-on or note-off message.
  30636. The value returned will be in the range 0 to 1.0
  30637. If the message isn't a note-on or off event, it will return 0.
  30638. @see getVelocity, setVelocity
  30639. */
  30640. float getFloatVelocity() const noexcept;
  30641. /** Changes the velocity of a note-on or note-off message.
  30642. If the message isn't a note on or off, this will do nothing.
  30643. @param newVelocity the new velocity, in the range 0 to 1.0
  30644. @see getFloatVelocity, multiplyVelocity
  30645. */
  30646. void setVelocity (float newVelocity) noexcept;
  30647. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  30648. If the message isn't a note on or off, this will do nothing.
  30649. @param scaleFactor the value by which to multiply the velocity
  30650. @see setVelocity
  30651. */
  30652. void multiplyVelocity (float scaleFactor) noexcept;
  30653. /** Returns true if this message is a 'sustain pedal down' controller message. */
  30654. bool isSustainPedalOn() const noexcept;
  30655. /** Returns true if this message is a 'sustain pedal up' controller message. */
  30656. bool isSustainPedalOff() const noexcept;
  30657. /** Returns true if this message is a 'sostenuto pedal down' controller message. */
  30658. bool isSostenutoPedalOn() const noexcept;
  30659. /** Returns true if this message is a 'sostenuto pedal up' controller message. */
  30660. bool isSostenutoPedalOff() const noexcept;
  30661. /** Returns true if this message is a 'soft pedal down' controller message. */
  30662. bool isSoftPedalOn() const noexcept;
  30663. /** Returns true if this message is a 'soft pedal up' controller message. */
  30664. bool isSoftPedalOff() const noexcept;
  30665. /** Returns true if the message is a program (patch) change message.
  30666. @see getProgramChangeNumber, getGMInstrumentName
  30667. */
  30668. bool isProgramChange() const noexcept;
  30669. /** Returns the new program number of a program change message.
  30670. If the message isn't a program change, the value returned will be
  30671. nonsense.
  30672. @see isProgramChange, getGMInstrumentName
  30673. */
  30674. int getProgramChangeNumber() const noexcept;
  30675. /** Creates a program-change message.
  30676. @param channel the midi channel, in the range 1 to 16
  30677. @param programNumber the midi program number, 0 to 127
  30678. @see isProgramChange, getGMInstrumentName
  30679. */
  30680. static MidiMessage programChange (int channel, int programNumber) noexcept;
  30681. /** Returns true if the message is a pitch-wheel move.
  30682. @see getPitchWheelValue, pitchWheel
  30683. */
  30684. bool isPitchWheel() const noexcept;
  30685. /** Returns the pitch wheel position from a pitch-wheel move message.
  30686. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  30687. If called for messages which aren't pitch wheel events, the number returned will be
  30688. nonsense.
  30689. @see isPitchWheel
  30690. */
  30691. int getPitchWheelValue() const noexcept;
  30692. /** Creates a pitch-wheel move message.
  30693. @param channel the midi channel, in the range 1 to 16
  30694. @param position the wheel position, in the range 0 to 16383
  30695. @see isPitchWheel
  30696. */
  30697. static MidiMessage pitchWheel (int channel, int position) noexcept;
  30698. /** Returns true if the message is an aftertouch event.
  30699. For aftertouch events, use the getNoteNumber() method to find out the key
  30700. that it applies to, and getAftertouchValue() to find out the amount. Use
  30701. getChannel() to find out the channel.
  30702. @see getAftertouchValue, getNoteNumber
  30703. */
  30704. bool isAftertouch() const noexcept;
  30705. /** Returns the amount of aftertouch from an aftertouch messages.
  30706. The value returned is in the range 0 to 127, and will be nonsense for messages
  30707. other than aftertouch messages.
  30708. @see isAftertouch
  30709. */
  30710. int getAfterTouchValue() const noexcept;
  30711. /** Creates an aftertouch message.
  30712. @param channel the midi channel, in the range 1 to 16
  30713. @param noteNumber the key number, 0 to 127
  30714. @param aftertouchAmount the amount of aftertouch, 0 to 127
  30715. @see isAftertouch
  30716. */
  30717. static MidiMessage aftertouchChange (int channel,
  30718. int noteNumber,
  30719. int aftertouchAmount) noexcept;
  30720. /** Returns true if the message is a channel-pressure change event.
  30721. This is like aftertouch, but common to the whole channel rather than a specific
  30722. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  30723. to find out the channel.
  30724. @see channelPressureChange
  30725. */
  30726. bool isChannelPressure() const noexcept;
  30727. /** Returns the pressure from a channel pressure change message.
  30728. @returns the pressure, in the range 0 to 127
  30729. @see isChannelPressure, channelPressureChange
  30730. */
  30731. int getChannelPressureValue() const noexcept;
  30732. /** Creates a channel-pressure change event.
  30733. @param channel the midi channel: 1 to 16
  30734. @param pressure the pressure, 0 to 127
  30735. @see isChannelPressure
  30736. */
  30737. static MidiMessage channelPressureChange (int channel, int pressure) noexcept;
  30738. /** Returns true if this is a midi controller message.
  30739. @see getControllerNumber, getControllerValue, controllerEvent
  30740. */
  30741. bool isController() const noexcept;
  30742. /** Returns the controller number of a controller message.
  30743. The name of the controller can be looked up using the getControllerName() method.
  30744. Note that the value returned is invalid for messages that aren't controller changes.
  30745. @see isController, getControllerName, getControllerValue
  30746. */
  30747. int getControllerNumber() const noexcept;
  30748. /** Returns the controller value from a controller message.
  30749. A value 0 to 127 is returned to indicate the new controller position.
  30750. Note that the value returned is invalid for messages that aren't controller changes.
  30751. @see isController, getControllerNumber
  30752. */
  30753. int getControllerValue() const noexcept;
  30754. /** Returns true if this message is a controller message and if it has the specified
  30755. controller type.
  30756. */
  30757. bool isControllerOfType (int controllerType) const noexcept;
  30758. /** Creates a controller message.
  30759. @param channel the midi channel, in the range 1 to 16
  30760. @param controllerType the type of controller
  30761. @param value the controller value
  30762. @see isController
  30763. */
  30764. static MidiMessage controllerEvent (int channel,
  30765. int controllerType,
  30766. int value) noexcept;
  30767. /** Checks whether this message is an all-notes-off message.
  30768. @see allNotesOff
  30769. */
  30770. bool isAllNotesOff() const noexcept;
  30771. /** Checks whether this message is an all-sound-off message.
  30772. @see allSoundOff
  30773. */
  30774. bool isAllSoundOff() const noexcept;
  30775. /** Creates an all-notes-off message.
  30776. @param channel the midi channel, in the range 1 to 16
  30777. @see isAllNotesOff
  30778. */
  30779. static MidiMessage allNotesOff (int channel) noexcept;
  30780. /** Creates an all-sound-off message.
  30781. @param channel the midi channel, in the range 1 to 16
  30782. @see isAllSoundOff
  30783. */
  30784. static MidiMessage allSoundOff (int channel) noexcept;
  30785. /** Creates an all-controllers-off message.
  30786. @param channel the midi channel, in the range 1 to 16
  30787. */
  30788. static MidiMessage allControllersOff (int channel) noexcept;
  30789. /** Returns true if this event is a meta-event.
  30790. Meta-events are things like tempo changes, track names, etc.
  30791. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  30792. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  30793. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  30794. */
  30795. bool isMetaEvent() const noexcept;
  30796. /** Returns a meta-event's type number.
  30797. If the message isn't a meta-event, this will return -1.
  30798. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  30799. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  30800. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  30801. */
  30802. int getMetaEventType() const noexcept;
  30803. /** Returns a pointer to the data in a meta-event.
  30804. @see isMetaEvent, getMetaEventLength
  30805. */
  30806. const uint8* getMetaEventData() const noexcept;
  30807. /** Returns the length of the data for a meta-event.
  30808. @see isMetaEvent, getMetaEventData
  30809. */
  30810. int getMetaEventLength() const noexcept;
  30811. /** Returns true if this is a 'track' meta-event. */
  30812. bool isTrackMetaEvent() const noexcept;
  30813. /** Returns true if this is an 'end-of-track' meta-event. */
  30814. bool isEndOfTrackMetaEvent() const noexcept;
  30815. /** Creates an end-of-track meta-event.
  30816. @see isEndOfTrackMetaEvent
  30817. */
  30818. static MidiMessage endOfTrack() noexcept;
  30819. /** Returns true if this is an 'track name' meta-event.
  30820. You can use the getTextFromTextMetaEvent() method to get the track's name.
  30821. */
  30822. bool isTrackNameEvent() const noexcept;
  30823. /** Returns true if this is a 'text' meta-event.
  30824. @see getTextFromTextMetaEvent
  30825. */
  30826. bool isTextMetaEvent() const noexcept;
  30827. /** Returns the text from a text meta-event.
  30828. @see isTextMetaEvent
  30829. */
  30830. String getTextFromTextMetaEvent() const;
  30831. /** Returns true if this is a 'tempo' meta-event.
  30832. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  30833. */
  30834. bool isTempoMetaEvent() const noexcept;
  30835. /** Returns the tick length from a tempo meta-event.
  30836. @param timeFormat the 16-bit time format value from the midi file's header.
  30837. @returns the tick length (in seconds).
  30838. @see isTempoMetaEvent
  30839. */
  30840. double getTempoMetaEventTickLength (short timeFormat) const noexcept;
  30841. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  30842. @see isTempoMetaEvent, getTempoMetaEventTickLength
  30843. */
  30844. double getTempoSecondsPerQuarterNote() const noexcept;
  30845. /** Creates a tempo meta-event.
  30846. @see isTempoMetaEvent
  30847. */
  30848. static MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) noexcept;
  30849. /** Returns true if this is a 'time-signature' meta-event.
  30850. @see getTimeSignatureInfo
  30851. */
  30852. bool isTimeSignatureMetaEvent() const noexcept;
  30853. /** Returns the time-signature values from a time-signature meta-event.
  30854. @see isTimeSignatureMetaEvent
  30855. */
  30856. void getTimeSignatureInfo (int& numerator, int& denominator) const noexcept;
  30857. /** Creates a time-signature meta-event.
  30858. @see isTimeSignatureMetaEvent
  30859. */
  30860. static MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  30861. /** Returns true if this is a 'key-signature' meta-event.
  30862. @see getKeySignatureNumberOfSharpsOrFlats
  30863. */
  30864. bool isKeySignatureMetaEvent() const noexcept;
  30865. /** Returns the key from a key-signature meta-event.
  30866. @see isKeySignatureMetaEvent
  30867. */
  30868. int getKeySignatureNumberOfSharpsOrFlats() const noexcept;
  30869. /** Returns true if this is a 'channel' meta-event.
  30870. A channel meta-event specifies the midi channel that should be used
  30871. for subsequent meta-events.
  30872. @see getMidiChannelMetaEventChannel
  30873. */
  30874. bool isMidiChannelMetaEvent() const noexcept;
  30875. /** Returns the channel number from a channel meta-event.
  30876. @returns the channel, in the range 1 to 16.
  30877. @see isMidiChannelMetaEvent
  30878. */
  30879. int getMidiChannelMetaEventChannel() const noexcept;
  30880. /** Creates a midi channel meta-event.
  30881. @param channel the midi channel, in the range 1 to 16
  30882. @see isMidiChannelMetaEvent
  30883. */
  30884. static MidiMessage midiChannelMetaEvent (int channel) noexcept;
  30885. /** Returns true if this is an active-sense message. */
  30886. bool isActiveSense() const noexcept;
  30887. /** Returns true if this is a midi start event.
  30888. @see midiStart
  30889. */
  30890. bool isMidiStart() const noexcept;
  30891. /** Creates a midi start event. */
  30892. static MidiMessage midiStart() noexcept;
  30893. /** Returns true if this is a midi continue event.
  30894. @see midiContinue
  30895. */
  30896. bool isMidiContinue() const noexcept;
  30897. /** Creates a midi continue event. */
  30898. static MidiMessage midiContinue() noexcept;
  30899. /** Returns true if this is a midi stop event.
  30900. @see midiStop
  30901. */
  30902. bool isMidiStop() const noexcept;
  30903. /** Creates a midi stop event. */
  30904. static MidiMessage midiStop() noexcept;
  30905. /** Returns true if this is a midi clock event.
  30906. @see midiClock, songPositionPointer
  30907. */
  30908. bool isMidiClock() const noexcept;
  30909. /** Creates a midi clock event. */
  30910. static MidiMessage midiClock() noexcept;
  30911. /** Returns true if this is a song-position-pointer message.
  30912. @see getSongPositionPointerMidiBeat, songPositionPointer
  30913. */
  30914. bool isSongPositionPointer() const noexcept;
  30915. /** Returns the midi beat-number of a song-position-pointer message.
  30916. @see isSongPositionPointer, songPositionPointer
  30917. */
  30918. int getSongPositionPointerMidiBeat() const noexcept;
  30919. /** Creates a song-position-pointer message.
  30920. The position is a number of midi beats from the start of the song, where 1 midi
  30921. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  30922. are 4 midi beats in a quarter-note.
  30923. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  30924. */
  30925. static MidiMessage songPositionPointer (int positionInMidiBeats) noexcept;
  30926. /** Returns true if this is a quarter-frame midi timecode message.
  30927. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  30928. */
  30929. bool isQuarterFrame() const noexcept;
  30930. /** Returns the sequence number of a quarter-frame midi timecode message.
  30931. This will be a value between 0 and 7.
  30932. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  30933. */
  30934. int getQuarterFrameSequenceNumber() const noexcept;
  30935. /** Returns the value from a quarter-frame message.
  30936. This will be the lower nybble of the message's data-byte, a value
  30937. between 0 and 15
  30938. */
  30939. int getQuarterFrameValue() const noexcept;
  30940. /** Creates a quarter-frame MTC message.
  30941. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  30942. @param value a value 0 to 15 for the lower nybble of the message's data byte
  30943. */
  30944. static MidiMessage quarterFrame (int sequenceNumber, int value) noexcept;
  30945. /** SMPTE timecode types.
  30946. Used by the getFullFrameParameters() and fullFrame() methods.
  30947. */
  30948. enum SmpteTimecodeType
  30949. {
  30950. fps24 = 0,
  30951. fps25 = 1,
  30952. fps30drop = 2,
  30953. fps30 = 3
  30954. };
  30955. /** Returns true if this is a full-frame midi timecode message.
  30956. */
  30957. bool isFullFrame() const noexcept;
  30958. /** Extracts the timecode information from a full-frame midi timecode message.
  30959. You should only call this on messages where you've used isFullFrame() to
  30960. check that they're the right kind.
  30961. */
  30962. void getFullFrameParameters (int& hours,
  30963. int& minutes,
  30964. int& seconds,
  30965. int& frames,
  30966. SmpteTimecodeType& timecodeType) const noexcept;
  30967. /** Creates a full-frame MTC message.
  30968. */
  30969. static MidiMessage fullFrame (int hours,
  30970. int minutes,
  30971. int seconds,
  30972. int frames,
  30973. SmpteTimecodeType timecodeType);
  30974. /** Types of MMC command.
  30975. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  30976. */
  30977. enum MidiMachineControlCommand
  30978. {
  30979. mmc_stop = 1,
  30980. mmc_play = 2,
  30981. mmc_deferredplay = 3,
  30982. mmc_fastforward = 4,
  30983. mmc_rewind = 5,
  30984. mmc_recordStart = 6,
  30985. mmc_recordStop = 7,
  30986. mmc_pause = 9
  30987. };
  30988. /** Checks whether this is an MMC message.
  30989. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  30990. */
  30991. bool isMidiMachineControlMessage() const noexcept;
  30992. /** For an MMC message, this returns its type.
  30993. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  30994. calling this method.
  30995. */
  30996. MidiMachineControlCommand getMidiMachineControlCommand() const noexcept;
  30997. /** Creates an MMC message.
  30998. */
  30999. static MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  31000. /** Checks whether this is an MMC "goto" message.
  31001. If it is, the parameters passed-in are set to the time that the message contains.
  31002. @see midiMachineControlGoto
  31003. */
  31004. bool isMidiMachineControlGoto (int& hours,
  31005. int& minutes,
  31006. int& seconds,
  31007. int& frames) const noexcept;
  31008. /** Creates an MMC "goto" message.
  31009. This messages tells the device to go to a specific frame.
  31010. @see isMidiMachineControlGoto
  31011. */
  31012. static MidiMessage midiMachineControlGoto (int hours,
  31013. int minutes,
  31014. int seconds,
  31015. int frames);
  31016. /** Creates a master-volume change message.
  31017. @param volume the volume, 0 to 1.0
  31018. */
  31019. static MidiMessage masterVolume (float volume);
  31020. /** Creates a system-exclusive message.
  31021. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  31022. */
  31023. static MidiMessage createSysExMessage (const uint8* sysexData,
  31024. int dataSize);
  31025. /** Reads a midi variable-length integer.
  31026. @param data the data to read the number from
  31027. @param numBytesUsed on return, this will be set to the number of bytes that were read
  31028. */
  31029. static int readVariableLengthVal (const uint8* data,
  31030. int& numBytesUsed) noexcept;
  31031. /** Based on the first byte of a short midi message, this uses a lookup table
  31032. to return the message length (either 1, 2, or 3 bytes).
  31033. The value passed in must be 0x80 or higher.
  31034. */
  31035. static int getMessageLengthFromFirstByte (const uint8 firstByte) noexcept;
  31036. /** Returns the name of a midi note number.
  31037. E.g "C", "D#", etc.
  31038. @param noteNumber the midi note number, 0 to 127
  31039. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  31040. they'll be flattened, e.g. "Db"
  31041. @param includeOctaveNumber if true, the octave number will be appended to the string,
  31042. e.g. "C#4"
  31043. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  31044. number that will be used for middle C's octave
  31045. @see getMidiNoteInHertz
  31046. */
  31047. static String getMidiNoteName (int noteNumber,
  31048. bool useSharps,
  31049. bool includeOctaveNumber,
  31050. int octaveNumForMiddleC);
  31051. /** Returns the frequency of a midi note number.
  31052. The frequencyOfA parameter is an optional frequency for 'A', normally 440-444Hz for concert pitch.
  31053. @see getMidiNoteName
  31054. */
  31055. static const double getMidiNoteInHertz (int noteNumber, const double frequencyOfA = 440.0) noexcept;
  31056. /** Returns the standard name of a GM instrument.
  31057. @param midiInstrumentNumber the program number 0 to 127
  31058. @see getProgramChangeNumber
  31059. */
  31060. static String getGMInstrumentName (int midiInstrumentNumber);
  31061. /** Returns the name of a bank of GM instruments.
  31062. @param midiBankNumber the bank, 0 to 15
  31063. */
  31064. static String getGMInstrumentBankName (int midiBankNumber);
  31065. /** Returns the standard name of a channel 10 percussion sound.
  31066. @param midiNoteNumber the key number, 35 to 81
  31067. */
  31068. static String getRhythmInstrumentName (int midiNoteNumber);
  31069. /** Returns the name of a controller type number.
  31070. @see getControllerNumber
  31071. */
  31072. static String getControllerName (int controllerNumber);
  31073. private:
  31074. double timeStamp;
  31075. uint8* data;
  31076. int size;
  31077. #ifndef DOXYGEN
  31078. union
  31079. {
  31080. uint8 asBytes[4];
  31081. uint32 asInt32;
  31082. } preallocatedData;
  31083. #endif
  31084. };
  31085. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  31086. /*** End of inlined file: juce_MidiMessage.h ***/
  31087. class MidiInput;
  31088. /**
  31089. Receives incoming messages from a physical MIDI input device.
  31090. This class is overridden to handle incoming midi messages. See the MidiInput
  31091. class for more details.
  31092. @see MidiInput
  31093. */
  31094. class JUCE_API MidiInputCallback
  31095. {
  31096. public:
  31097. /** Destructor. */
  31098. virtual ~MidiInputCallback() {}
  31099. /** Receives an incoming message.
  31100. A MidiInput object will call this method when a midi event arrives. It'll be
  31101. called on a high-priority system thread, so avoid doing anything time-consuming
  31102. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  31103. for queueing incoming messages for use later.
  31104. @param source the MidiInput object that generated the message
  31105. @param message the incoming message. The message's timestamp is set to a value
  31106. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  31107. time when the message arrived.
  31108. */
  31109. virtual void handleIncomingMidiMessage (MidiInput* source,
  31110. const MidiMessage& message) = 0;
  31111. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  31112. If a long sysex message is broken up into multiple packets, this callback is made
  31113. for each packet that arrives until the message is finished, at which point
  31114. the normal handleIncomingMidiMessage() callback will be made with the entire
  31115. message.
  31116. The message passed in will contain the start of a sysex, but won't be finished
  31117. with the terminating 0xf7 byte.
  31118. */
  31119. virtual void handlePartialSysexMessage (MidiInput* source,
  31120. const uint8* messageData,
  31121. const int numBytesSoFar,
  31122. const double timestamp)
  31123. {
  31124. // (this bit is just to avoid compiler warnings about unused variables)
  31125. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  31126. }
  31127. };
  31128. /**
  31129. Represents a midi input device.
  31130. To create one of these, use the static getDevices() method to find out what inputs are
  31131. available, and then use the openDevice() method to try to open one.
  31132. @see MidiOutput
  31133. */
  31134. class JUCE_API MidiInput
  31135. {
  31136. public:
  31137. /** Returns a list of the available midi input devices.
  31138. You can open one of the devices by passing its index into the
  31139. openDevice() method.
  31140. @see getDefaultDeviceIndex, openDevice
  31141. */
  31142. static StringArray getDevices();
  31143. /** Returns the index of the default midi input device to use.
  31144. This refers to the index in the list returned by getDevices().
  31145. */
  31146. static int getDefaultDeviceIndex();
  31147. /** Tries to open one of the midi input devices.
  31148. This will return a MidiInput object if it manages to open it. You can then
  31149. call start() and stop() on this device, and delete it when no longer needed.
  31150. If the device can't be opened, this will return a null pointer.
  31151. @param deviceIndex the index of a device from the list returned by getDevices()
  31152. @param callback the object that will receive the midi messages from this device.
  31153. @see MidiInputCallback, getDevices
  31154. */
  31155. static MidiInput* openDevice (int deviceIndex,
  31156. MidiInputCallback* callback);
  31157. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  31158. /** This will try to create a new midi input device (Not available on Windows).
  31159. This will attempt to create a new midi input device with the specified name,
  31160. for other apps to connect to.
  31161. Returns 0 if a device can't be created.
  31162. @param deviceName the name to use for the new device
  31163. @param callback the object that will receive the midi messages from this device.
  31164. */
  31165. static MidiInput* createNewDevice (const String& deviceName,
  31166. MidiInputCallback* callback);
  31167. #endif
  31168. /** Destructor. */
  31169. virtual ~MidiInput();
  31170. /** Returns the name of this device. */
  31171. const String& getName() const noexcept { return name; }
  31172. /** Allows you to set a custom name for the device, in case you don't like the name
  31173. it was given when created.
  31174. */
  31175. void setName (const String& newName) noexcept { name = newName; }
  31176. /** Starts the device running.
  31177. After calling this, the device will start sending midi messages to the
  31178. MidiInputCallback object that was specified when the openDevice() method
  31179. was called.
  31180. @see stop
  31181. */
  31182. virtual void start();
  31183. /** Stops the device running.
  31184. @see start
  31185. */
  31186. virtual void stop();
  31187. protected:
  31188. String name;
  31189. void* internal;
  31190. explicit MidiInput (const String& name);
  31191. private:
  31192. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInput);
  31193. };
  31194. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  31195. /*** End of inlined file: juce_MidiInput.h ***/
  31196. /*** Start of inlined file: juce_MidiOutput.h ***/
  31197. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  31198. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  31199. /*** Start of inlined file: juce_MidiBuffer.h ***/
  31200. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  31201. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  31202. /**
  31203. Holds a sequence of time-stamped midi events.
  31204. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  31205. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  31206. @see MidiMessage
  31207. */
  31208. class JUCE_API MidiBuffer
  31209. {
  31210. public:
  31211. /** Creates an empty MidiBuffer. */
  31212. MidiBuffer() noexcept;
  31213. /** Creates a MidiBuffer containing a single midi message. */
  31214. explicit MidiBuffer (const MidiMessage& message) noexcept;
  31215. /** Creates a copy of another MidiBuffer. */
  31216. MidiBuffer (const MidiBuffer& other) noexcept;
  31217. /** Makes a copy of another MidiBuffer. */
  31218. MidiBuffer& operator= (const MidiBuffer& other) noexcept;
  31219. /** Destructor */
  31220. ~MidiBuffer();
  31221. /** Removes all events from the buffer. */
  31222. void clear() noexcept;
  31223. /** Removes all events between two times from the buffer.
  31224. All events for which (start <= event position < start + numSamples) will
  31225. be removed.
  31226. */
  31227. void clear (int start, int numSamples);
  31228. /** Returns true if the buffer is empty.
  31229. To actually retrieve the events, use a MidiBuffer::Iterator object
  31230. */
  31231. bool isEmpty() const noexcept;
  31232. /** Counts the number of events in the buffer.
  31233. This is actually quite a slow operation, as it has to iterate through all
  31234. the events, so you might prefer to call isEmpty() if that's all you need
  31235. to know.
  31236. */
  31237. int getNumEvents() const noexcept;
  31238. /** Adds an event to the buffer.
  31239. The sample number will be used to determine the position of the event in
  31240. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  31241. ignored.
  31242. If an event is added whose sample position is the same as one or more events
  31243. already in the buffer, the new event will be placed after the existing ones.
  31244. To retrieve events, use a MidiBuffer::Iterator object
  31245. */
  31246. void addEvent (const MidiMessage& midiMessage, int sampleNumber);
  31247. /** Adds an event to the buffer from raw midi data.
  31248. The sample number will be used to determine the position of the event in
  31249. the buffer, which is always kept sorted.
  31250. If an event is added whose sample position is the same as one or more events
  31251. already in the buffer, the new event will be placed after the existing ones.
  31252. The event data will be inspected to calculate the number of bytes in length that
  31253. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  31254. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  31255. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  31256. add an event at all.
  31257. To retrieve events, use a MidiBuffer::Iterator object
  31258. */
  31259. void addEvent (const void* rawMidiData,
  31260. int maxBytesOfMidiData,
  31261. int sampleNumber);
  31262. /** Adds some events from another buffer to this one.
  31263. @param otherBuffer the buffer containing the events you want to add
  31264. @param startSample the lowest sample number in the source buffer for which
  31265. events should be added. Any source events whose timestamp is
  31266. less than this will be ignored
  31267. @param numSamples the valid range of samples from the source buffer for which
  31268. events should be added - i.e. events in the source buffer whose
  31269. timestamp is greater than or equal to (startSample + numSamples)
  31270. will be ignored. If this value is less than 0, all events after
  31271. startSample will be taken.
  31272. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  31273. that are added to this buffer
  31274. */
  31275. void addEvents (const MidiBuffer& otherBuffer,
  31276. int startSample,
  31277. int numSamples,
  31278. int sampleDeltaToAdd);
  31279. /** Returns the sample number of the first event in the buffer.
  31280. If the buffer's empty, this will just return 0.
  31281. */
  31282. int getFirstEventTime() const noexcept;
  31283. /** Returns the sample number of the last event in the buffer.
  31284. If the buffer's empty, this will just return 0.
  31285. */
  31286. int getLastEventTime() const noexcept;
  31287. /** Exchanges the contents of this buffer with another one.
  31288. This is a quick operation, because no memory allocating or copying is done, it
  31289. just swaps the internal state of the two buffers.
  31290. */
  31291. void swapWith (MidiBuffer& other) noexcept;
  31292. /** Preallocates some memory for the buffer to use.
  31293. This helps to avoid needing to reallocate space when the buffer has messages
  31294. added to it.
  31295. */
  31296. void ensureSize (size_t minimumNumBytes);
  31297. /**
  31298. Used to iterate through the events in a MidiBuffer.
  31299. Note that altering the buffer while an iterator is using it isn't a
  31300. safe operation.
  31301. @see MidiBuffer
  31302. */
  31303. class JUCE_API Iterator
  31304. {
  31305. public:
  31306. /** Creates an Iterator for this MidiBuffer. */
  31307. Iterator (const MidiBuffer& buffer) noexcept;
  31308. /** Destructor. */
  31309. ~Iterator() noexcept;
  31310. /** Repositions the iterator so that the next event retrieved will be the first
  31311. one whose sample position is at greater than or equal to the given position.
  31312. */
  31313. void setNextSamplePosition (int samplePosition) noexcept;
  31314. /** Retrieves a copy of the next event from the buffer.
  31315. @param result on return, this will be the message (the MidiMessage's timestamp
  31316. is not set)
  31317. @param samplePosition on return, this will be the position of the event
  31318. @returns true if an event was found, or false if the iterator has reached
  31319. the end of the buffer
  31320. */
  31321. bool getNextEvent (MidiMessage& result,
  31322. int& samplePosition) noexcept;
  31323. /** Retrieves the next event from the buffer.
  31324. @param midiData on return, this pointer will be set to a block of data containing
  31325. the midi message. Note that to make it fast, this is a pointer
  31326. directly into the MidiBuffer's internal data, so is only valid
  31327. temporarily until the MidiBuffer is altered.
  31328. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  31329. midi message
  31330. @param samplePosition on return, this will be the position of the event
  31331. @returns true if an event was found, or false if the iterator has reached
  31332. the end of the buffer
  31333. */
  31334. bool getNextEvent (const uint8* &midiData,
  31335. int& numBytesOfMidiData,
  31336. int& samplePosition) noexcept;
  31337. private:
  31338. const MidiBuffer& buffer;
  31339. const uint8* data;
  31340. JUCE_DECLARE_NON_COPYABLE (Iterator);
  31341. };
  31342. private:
  31343. friend class MidiBuffer::Iterator;
  31344. MemoryBlock data;
  31345. int bytesUsed;
  31346. uint8* getData() const noexcept;
  31347. uint8* findEventAfter (uint8* d, int samplePosition) const noexcept;
  31348. static int getEventTime (const void* d) noexcept;
  31349. static uint16 getEventDataSize (const void* d) noexcept;
  31350. static uint16 getEventTotalSize (const void* d) noexcept;
  31351. JUCE_LEAK_DETECTOR (MidiBuffer);
  31352. };
  31353. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  31354. /*** End of inlined file: juce_MidiBuffer.h ***/
  31355. /**
  31356. Controls a physical MIDI output device.
  31357. To create one of these, use the static getDevices() method to get a list of the
  31358. available output devices, then use the openDevice() method to try to open one.
  31359. @see MidiInput
  31360. */
  31361. class JUCE_API MidiOutput : private Thread
  31362. {
  31363. public:
  31364. /** Returns a list of the available midi output devices.
  31365. You can open one of the devices by passing its index into the
  31366. openDevice() method.
  31367. @see getDefaultDeviceIndex, openDevice
  31368. */
  31369. static StringArray getDevices();
  31370. /** Returns the index of the default midi output device to use.
  31371. This refers to the index in the list returned by getDevices().
  31372. */
  31373. static int getDefaultDeviceIndex();
  31374. /** Tries to open one of the midi output devices.
  31375. This will return a MidiOutput object if it manages to open it. You can then
  31376. send messages to this device, and delete it when no longer needed.
  31377. If the device can't be opened, this will return a null pointer.
  31378. @param deviceIndex the index of a device from the list returned by getDevices()
  31379. @see getDevices
  31380. */
  31381. static MidiOutput* openDevice (int deviceIndex);
  31382. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  31383. /** This will try to create a new midi output device (Not available on Windows).
  31384. This will attempt to create a new midi output device that other apps can connect
  31385. to and use as their midi input.
  31386. Returns 0 if a device can't be created.
  31387. @param deviceName the name to use for the new device
  31388. */
  31389. static MidiOutput* createNewDevice (const String& deviceName);
  31390. #endif
  31391. /** Destructor. */
  31392. virtual ~MidiOutput();
  31393. /** Makes this device output a midi message.
  31394. @see MidiMessage
  31395. */
  31396. virtual void sendMessageNow (const MidiMessage& message);
  31397. /** This lets you supply a block of messages that will be sent out at some point
  31398. in the future.
  31399. The MidiOutput class has an internal thread that can send out timestamped
  31400. messages - this appends a set of messages to its internal buffer, ready for
  31401. sending.
  31402. This will only work if you've already started the thread with startBackgroundThread().
  31403. A time is supplied, at which the block of messages should be sent. This time uses
  31404. the same time base as Time::getMillisecondCounter(), and must be in the future.
  31405. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  31406. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  31407. samplesPerSecondForBuffer value is needed to convert this sample position to a
  31408. real time.
  31409. */
  31410. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  31411. double millisecondCounterToStartAt,
  31412. double samplesPerSecondForBuffer);
  31413. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  31414. */
  31415. virtual void clearAllPendingMessages();
  31416. /** Starts up a background thread so that the device can send blocks of data.
  31417. Call this to get the device ready, before using sendBlockOfMessages().
  31418. */
  31419. virtual void startBackgroundThread();
  31420. /** Stops the background thread, and clears any pending midi events.
  31421. @see startBackgroundThread
  31422. */
  31423. virtual void stopBackgroundThread();
  31424. protected:
  31425. void* internal;
  31426. CriticalSection lock;
  31427. struct PendingMessage;
  31428. PendingMessage* firstMessage;
  31429. MidiOutput();
  31430. void run();
  31431. private:
  31432. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutput);
  31433. };
  31434. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  31435. /*** End of inlined file: juce_MidiOutput.h ***/
  31436. /**
  31437. Manages the state of some audio and midi i/o devices.
  31438. This class keeps tracks of a currently-selected audio device, through
  31439. with which it continuously streams data from an audio callback, as well as
  31440. one or more midi inputs.
  31441. The idea is that your application will create one global instance of this object,
  31442. and let it take care of creating and deleting specific types of audio devices
  31443. internally. So when the device is changed, your callbacks will just keep running
  31444. without having to worry about this.
  31445. The manager can save and reload all of its device settings as XML, which
  31446. makes it very easy for you to save and reload the audio setup of your
  31447. application.
  31448. And to make it easy to let the user change its settings, there's a component
  31449. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  31450. device selection/sample-rate/latency controls.
  31451. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  31452. call addAudioCallback() to register your audio callback with it, and use that to process
  31453. your audio data.
  31454. The manager also acts as a handy hub for incoming midi messages, allowing a
  31455. listener to register for messages from either a specific midi device, or from whatever
  31456. the current default midi input device is. The listener then doesn't have to worry about
  31457. re-registering with different midi devices if they are changed or deleted.
  31458. And yet another neat trick is that amount of CPU time being used is measured and
  31459. available with the getCpuUsage() method.
  31460. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  31461. listeners whenever one of its settings is changed.
  31462. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  31463. */
  31464. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  31465. {
  31466. public:
  31467. /** Creates a default AudioDeviceManager.
  31468. Initially no audio device will be selected. You should call the initialise() method
  31469. and register an audio callback with setAudioCallback() before it'll be able to
  31470. actually make any noise.
  31471. */
  31472. AudioDeviceManager();
  31473. /** Destructor. */
  31474. ~AudioDeviceManager();
  31475. /**
  31476. This structure holds a set of properties describing the current audio setup.
  31477. An AudioDeviceManager uses this class to save/load its current settings, and to
  31478. specify your preferred options when opening a device.
  31479. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  31480. */
  31481. struct JUCE_API AudioDeviceSetup
  31482. {
  31483. /** Creates an AudioDeviceSetup object.
  31484. The default constructor sets all the member variables to indicate default values.
  31485. You can then fill-in any values you want to before passing the object to
  31486. AudioDeviceManager::initialise().
  31487. */
  31488. AudioDeviceSetup();
  31489. bool operator== (const AudioDeviceSetup& other) const;
  31490. /** The name of the audio device used for output.
  31491. The name has to be one of the ones listed by the AudioDeviceManager's currently
  31492. selected device type.
  31493. This may be the same as the input device.
  31494. An empty string indicates the default device.
  31495. */
  31496. String outputDeviceName;
  31497. /** The name of the audio device used for input.
  31498. This may be the same as the output device.
  31499. An empty string indicates the default device.
  31500. */
  31501. String inputDeviceName;
  31502. /** The current sample rate.
  31503. This rate is used for both the input and output devices.
  31504. A value of 0 indicates the default rate.
  31505. */
  31506. double sampleRate;
  31507. /** The buffer size, in samples.
  31508. This buffer size is used for both the input and output devices.
  31509. A value of 0 indicates the default buffer size.
  31510. */
  31511. int bufferSize;
  31512. /** The set of active input channels.
  31513. The bits that are set in this array indicate the channels of the
  31514. input device that are active.
  31515. If useDefaultInputChannels is true, this value is ignored.
  31516. */
  31517. BigInteger inputChannels;
  31518. /** If this is true, it indicates that the inputChannels array
  31519. should be ignored, and instead, the device's default channels
  31520. should be used.
  31521. */
  31522. bool useDefaultInputChannels;
  31523. /** The set of active output channels.
  31524. The bits that are set in this array indicate the channels of the
  31525. input device that are active.
  31526. If useDefaultOutputChannels is true, this value is ignored.
  31527. */
  31528. BigInteger outputChannels;
  31529. /** If this is true, it indicates that the outputChannels array
  31530. should be ignored, and instead, the device's default channels
  31531. should be used.
  31532. */
  31533. bool useDefaultOutputChannels;
  31534. };
  31535. /** Opens a set of audio devices ready for use.
  31536. This will attempt to open either a default audio device, or one that was
  31537. previously saved as XML.
  31538. @param numInputChannelsNeeded a minimum number of input channels needed
  31539. by your app.
  31540. @param numOutputChannelsNeeded a minimum number of output channels to open
  31541. @param savedState either a previously-saved state that was produced
  31542. by createStateXml(), or 0 if you want the manager
  31543. to choose the best device to open.
  31544. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  31545. fails to open, then a default device will be used
  31546. instead. If false, then on failure, no device is
  31547. opened.
  31548. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  31549. name, then that will be used as the default device
  31550. (assuming that there wasn't one specified in the XML).
  31551. The string can actually be a simple wildcard, containing "*"
  31552. and "?" characters
  31553. @param preferredSetupOptions if this is non-null, the structure will be used as the
  31554. set of preferred settings when opening the device. If you
  31555. use this parameter, the preferredDefaultDeviceName
  31556. field will be ignored
  31557. @returns an error message if anything went wrong, or an empty string if it worked ok.
  31558. */
  31559. String initialise (int numInputChannelsNeeded,
  31560. int numOutputChannelsNeeded,
  31561. const XmlElement* savedState,
  31562. bool selectDefaultDeviceOnFailure,
  31563. const String& preferredDefaultDeviceName = String::empty,
  31564. const AudioDeviceSetup* preferredSetupOptions = 0);
  31565. /** Returns some XML representing the current state of the manager.
  31566. This stores the current device, its samplerate, block size, etc, and
  31567. can be restored later with initialise().
  31568. Note that this can return a null pointer if no settings have been explicitly changed
  31569. (i.e. if the device manager has just been left in its default state).
  31570. */
  31571. XmlElement* createStateXml() const;
  31572. /** Returns the current device properties that are in use.
  31573. @see setAudioDeviceSetup
  31574. */
  31575. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  31576. /** Changes the current device or its settings.
  31577. If you want to change a device property, like the current sample rate or
  31578. block size, you can call getAudioDeviceSetup() to retrieve the current
  31579. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  31580. and pass it back into this method to apply the new settings.
  31581. @param newSetup the settings that you'd like to use
  31582. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  31583. settings will be taken as having been explicitly chosen by the
  31584. user, and the next time createStateXml() is called, these settings
  31585. will be returned. If it's false, then the device is treated as a
  31586. temporary or default device, and a call to createStateXml() will
  31587. return either the last settings that were made with treatAsChosenDevice
  31588. as true, or the last XML settings that were passed into initialise().
  31589. @returns an error message if anything went wrong, or an empty string if it worked ok.
  31590. @see getAudioDeviceSetup
  31591. */
  31592. String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  31593. bool treatAsChosenDevice);
  31594. /** Returns the currently-active audio device. */
  31595. AudioIODevice* getCurrentAudioDevice() const noexcept { return currentAudioDevice; }
  31596. /** Returns the type of audio device currently in use.
  31597. @see setCurrentAudioDeviceType
  31598. */
  31599. String getCurrentAudioDeviceType() const { return currentDeviceType; }
  31600. /** Returns the currently active audio device type object.
  31601. Don't keep a copy of this pointer - it's owned by the device manager and could
  31602. change at any time.
  31603. */
  31604. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  31605. /** Changes the class of audio device being used.
  31606. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  31607. this because there's only one type: CoreAudio.
  31608. For a list of types, see getAvailableDeviceTypes().
  31609. */
  31610. void setCurrentAudioDeviceType (const String& type,
  31611. bool treatAsChosenDevice);
  31612. /** Closes the currently-open device.
  31613. You can call restartLastAudioDevice() later to reopen it in the same state
  31614. that it was just in.
  31615. */
  31616. void closeAudioDevice();
  31617. /** Tries to reload the last audio device that was running.
  31618. Note that this only reloads the last device that was running before
  31619. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  31620. and can only be called after a device has been opened with SetAudioDevice().
  31621. If a device is already open, this call will do nothing.
  31622. */
  31623. void restartLastAudioDevice();
  31624. /** Registers an audio callback to be used.
  31625. The manager will redirect callbacks from whatever audio device is currently
  31626. in use to all registered callback objects. If more than one callback is
  31627. active, they will all be given the same input data, and their outputs will
  31628. be summed.
  31629. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  31630. object before returning.
  31631. To remove a callback, use removeAudioCallback().
  31632. */
  31633. void addAudioCallback (AudioIODeviceCallback* newCallback);
  31634. /** Deregisters a previously added callback.
  31635. If necessary, this method will invoke audioDeviceStopped() on the callback
  31636. object before returning.
  31637. @see addAudioCallback
  31638. */
  31639. void removeAudioCallback (AudioIODeviceCallback* callback);
  31640. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  31641. Returns a value between 0 and 1.0
  31642. */
  31643. double getCpuUsage() const;
  31644. /** Enables or disables a midi input device.
  31645. The list of devices can be obtained with the MidiInput::getDevices() method.
  31646. Any incoming messages from enabled input devices will be forwarded on to all the
  31647. listeners that have been registered with the addMidiInputCallback() method. They
  31648. can either register for messages from a particular device, or from just the
  31649. "default" midi input.
  31650. Routing the midi input via an AudioDeviceManager means that when a listener
  31651. registers for the default midi input, this default device can be changed by the
  31652. manager without the listeners having to know about it or re-register.
  31653. It also means that a listener can stay registered for a midi input that is disabled
  31654. or not present, so that when the input is re-enabled, the listener will start
  31655. receiving messages again.
  31656. @see addMidiInputCallback, isMidiInputEnabled
  31657. */
  31658. void setMidiInputEnabled (const String& midiInputDeviceName, bool enabled);
  31659. /** Returns true if a given midi input device is being used.
  31660. @see setMidiInputEnabled
  31661. */
  31662. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  31663. /** Registers a listener for callbacks when midi events arrive from a midi input.
  31664. The device name can be empty to indicate that it wants events from whatever the
  31665. current "default" device is. Or it can be the name of one of the midi input devices
  31666. (see MidiInput::getDevices() for the names).
  31667. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  31668. events forwarded on to listeners.
  31669. */
  31670. void addMidiInputCallback (const String& midiInputDeviceName,
  31671. MidiInputCallback* callback);
  31672. /** Removes a listener that was previously registered with addMidiInputCallback().
  31673. */
  31674. void removeMidiInputCallback (const String& midiInputDeviceName,
  31675. MidiInputCallback* callback);
  31676. /** Sets a midi output device to use as the default.
  31677. The list of devices can be obtained with the MidiOutput::getDevices() method.
  31678. The specified device will be opened automatically and can be retrieved with the
  31679. getDefaultMidiOutput() method.
  31680. Pass in an empty string to deselect all devices. For the default device, you
  31681. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  31682. @see getDefaultMidiOutput, getDefaultMidiOutputName
  31683. */
  31684. void setDefaultMidiOutput (const String& deviceName);
  31685. /** Returns the name of the default midi output.
  31686. @see setDefaultMidiOutput, getDefaultMidiOutput
  31687. */
  31688. String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  31689. /** Returns the current default midi output device.
  31690. If no device has been selected, or the device can't be opened, this will
  31691. return 0.
  31692. @see getDefaultMidiOutputName
  31693. */
  31694. MidiOutput* getDefaultMidiOutput() const noexcept { return defaultMidiOutput; }
  31695. /** Returns a list of the types of device supported.
  31696. */
  31697. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  31698. /** Creates a list of available types.
  31699. This will add a set of new AudioIODeviceType objects to the specified list, to
  31700. represent each available types of device.
  31701. You can override this if your app needs to do something specific, like avoid
  31702. using DirectSound devices, etc.
  31703. */
  31704. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  31705. /** Plays a beep through the current audio device.
  31706. This is here to allow the audio setup UI panels to easily include a "test"
  31707. button so that the user can check where the audio is coming from.
  31708. */
  31709. void playTestSound();
  31710. /** Turns on level-measuring.
  31711. When enabled, the device manager will measure the peak input level
  31712. across all channels, and you can get this level by calling getCurrentInputLevel().
  31713. This is mainly intended for audio setup UI panels to use to create a mic
  31714. level display, so that the user can check that they've selected the right
  31715. device.
  31716. A simple filter is used to make the level decay smoothly, but this is
  31717. only intended for giving rough feedback, and not for any kind of accurate
  31718. measurement.
  31719. */
  31720. void enableInputLevelMeasurement (bool enableMeasurement);
  31721. /** Returns the current input level.
  31722. To use this, you must first enable it by calling enableInputLevelMeasurement().
  31723. See enableInputLevelMeasurement() for more info.
  31724. */
  31725. double getCurrentInputLevel() const;
  31726. /** Returns the a lock that can be used to synchronise access to the audio callback.
  31727. Obviously while this is locked, you're blocking the audio thread from running, so
  31728. it must only be used for very brief periods when absolutely necessary.
  31729. */
  31730. CriticalSection& getAudioCallbackLock() noexcept { return audioCallbackLock; }
  31731. /** Returns the a lock that can be used to synchronise access to the midi callback.
  31732. Obviously while this is locked, you're blocking the midi system from running, so
  31733. it must only be used for very brief periods when absolutely necessary.
  31734. */
  31735. CriticalSection& getMidiCallbackLock() noexcept { return midiCallbackLock; }
  31736. private:
  31737. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  31738. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  31739. AudioDeviceSetup currentSetup;
  31740. ScopedPointer <AudioIODevice> currentAudioDevice;
  31741. Array <AudioIODeviceCallback*> callbacks;
  31742. int numInputChansNeeded, numOutputChansNeeded;
  31743. String currentDeviceType;
  31744. BigInteger inputChannels, outputChannels;
  31745. ScopedPointer <XmlElement> lastExplicitSettings;
  31746. mutable bool listNeedsScanning;
  31747. bool useInputNames;
  31748. int inputLevelMeasurementEnabledCount;
  31749. double inputLevel;
  31750. ScopedPointer <AudioSampleBuffer> testSound;
  31751. int testSoundPosition;
  31752. AudioSampleBuffer tempBuffer;
  31753. StringArray midiInsFromXml;
  31754. OwnedArray <MidiInput> enabledMidiInputs;
  31755. Array <MidiInputCallback*> midiCallbacks;
  31756. StringArray midiCallbackDevices;
  31757. String defaultMidiOutputName;
  31758. ScopedPointer <MidiOutput> defaultMidiOutput;
  31759. CriticalSection audioCallbackLock, midiCallbackLock;
  31760. double cpuUsageMs, timeToCpuScale;
  31761. class CallbackHandler : public AudioIODeviceCallback,
  31762. public MidiInputCallback,
  31763. public AudioIODeviceType::Listener
  31764. {
  31765. public:
  31766. void audioDeviceIOCallback (const float**, int, float**, int, int);
  31767. void audioDeviceAboutToStart (AudioIODevice*);
  31768. void audioDeviceStopped();
  31769. void handleIncomingMidiMessage (MidiInput*, const MidiMessage&);
  31770. void audioDeviceListChanged();
  31771. AudioDeviceManager* owner;
  31772. };
  31773. CallbackHandler callbackHandler;
  31774. friend class CallbackHandler;
  31775. void audioDeviceIOCallbackInt (const float** inputChannelData, int totalNumInputChannels,
  31776. float** outputChannelData, int totalNumOutputChannels, int numSamples);
  31777. void audioDeviceAboutToStartInt (AudioIODevice*);
  31778. void audioDeviceStoppedInt();
  31779. void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
  31780. void audioDeviceListChanged();
  31781. String restartDevice (int blockSizeToUse, double sampleRateToUse,
  31782. const BigInteger& ins, const BigInteger& outs);
  31783. void stopDevice();
  31784. void updateXml();
  31785. void createDeviceTypesIfNeeded();
  31786. void scanDevicesIfNeeded();
  31787. void deleteCurrentDevice();
  31788. double chooseBestSampleRate (double preferred) const;
  31789. int chooseBestBufferSize (int preferred) const;
  31790. void insertDefaultDeviceNames (AudioDeviceSetup&) const;
  31791. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  31792. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager);
  31793. };
  31794. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  31795. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  31796. #endif
  31797. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  31798. #endif
  31799. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  31800. #endif
  31801. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  31802. #endif
  31803. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  31804. #endif
  31805. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  31806. /*** Start of inlined file: juce_Decibels.h ***/
  31807. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  31808. #define __JUCE_DECIBELS_JUCEHEADER__
  31809. /**
  31810. This class contains some helpful static methods for dealing with decibel values.
  31811. */
  31812. class Decibels
  31813. {
  31814. public:
  31815. /** Converts a dBFS value to its equivalent gain level.
  31816. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values. Any
  31817. decibel value lower than minusInfinityDb will return a gain of 0.
  31818. */
  31819. template <typename Type>
  31820. static Type decibelsToGain (const Type decibels,
  31821. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  31822. {
  31823. return decibels > minusInfinityDb ? powf ((Type) 10.0, decibels * (Type) 0.05)
  31824. : Type();
  31825. }
  31826. /** Converts a gain level into a dBFS value.
  31827. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values.
  31828. If the gain is 0 (or negative), then the method will return the value
  31829. provided as minusInfinityDb.
  31830. */
  31831. template <typename Type>
  31832. static Type gainToDecibels (const Type gain,
  31833. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  31834. {
  31835. return gain > Type() ? jmax (minusInfinityDb, (Type) std::log10 (gain) * (Type) 20.0)
  31836. : minusInfinityDb;
  31837. }
  31838. /** Converts a decibel reading to a string, with the 'dB' suffix.
  31839. If the decibel value is lower than minusInfinityDb, the return value will
  31840. be "-INF dB".
  31841. */
  31842. template <typename Type>
  31843. static String toString (const Type decibels,
  31844. const int decimalPlaces = 2,
  31845. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  31846. {
  31847. String s;
  31848. if (decibels <= minusInfinityDb)
  31849. {
  31850. s = "-INF dB";
  31851. }
  31852. else
  31853. {
  31854. if (decibels >= Type())
  31855. s << '+';
  31856. s << String (decibels, decimalPlaces) << " dB";
  31857. }
  31858. return s;
  31859. }
  31860. private:
  31861. enum
  31862. {
  31863. defaultMinusInfinitydB = -100
  31864. };
  31865. Decibels(); // This class can't be instantiated, it's just a holder for static methods..
  31866. JUCE_DECLARE_NON_COPYABLE (Decibels);
  31867. };
  31868. #endif // __JUCE_DECIBELS_JUCEHEADER__
  31869. /*** End of inlined file: juce_Decibels.h ***/
  31870. #endif
  31871. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  31872. #endif
  31873. #ifndef __JUCE_REVERB_JUCEHEADER__
  31874. #endif
  31875. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  31876. #endif
  31877. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  31878. /*** Start of inlined file: juce_MidiFile.h ***/
  31879. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  31880. #define __JUCE_MIDIFILE_JUCEHEADER__
  31881. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  31882. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  31883. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  31884. /**
  31885. A sequence of timestamped midi messages.
  31886. This allows the sequence to be manipulated, and also to be read from and
  31887. written to a standard midi file.
  31888. @see MidiMessage, MidiFile
  31889. */
  31890. class JUCE_API MidiMessageSequence
  31891. {
  31892. public:
  31893. /** Creates an empty midi sequence object. */
  31894. MidiMessageSequence();
  31895. /** Creates a copy of another sequence. */
  31896. MidiMessageSequence (const MidiMessageSequence& other);
  31897. /** Replaces this sequence with another one. */
  31898. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  31899. /** Destructor. */
  31900. ~MidiMessageSequence();
  31901. /** Structure used to hold midi events in the sequence.
  31902. These structures act as 'handles' on the events as they are moved about in
  31903. the list, and make it quick to find the matching note-offs for note-on events.
  31904. @see MidiMessageSequence::getEventPointer
  31905. */
  31906. class MidiEventHolder
  31907. {
  31908. public:
  31909. /** Destructor. */
  31910. ~MidiEventHolder();
  31911. /** The message itself, whose timestamp is used to specify the event's time.
  31912. */
  31913. MidiMessage message;
  31914. /** The matching note-off event (if this is a note-on event).
  31915. If this isn't a note-on, this pointer will be null.
  31916. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  31917. note-offs up-to-date after events have been moved around in the sequence
  31918. or deleted.
  31919. */
  31920. MidiEventHolder* noteOffObject;
  31921. private:
  31922. friend class MidiMessageSequence;
  31923. MidiEventHolder (const MidiMessage& message);
  31924. JUCE_LEAK_DETECTOR (MidiEventHolder);
  31925. };
  31926. /** Clears the sequence. */
  31927. void clear();
  31928. /** Returns the number of events in the sequence. */
  31929. int getNumEvents() const;
  31930. /** Returns a pointer to one of the events. */
  31931. MidiEventHolder* getEventPointer (int index) const;
  31932. /** Returns the time of the note-up that matches the note-on at this index.
  31933. If the event at this index isn't a note-on, it'll just return 0.
  31934. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  31935. */
  31936. double getTimeOfMatchingKeyUp (int index) const;
  31937. /** Returns the index of the note-up that matches the note-on at this index.
  31938. If the event at this index isn't a note-on, it'll just return -1.
  31939. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  31940. */
  31941. int getIndexOfMatchingKeyUp (int index) const;
  31942. /** Returns the index of an event. */
  31943. int getIndexOf (MidiEventHolder* event) const;
  31944. /** Returns the index of the first event on or after the given timestamp.
  31945. If the time is beyond the end of the sequence, this will return the
  31946. number of events.
  31947. */
  31948. int getNextIndexAtTime (double timeStamp) const;
  31949. /** Returns the timestamp of the first event in the sequence.
  31950. @see getEndTime
  31951. */
  31952. double getStartTime() const;
  31953. /** Returns the timestamp of the last event in the sequence.
  31954. @see getStartTime
  31955. */
  31956. double getEndTime() const;
  31957. /** Returns the timestamp of the event at a given index.
  31958. If the index is out-of-range, this will return 0.0
  31959. */
  31960. double getEventTime (int index) const;
  31961. /** Inserts a midi message into the sequence.
  31962. The index at which the new message gets inserted will depend on its timestamp,
  31963. because the sequence is kept sorted.
  31964. Remember to call updateMatchedPairs() after adding note-on events.
  31965. @param newMessage the new message to add (an internal copy will be made)
  31966. @param timeAdjustment an optional value to add to the timestamp of the message
  31967. that will be inserted
  31968. @see updateMatchedPairs
  31969. */
  31970. void addEvent (const MidiMessage& newMessage,
  31971. double timeAdjustment = 0);
  31972. /** Deletes one of the events in the sequence.
  31973. Remember to call updateMatchedPairs() after removing events.
  31974. @param index the index of the event to delete
  31975. @param deleteMatchingNoteUp whether to also remove the matching note-off
  31976. if the event you're removing is a note-on
  31977. */
  31978. void deleteEvent (int index, bool deleteMatchingNoteUp);
  31979. /** Merges another sequence into this one.
  31980. Remember to call updateMatchedPairs() after using this method.
  31981. @param other the sequence to add from
  31982. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  31983. as they are read from the other sequence
  31984. @param firstAllowableDestTime events will not be added if their time is earlier
  31985. than this time. (This is after their time has been adjusted
  31986. by the timeAdjustmentDelta)
  31987. @param endOfAllowableDestTimes events will not be added if their time is equal to
  31988. or greater than this time. (This is after their time has
  31989. been adjusted by the timeAdjustmentDelta)
  31990. */
  31991. void addSequence (const MidiMessageSequence& other,
  31992. double timeAdjustmentDelta,
  31993. double firstAllowableDestTime,
  31994. double endOfAllowableDestTimes);
  31995. /** Makes sure all the note-on and note-off pairs are up-to-date.
  31996. Call this after moving messages about or deleting/adding messages, and it
  31997. will scan the list and make sure all the note-offs in the MidiEventHolder
  31998. structures are pointing at the correct ones.
  31999. */
  32000. void updateMatchedPairs();
  32001. /** Copies all the messages for a particular midi channel to another sequence.
  32002. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  32003. @param destSequence the sequence that the chosen events should be copied to
  32004. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  32005. channel) will also be copied across.
  32006. @see extractSysExMessages
  32007. */
  32008. void extractMidiChannelMessages (int channelNumberToExtract,
  32009. MidiMessageSequence& destSequence,
  32010. bool alsoIncludeMetaEvents) const;
  32011. /** Copies all midi sys-ex messages to another sequence.
  32012. @param destSequence this is the sequence to which any sys-exes in this sequence
  32013. will be added
  32014. @see extractMidiChannelMessages
  32015. */
  32016. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  32017. /** Removes any messages in this sequence that have a specific midi channel.
  32018. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  32019. */
  32020. void deleteMidiChannelMessages (int channelNumberToRemove);
  32021. /** Removes any sys-ex messages from this sequence.
  32022. */
  32023. void deleteSysExMessages();
  32024. /** Adds an offset to the timestamps of all events in the sequence.
  32025. @param deltaTime the amount to add to each timestamp.
  32026. */
  32027. void addTimeToMessages (double deltaTime);
  32028. /** Scans through the sequence to determine the state of any midi controllers at
  32029. a given time.
  32030. This will create a sequence of midi controller changes that can be
  32031. used to set all midi controllers to the state they would be in at the
  32032. specified time within this sequence.
  32033. As well as controllers, it will also recreate the midi program number
  32034. and pitch bend position.
  32035. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  32036. for other channels will be ignored.
  32037. @param time the time at which you want to find out the state - there are
  32038. no explicit units for this time measurement, it's the same units
  32039. as used for the timestamps of the messages
  32040. @param resultMessages an array to which midi controller-change messages will be added. This
  32041. will be the minimum number of controller changes to recreate the
  32042. state at the required time.
  32043. */
  32044. void createControllerUpdatesForTime (int channelNumber, double time,
  32045. OwnedArray<MidiMessage>& resultMessages);
  32046. /** Swaps this sequence with another one. */
  32047. void swapWith (MidiMessageSequence& other) noexcept;
  32048. /** @internal */
  32049. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  32050. const MidiMessageSequence::MidiEventHolder* second) noexcept;
  32051. private:
  32052. friend class MidiFile;
  32053. OwnedArray <MidiEventHolder> list;
  32054. void sort();
  32055. JUCE_LEAK_DETECTOR (MidiMessageSequence);
  32056. };
  32057. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  32058. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  32059. /**
  32060. Reads/writes standard midi format files.
  32061. To read a midi file, create a MidiFile object and call its readFrom() method. You
  32062. can then get the individual midi tracks from it using the getTrack() method.
  32063. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  32064. to it using the addTrack() method, and then call its writeTo() method to stream
  32065. it out.
  32066. @see MidiMessageSequence
  32067. */
  32068. class JUCE_API MidiFile
  32069. {
  32070. public:
  32071. /** Creates an empty MidiFile object.
  32072. */
  32073. MidiFile();
  32074. /** Destructor. */
  32075. ~MidiFile();
  32076. /** Returns the number of tracks in the file.
  32077. @see getTrack, addTrack
  32078. */
  32079. int getNumTracks() const noexcept;
  32080. /** Returns a pointer to one of the tracks in the file.
  32081. @returns a pointer to the track, or 0 if the index is out-of-range
  32082. @see getNumTracks, addTrack
  32083. */
  32084. const MidiMessageSequence* getTrack (int index) const noexcept;
  32085. /** Adds a midi track to the file.
  32086. This will make its own internal copy of the sequence that is passed-in.
  32087. @see getNumTracks, getTrack
  32088. */
  32089. void addTrack (const MidiMessageSequence& trackSequence);
  32090. /** Removes all midi tracks from the file.
  32091. @see getNumTracks
  32092. */
  32093. void clear();
  32094. /** Returns the raw time format code that will be written to a stream.
  32095. After reading a midi file, this method will return the time-format that
  32096. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  32097. or setSmpteTimeFormat() methods.
  32098. If the value returned is positive, it indicates the number of midi ticks
  32099. per quarter-note - see setTicksPerQuarterNote().
  32100. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  32101. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  32102. */
  32103. short getTimeFormat() const noexcept;
  32104. /** Sets the time format to use when this file is written to a stream.
  32105. If this is called, the file will be written as bars/beats using the
  32106. specified resolution, rather than SMPTE absolute times, as would be
  32107. used if setSmpteTimeFormat() had been called instead.
  32108. @param ticksPerQuarterNote e.g. 96, 960
  32109. @see setSmpteTimeFormat
  32110. */
  32111. void setTicksPerQuarterNote (int ticksPerQuarterNote) noexcept;
  32112. /** Sets the time format to use when this file is written to a stream.
  32113. If this is called, the file will be written using absolute times, rather
  32114. than bars/beats as would be the case if setTicksPerBeat() had been called
  32115. instead.
  32116. @param framesPerSecond must be 24, 25, 29 or 30
  32117. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  32118. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  32119. timing, setSmpteTimeFormat (25, 40)
  32120. @see setTicksPerBeat
  32121. */
  32122. void setSmpteTimeFormat (int framesPerSecond,
  32123. int subframeResolution) noexcept;
  32124. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  32125. Useful for finding the positions of all the tempo changes in a file.
  32126. @param tempoChangeEvents a list to which all the events will be added
  32127. */
  32128. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  32129. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  32130. Useful for finding the positions of all the tempo changes in a file.
  32131. @param timeSigEvents a list to which all the events will be added
  32132. */
  32133. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  32134. /** Returns the latest timestamp in any of the tracks.
  32135. (Useful for finding the length of the file).
  32136. */
  32137. double getLastTimestamp() const;
  32138. /** Reads a midi file format stream.
  32139. After calling this, you can get the tracks that were read from the file by using the
  32140. getNumTracks() and getTrack() methods.
  32141. The timestamps of the midi events in the tracks will represent their positions in
  32142. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  32143. method.
  32144. @returns true if the stream was read successfully
  32145. */
  32146. bool readFrom (InputStream& sourceStream);
  32147. /** Writes the midi tracks as a standard midi file.
  32148. @returns true if the operation succeeded.
  32149. */
  32150. bool writeTo (OutputStream& destStream);
  32151. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  32152. This will use the midi time format and tempo/time signature info in the
  32153. tracks to convert all the timestamps to absolute values in seconds.
  32154. */
  32155. void convertTimestampTicksToSeconds();
  32156. private:
  32157. OwnedArray <MidiMessageSequence> tracks;
  32158. short timeFormat;
  32159. void readNextTrack (const uint8* data, int size);
  32160. void writeTrack (OutputStream& mainOut, int trackNum);
  32161. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiFile);
  32162. };
  32163. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  32164. /*** End of inlined file: juce_MidiFile.h ***/
  32165. #endif
  32166. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  32167. #endif
  32168. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32169. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  32170. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32171. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32172. class MidiKeyboardState;
  32173. /**
  32174. Receives events from a MidiKeyboardState object.
  32175. @see MidiKeyboardState
  32176. */
  32177. class JUCE_API MidiKeyboardStateListener
  32178. {
  32179. public:
  32180. MidiKeyboardStateListener() noexcept {}
  32181. virtual ~MidiKeyboardStateListener() {}
  32182. /** Called when one of the MidiKeyboardState's keys is pressed.
  32183. This will be called synchronously when the state is either processing a
  32184. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  32185. when a note is being played with its MidiKeyboardState::noteOn() method.
  32186. Note that this callback could happen from an audio callback thread, so be
  32187. careful not to block, and avoid any UI activity in the callback.
  32188. */
  32189. virtual void handleNoteOn (MidiKeyboardState* source,
  32190. int midiChannel, int midiNoteNumber, float velocity) = 0;
  32191. /** Called when one of the MidiKeyboardState's keys is released.
  32192. This will be called synchronously when the state is either processing a
  32193. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  32194. when a note is being played with its MidiKeyboardState::noteOff() method.
  32195. Note that this callback could happen from an audio callback thread, so be
  32196. careful not to block, and avoid any UI activity in the callback.
  32197. */
  32198. virtual void handleNoteOff (MidiKeyboardState* source,
  32199. int midiChannel, int midiNoteNumber) = 0;
  32200. };
  32201. /**
  32202. Represents a piano keyboard, keeping track of which keys are currently pressed.
  32203. This object can parse a stream of midi events, using them to update its idea
  32204. of which keys are pressed for each individiual midi channel.
  32205. When keys go up or down, it can broadcast these events to listener objects.
  32206. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  32207. methods, and midi messages for these events will be merged into the
  32208. midi stream that gets processed by processNextMidiBuffer().
  32209. */
  32210. class JUCE_API MidiKeyboardState
  32211. {
  32212. public:
  32213. MidiKeyboardState();
  32214. ~MidiKeyboardState();
  32215. /** Resets the state of the object.
  32216. All internal data for all the channels is reset, but no events are sent as a
  32217. result.
  32218. If you want to release any keys that are currently down, and to send out note-up
  32219. midi messages for this, use the allNotesOff() method instead.
  32220. */
  32221. void reset();
  32222. /** Returns true if the given midi key is currently held down for the given midi channel.
  32223. The channel number must be between 1 and 16. If you want to see if any notes are
  32224. on for a range of channels, use the isNoteOnForChannels() method.
  32225. */
  32226. bool isNoteOn (int midiChannel, int midiNoteNumber) const noexcept;
  32227. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  32228. The channel mask has a bit set for each midi channel you want to test for - bit
  32229. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  32230. If a note is on for at least one of the specified channels, this returns true.
  32231. */
  32232. bool isNoteOnForChannels (int midiChannelMask, int midiNoteNumber) const noexcept;
  32233. /** Turns a specified note on.
  32234. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  32235. next call to processNextMidiBuffer().
  32236. It will also trigger a synchronous callback to the listeners to tell them that the key has
  32237. gone down.
  32238. */
  32239. void noteOn (int midiChannel, int midiNoteNumber, float velocity);
  32240. /** Turns a specified note off.
  32241. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  32242. next call to processNextMidiBuffer().
  32243. It will also trigger a synchronous callback to the listeners to tell them that the key has
  32244. gone up.
  32245. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  32246. */
  32247. void noteOff (int midiChannel, int midiNoteNumber);
  32248. /** This will turn off any currently-down notes for the given midi channel.
  32249. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  32250. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  32251. and events being added to the midi stream.
  32252. */
  32253. void allNotesOff (int midiChannel);
  32254. /** Looks at a key-up/down event and uses it to update the state of this object.
  32255. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  32256. instead.
  32257. */
  32258. void processNextMidiEvent (const MidiMessage& message);
  32259. /** Scans a midi stream for up/down events and adds its own events to it.
  32260. This will look for any up/down events and use them to update the internal state,
  32261. synchronously making suitable callbacks to the listeners.
  32262. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  32263. and noteOff() calls will be added into the buffer.
  32264. Only the section of the buffer whose timestamps are between startSample and
  32265. (startSample + numSamples) will be affected, and any events added will be placed
  32266. between these times.
  32267. If you're going to use this method, you'll need to keep calling it regularly for
  32268. it to work satisfactorily.
  32269. To process a single midi event at a time, use the processNextMidiEvent() method
  32270. instead.
  32271. */
  32272. void processNextMidiBuffer (MidiBuffer& buffer,
  32273. int startSample,
  32274. int numSamples,
  32275. bool injectIndirectEvents);
  32276. /** Registers a listener for callbacks when keys go up or down.
  32277. @see removeListener
  32278. */
  32279. void addListener (MidiKeyboardStateListener* listener);
  32280. /** Deregisters a listener.
  32281. @see addListener
  32282. */
  32283. void removeListener (MidiKeyboardStateListener* listener);
  32284. private:
  32285. CriticalSection lock;
  32286. uint16 noteStates [128];
  32287. MidiBuffer eventsToAdd;
  32288. Array <MidiKeyboardStateListener*> listeners;
  32289. void noteOnInternal (int midiChannel, int midiNoteNumber, float velocity);
  32290. void noteOffInternal (int midiChannel, int midiNoteNumber);
  32291. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardState);
  32292. };
  32293. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32294. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  32295. #endif
  32296. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  32297. #endif
  32298. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32299. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  32300. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32301. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32302. /**
  32303. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  32304. processing by a block-based audio callback.
  32305. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  32306. so it can easily use a midi input or keyboard component as its source.
  32307. @see MidiMessage, MidiInput
  32308. */
  32309. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  32310. public MidiInputCallback
  32311. {
  32312. public:
  32313. /** Creates a MidiMessageCollector. */
  32314. MidiMessageCollector();
  32315. /** Destructor. */
  32316. ~MidiMessageCollector();
  32317. /** Clears any messages from the queue.
  32318. You need to call this method before starting to use the collector, so that
  32319. it knows the correct sample rate to use.
  32320. */
  32321. void reset (double sampleRate);
  32322. /** Takes an incoming real-time message and adds it to the queue.
  32323. The message's timestamp is taken, and it will be ready for retrieval as part
  32324. of the block returned by the next call to removeNextBlockOfMessages().
  32325. This method is fully thread-safe when overlapping calls are made with
  32326. removeNextBlockOfMessages().
  32327. */
  32328. void addMessageToQueue (const MidiMessage& message);
  32329. /** Removes all the pending messages from the queue as a buffer.
  32330. This will also correct the messages' timestamps to make sure they're in
  32331. the range 0 to numSamples - 1.
  32332. This call should be made regularly by something like an audio processing
  32333. callback, because the time that it happens is used in calculating the
  32334. midi event positions.
  32335. This method is fully thread-safe when overlapping calls are made with
  32336. addMessageToQueue().
  32337. */
  32338. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  32339. /** @internal */
  32340. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  32341. /** @internal */
  32342. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  32343. /** @internal */
  32344. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  32345. private:
  32346. double lastCallbackTime;
  32347. CriticalSection midiCallbackLock;
  32348. MidiBuffer incomingMessages;
  32349. double sampleRate;
  32350. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiMessageCollector);
  32351. };
  32352. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32353. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  32354. #endif
  32355. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  32356. #endif
  32357. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  32358. #endif
  32359. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  32360. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  32361. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  32362. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  32363. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  32364. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  32365. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  32366. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  32367. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  32368. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  32369. /*** Start of inlined file: juce_AudioProcessor.h ***/
  32370. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  32371. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  32372. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  32373. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  32374. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  32375. class AudioProcessor;
  32376. /**
  32377. Base class for the component that acts as the GUI for an AudioProcessor.
  32378. Derive your editor component from this class, and create an instance of it
  32379. by overriding the AudioProcessor::createEditor() method.
  32380. @see AudioProcessor, GenericAudioProcessorEditor
  32381. */
  32382. class JUCE_API AudioProcessorEditor : public Component
  32383. {
  32384. protected:
  32385. /** Creates an editor for the specified processor.
  32386. */
  32387. AudioProcessorEditor (AudioProcessor* owner);
  32388. public:
  32389. /** Destructor. */
  32390. ~AudioProcessorEditor();
  32391. /** Returns a pointer to the processor that this editor represents. */
  32392. AudioProcessor* getAudioProcessor() const noexcept { return owner; }
  32393. private:
  32394. AudioProcessor* const owner;
  32395. JUCE_DECLARE_NON_COPYABLE (AudioProcessorEditor);
  32396. };
  32397. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  32398. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  32399. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  32400. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  32401. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  32402. class AudioProcessor;
  32403. /**
  32404. Base class for listeners that want to know about changes to an AudioProcessor.
  32405. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  32406. @see AudioProcessor
  32407. */
  32408. class JUCE_API AudioProcessorListener
  32409. {
  32410. public:
  32411. /** Destructor. */
  32412. virtual ~AudioProcessorListener() {}
  32413. /** Receives a callback when a parameter is changed.
  32414. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  32415. many audio processors will change their parameter during their audio callback.
  32416. This means that not only has your handler code got to be completely thread-safe,
  32417. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  32418. this event on your message thread, use this callback to trigger an AsyncUpdater
  32419. or ChangeBroadcaster which you can respond to on the message thread.
  32420. */
  32421. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  32422. int parameterIndex,
  32423. float newValue) = 0;
  32424. /** Called to indicate that something else in the plugin has changed, like its
  32425. program, number of parameters, etc.
  32426. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  32427. call it during their audio callback. This means that not only has your handler code
  32428. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  32429. blocking. If you need to handle this event on your message thread, use this callback
  32430. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  32431. message thread.
  32432. */
  32433. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  32434. /** Indicates that a parameter change gesture has started.
  32435. E.g. if the user is dragging a slider, this would be called when they first
  32436. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  32437. called when they release it.
  32438. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  32439. call it during their audio callback. This means that not only has your handler code
  32440. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  32441. blocking. If you need to handle this event on your message thread, use this callback
  32442. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  32443. message thread.
  32444. @see audioProcessorParameterChangeGestureEnd
  32445. */
  32446. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  32447. int parameterIndex);
  32448. /** Indicates that a parameter change gesture has finished.
  32449. E.g. if the user is dragging a slider, this would be called when they release
  32450. the mouse button.
  32451. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  32452. call it during their audio callback. This means that not only has your handler code
  32453. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  32454. blocking. If you need to handle this event on your message thread, use this callback
  32455. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  32456. message thread.
  32457. @see audioProcessorParameterChangeGestureBegin
  32458. */
  32459. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  32460. int parameterIndex);
  32461. };
  32462. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  32463. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  32464. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  32465. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  32466. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  32467. /**
  32468. A subclass of AudioPlayHead can supply information about the position and
  32469. status of a moving play head during audio playback.
  32470. One of these can be supplied to an AudioProcessor object so that it can find
  32471. out about the position of the audio that it is rendering.
  32472. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  32473. */
  32474. class JUCE_API AudioPlayHead
  32475. {
  32476. protected:
  32477. AudioPlayHead() {}
  32478. public:
  32479. virtual ~AudioPlayHead() {}
  32480. /** Frame rate types. */
  32481. enum FrameRateType
  32482. {
  32483. fps24 = 0,
  32484. fps25 = 1,
  32485. fps2997 = 2,
  32486. fps30 = 3,
  32487. fps2997drop = 4,
  32488. fps30drop = 5,
  32489. fpsUnknown = 99
  32490. };
  32491. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  32492. */
  32493. struct CurrentPositionInfo
  32494. {
  32495. /** The tempo in BPM */
  32496. double bpm;
  32497. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  32498. int timeSigNumerator;
  32499. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  32500. int timeSigDenominator;
  32501. /** The current play position, in seconds from the start of the edit. */
  32502. double timeInSeconds;
  32503. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  32504. double editOriginTime;
  32505. /** The current play position in pulses-per-quarter-note.
  32506. This is the number of quarter notes since the edit start.
  32507. */
  32508. double ppqPosition;
  32509. /** The position of the start of the last bar, in pulses-per-quarter-note.
  32510. This is the number of quarter notes from the start of the edit to the
  32511. start of the current bar.
  32512. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  32513. it's not available, the value will be 0.
  32514. */
  32515. double ppqPositionOfLastBarStart;
  32516. /** The video frame rate, if applicable. */
  32517. FrameRateType frameRate;
  32518. /** True if the transport is currently playing. */
  32519. bool isPlaying;
  32520. /** True if the transport is currently recording.
  32521. (When isRecording is true, then isPlaying will also be true).
  32522. */
  32523. bool isRecording;
  32524. bool operator== (const CurrentPositionInfo& other) const noexcept;
  32525. bool operator!= (const CurrentPositionInfo& other) const noexcept;
  32526. void resetToDefault();
  32527. };
  32528. /** Fills-in the given structure with details about the transport's
  32529. position at the start of the current processing block.
  32530. */
  32531. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  32532. };
  32533. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  32534. /*** End of inlined file: juce_AudioPlayHead.h ***/
  32535. /**
  32536. Base class for audio processing filters or plugins.
  32537. This is intended to act as a base class of audio filter that is general enough to
  32538. be wrapped as a VST, AU, RTAS, etc, or used internally.
  32539. It is also used by the plugin hosting code as the wrapper around an instance
  32540. of a loaded plugin.
  32541. Derive your filter class from this base class, and if you're building a plugin,
  32542. you should implement a global function called createPluginFilter() which creates
  32543. and returns a new instance of your subclass.
  32544. */
  32545. class JUCE_API AudioProcessor
  32546. {
  32547. protected:
  32548. /** Constructor.
  32549. You can also do your initialisation tasks in the initialiseFilterInfo()
  32550. call, which will be made after this object has been created.
  32551. */
  32552. AudioProcessor();
  32553. public:
  32554. /** Destructor. */
  32555. virtual ~AudioProcessor();
  32556. /** Returns the name of this processor.
  32557. */
  32558. virtual const String getName() const = 0;
  32559. /** Called before playback starts, to let the filter prepare itself.
  32560. The sample rate is the target sample rate, and will remain constant until
  32561. playback stops.
  32562. The estimatedSamplesPerBlock value is a HINT about the typical number of
  32563. samples that will be processed for each callback, but isn't any kind
  32564. of guarantee. The actual block sizes that the host uses may be different
  32565. each time the callback happens, and may be more or less than this value.
  32566. */
  32567. virtual void prepareToPlay (double sampleRate,
  32568. int estimatedSamplesPerBlock) = 0;
  32569. /** Called after playback has stopped, to let the filter free up any resources it
  32570. no longer needs.
  32571. */
  32572. virtual void releaseResources() = 0;
  32573. /** Renders the next block.
  32574. When this method is called, the buffer contains a number of channels which is
  32575. at least as great as the maximum number of input and output channels that
  32576. this filter is using. It will be filled with the filter's input data and
  32577. should be replaced with the filter's output.
  32578. So for example if your filter has 2 input channels and 4 output channels, then
  32579. the buffer will contain 4 channels, the first two being filled with the
  32580. input data. Your filter should read these, do its processing, and replace
  32581. the contents of all 4 channels with its output.
  32582. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  32583. all filled with data, and your filter should overwrite the first 2 of these
  32584. with its output. But be VERY careful not to write anything to the last 3
  32585. channels, as these might be mapped to memory that the host assumes is read-only!
  32586. Note that if you have more outputs than inputs, then only those channels that
  32587. correspond to an input channel are guaranteed to contain sensible data - e.g.
  32588. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  32589. but the last two channels may contain garbage, so you should be careful not to
  32590. let this pass through without being overwritten or cleared.
  32591. Also note that the buffer may have more channels than are strictly necessary,
  32592. but your should only read/write from the ones that your filter is supposed to
  32593. be using.
  32594. The number of samples in these buffers is NOT guaranteed to be the same for every
  32595. callback, and may be more or less than the estimated value given to prepareToPlay().
  32596. Your code must be able to cope with variable-sized blocks, or you're going to get
  32597. clicks and crashes!
  32598. If the filter is receiving a midi input, then the midiMessages array will be filled
  32599. with the midi messages for this block. Each message's timestamp will indicate the
  32600. message's time, as a number of samples from the start of the block.
  32601. Any messages left in the midi buffer when this method has finished are assumed to
  32602. be the filter's midi output. This means that your filter should be careful to
  32603. clear any incoming messages from the array if it doesn't want them to be passed-on.
  32604. Be very careful about what you do in this callback - it's going to be called by
  32605. the audio thread, so any kind of interaction with the UI is absolutely
  32606. out of the question. If you change a parameter in here and need to tell your UI to
  32607. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  32608. the UI components register as listeners, and then call sendChangeMessage() inside the
  32609. processBlock() method to send out an asynchronous message. You could also use
  32610. the AsyncUpdater class in a similar way.
  32611. */
  32612. virtual void processBlock (AudioSampleBuffer& buffer,
  32613. MidiBuffer& midiMessages) = 0;
  32614. /** Returns the current AudioPlayHead object that should be used to find
  32615. out the state and position of the playhead.
  32616. You can call this from your processBlock() method, and use the AudioPlayHead
  32617. object to get the details about the time of the start of the block currently
  32618. being processed.
  32619. If the host hasn't supplied a playhead object, this will return 0.
  32620. */
  32621. AudioPlayHead* getPlayHead() const noexcept { return playHead; }
  32622. /** Returns the current sample rate.
  32623. This can be called from your processBlock() method - it's not guaranteed
  32624. to be valid at any other time, and may return 0 if it's unknown.
  32625. */
  32626. double getSampleRate() const noexcept { return sampleRate; }
  32627. /** Returns the current typical block size that is being used.
  32628. This can be called from your processBlock() method - it's not guaranteed
  32629. to be valid at any other time.
  32630. Remember it's not the ONLY block size that may be used when calling
  32631. processBlock, it's just the normal one. The actual block sizes used may be
  32632. larger or smaller than this, and will vary between successive calls.
  32633. */
  32634. int getBlockSize() const noexcept { return blockSize; }
  32635. /** Returns the number of input channels that the host will be sending the filter.
  32636. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  32637. number of channels that your filter would prefer to have, and this method lets
  32638. you know how many the host is actually using.
  32639. Note that this method is only valid during or after the prepareToPlay()
  32640. method call. Until that point, the number of channels will be unknown.
  32641. */
  32642. int getNumInputChannels() const noexcept { return numInputChannels; }
  32643. /** Returns the number of output channels that the host will be sending the filter.
  32644. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  32645. number of channels that your filter would prefer to have, and this method lets
  32646. you know how many the host is actually using.
  32647. Note that this method is only valid during or after the prepareToPlay()
  32648. method call. Until that point, the number of channels will be unknown.
  32649. */
  32650. int getNumOutputChannels() const noexcept { return numOutputChannels; }
  32651. /** Returns the name of one of the input channels, as returned by the host.
  32652. The host might not supply very useful names for channels, and this might be
  32653. something like "1", "2", "left", "right", etc.
  32654. */
  32655. virtual const String getInputChannelName (int channelIndex) const = 0;
  32656. /** Returns the name of one of the output channels, as returned by the host.
  32657. The host might not supply very useful names for channels, and this might be
  32658. something like "1", "2", "left", "right", etc.
  32659. */
  32660. virtual const String getOutputChannelName (int channelIndex) const = 0;
  32661. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  32662. virtual bool isInputChannelStereoPair (int index) const = 0;
  32663. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  32664. virtual bool isOutputChannelStereoPair (int index) const = 0;
  32665. /** This returns the number of samples delay that the filter imposes on the audio
  32666. passing through it.
  32667. The host will call this to find the latency - the filter itself should set this value
  32668. by calling setLatencySamples() as soon as it can during its initialisation.
  32669. */
  32670. int getLatencySamples() const noexcept { return latencySamples; }
  32671. /** The filter should call this to set the number of samples delay that it introduces.
  32672. The filter should call this as soon as it can during initialisation, and can call it
  32673. later if the value changes.
  32674. */
  32675. void setLatencySamples (int newLatency);
  32676. /** Returns true if the processor wants midi messages. */
  32677. virtual bool acceptsMidi() const = 0;
  32678. /** Returns true if the processor produces midi messages. */
  32679. virtual bool producesMidi() const = 0;
  32680. /** This returns a critical section that will automatically be locked while the host
  32681. is calling the processBlock() method.
  32682. Use it from your UI or other threads to lock access to variables that are used
  32683. by the process callback, but obviously be careful not to keep it locked for
  32684. too long, because that could cause stuttering playback. If you need to do something
  32685. that'll take a long time and need the processing to stop while it happens, use the
  32686. suspendProcessing() method instead.
  32687. @see suspendProcessing
  32688. */
  32689. const CriticalSection& getCallbackLock() const noexcept { return callbackLock; }
  32690. /** Enables and disables the processing callback.
  32691. If you need to do something time-consuming on a thread and would like to make sure
  32692. the audio processing callback doesn't happen until you've finished, use this
  32693. to disable the callback and re-enable it again afterwards.
  32694. E.g.
  32695. @code
  32696. void loadNewPatch()
  32697. {
  32698. suspendProcessing (true);
  32699. ..do something that takes ages..
  32700. suspendProcessing (false);
  32701. }
  32702. @endcode
  32703. If the host tries to make an audio callback while processing is suspended, the
  32704. filter will return an empty buffer, but won't block the audio thread like it would
  32705. do if you use the getCallbackLock() critical section to synchronise access.
  32706. If you're going to use this, your processBlock() method must call isSuspended() and
  32707. check whether it's suspended or not. If it is, then it should skip doing any real
  32708. processing, either emitting silence or passing the input through unchanged.
  32709. @see getCallbackLock
  32710. */
  32711. void suspendProcessing (bool shouldBeSuspended);
  32712. /** Returns true if processing is currently suspended.
  32713. @see suspendProcessing
  32714. */
  32715. bool isSuspended() const noexcept { return suspended; }
  32716. /** A plugin can override this to be told when it should reset any playing voices.
  32717. The default implementation does nothing, but a host may call this to tell the
  32718. plugin that it should stop any tails or sounds that have been left running.
  32719. */
  32720. virtual void reset();
  32721. /** Returns true if the processor is being run in an offline mode for rendering.
  32722. If the processor is being run live on realtime signals, this returns false.
  32723. If the mode is unknown, this will assume it's realtime and return false.
  32724. This value may be unreliable until the prepareToPlay() method has been called,
  32725. and could change each time prepareToPlay() is called.
  32726. @see setNonRealtime()
  32727. */
  32728. bool isNonRealtime() const noexcept { return nonRealtime; }
  32729. /** Called by the host to tell this processor whether it's being used in a non-realime
  32730. capacity for offline rendering or bouncing.
  32731. Whatever value is passed-in will be
  32732. */
  32733. void setNonRealtime (bool isNonRealtime) noexcept;
  32734. /** Creates the filter's UI.
  32735. This can return 0 if you want a UI-less filter, in which case the host may create
  32736. a generic UI that lets the user twiddle the parameters directly.
  32737. If you do want to pass back a component, the component should be created and set to
  32738. the correct size before returning it. If you implement this method, you must
  32739. also implement the hasEditor() method and make it return true.
  32740. Remember not to do anything silly like allowing your filter to keep a pointer to
  32741. the component that gets created - it could be deleted later without any warning, which
  32742. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  32743. The correct way to handle the connection between an editor component and its
  32744. filter is to use something like a ChangeBroadcaster so that the editor can
  32745. register itself as a listener, and be told when a change occurs. This lets them
  32746. safely unregister themselves when they are deleted.
  32747. Here are a few things to bear in mind when writing an editor:
  32748. - Initially there won't be an editor, until the user opens one, or they might
  32749. not open one at all. Your filter mustn't rely on it being there.
  32750. - An editor object may be deleted and a replacement one created again at any time.
  32751. - It's safe to assume that an editor will be deleted before its filter.
  32752. @see hasEditor
  32753. */
  32754. virtual AudioProcessorEditor* createEditor() = 0;
  32755. /** Your filter must override this and return true if it can create an editor component.
  32756. @see createEditor
  32757. */
  32758. virtual bool hasEditor() const = 0;
  32759. /** Returns the active editor, if there is one.
  32760. Bear in mind this can return 0, even if an editor has previously been
  32761. opened.
  32762. */
  32763. AudioProcessorEditor* getActiveEditor() const noexcept { return activeEditor; }
  32764. /** Returns the active editor, or if there isn't one, it will create one.
  32765. This may call createEditor() internally to create the component.
  32766. */
  32767. AudioProcessorEditor* createEditorIfNeeded();
  32768. /** This must return the correct value immediately after the object has been
  32769. created, and mustn't change the number of parameters later.
  32770. */
  32771. virtual int getNumParameters() = 0;
  32772. /** Returns the name of a particular parameter. */
  32773. virtual const String getParameterName (int parameterIndex) = 0;
  32774. /** Called by the host to find out the value of one of the filter's parameters.
  32775. The host will expect the value returned to be between 0 and 1.0.
  32776. This could be called quite frequently, so try to make your code efficient.
  32777. It's also likely to be called by non-UI threads, so the code in here should
  32778. be thread-aware.
  32779. */
  32780. virtual float getParameter (int parameterIndex) = 0;
  32781. /** Returns the value of a parameter as a text string. */
  32782. virtual const String getParameterText (int parameterIndex) = 0;
  32783. /** The host will call this method to change the value of one of the filter's parameters.
  32784. The host may call this at any time, including during the audio processing
  32785. callback, so the filter has to process this very fast and avoid blocking.
  32786. If you want to set the value of a parameter internally, e.g. from your
  32787. editor component, then don't call this directly - instead, use the
  32788. setParameterNotifyingHost() method, which will also send a message to
  32789. the host telling it about the change. If the message isn't sent, the host
  32790. won't be able to automate your parameters properly.
  32791. The value passed will be between 0 and 1.0.
  32792. */
  32793. virtual void setParameter (int parameterIndex,
  32794. float newValue) = 0;
  32795. /** Your filter can call this when it needs to change one of its parameters.
  32796. This could happen when the editor or some other internal operation changes
  32797. a parameter. This method will call the setParameter() method to change the
  32798. value, and will then send a message to the host telling it about the change.
  32799. Note that to make sure the host correctly handles automation, you should call
  32800. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  32801. tell the host when the user has started and stopped changing the parameter.
  32802. */
  32803. void setParameterNotifyingHost (int parameterIndex,
  32804. float newValue);
  32805. /** Returns true if the host can automate this parameter.
  32806. By default, this returns true for all parameters.
  32807. */
  32808. virtual bool isParameterAutomatable (int parameterIndex) const;
  32809. /** Should return true if this parameter is a "meta" parameter.
  32810. A meta-parameter is a parameter that changes other params. It is used
  32811. by some hosts (e.g. AudioUnit hosts).
  32812. By default this returns false.
  32813. */
  32814. virtual bool isMetaParameter (int parameterIndex) const;
  32815. /** Sends a signal to the host to tell it that the user is about to start changing this
  32816. parameter.
  32817. This allows the host to know when a parameter is actively being held by the user, and
  32818. it may use this information to help it record automation.
  32819. If you call this, it must be matched by a later call to endParameterChangeGesture().
  32820. */
  32821. void beginParameterChangeGesture (int parameterIndex);
  32822. /** Tells the host that the user has finished changing this parameter.
  32823. This allows the host to know when a parameter is actively being held by the user, and
  32824. it may use this information to help it record automation.
  32825. A call to this method must follow a call to beginParameterChangeGesture().
  32826. */
  32827. void endParameterChangeGesture (int parameterIndex);
  32828. /** The filter can call this when something (apart from a parameter value) has changed.
  32829. It sends a hint to the host that something like the program, number of parameters,
  32830. etc, has changed, and that it should update itself.
  32831. */
  32832. void updateHostDisplay();
  32833. /** Returns the number of preset programs the filter supports.
  32834. The value returned must be valid as soon as this object is created, and
  32835. must not change over its lifetime.
  32836. This value shouldn't be less than 1.
  32837. */
  32838. virtual int getNumPrograms() = 0;
  32839. /** Returns the number of the currently active program.
  32840. */
  32841. virtual int getCurrentProgram() = 0;
  32842. /** Called by the host to change the current program.
  32843. */
  32844. virtual void setCurrentProgram (int index) = 0;
  32845. /** Must return the name of a given program. */
  32846. virtual const String getProgramName (int index) = 0;
  32847. /** Called by the host to rename a program.
  32848. */
  32849. virtual void changeProgramName (int index, const String& newName) = 0;
  32850. /** The host will call this method when it wants to save the filter's internal state.
  32851. This must copy any info about the filter's state into the block of memory provided,
  32852. so that the host can store this and later restore it using setStateInformation().
  32853. Note that there's also a getCurrentProgramStateInformation() method, which only
  32854. stores the current program, not the state of the entire filter.
  32855. See also the helper function copyXmlToBinary() for storing settings as XML.
  32856. @see getCurrentProgramStateInformation
  32857. */
  32858. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  32859. /** The host will call this method if it wants to save the state of just the filter's
  32860. current program.
  32861. Unlike getStateInformation, this should only return the current program's state.
  32862. Not all hosts support this, and if you don't implement it, the base class
  32863. method just calls getStateInformation() instead. If you do implement it, be
  32864. sure to also implement getCurrentProgramStateInformation.
  32865. @see getStateInformation, setCurrentProgramStateInformation
  32866. */
  32867. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  32868. /** This must restore the filter's state from a block of data previously created
  32869. using getStateInformation().
  32870. Note that there's also a setCurrentProgramStateInformation() method, which tries
  32871. to restore just the current program, not the state of the entire filter.
  32872. See also the helper function getXmlFromBinary() for loading settings as XML.
  32873. @see setCurrentProgramStateInformation
  32874. */
  32875. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  32876. /** The host will call this method if it wants to restore the state of just the filter's
  32877. current program.
  32878. Not all hosts support this, and if you don't implement it, the base class
  32879. method just calls setStateInformation() instead. If you do implement it, be
  32880. sure to also implement getCurrentProgramStateInformation.
  32881. @see setStateInformation, getCurrentProgramStateInformation
  32882. */
  32883. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  32884. /** Adds a listener that will be called when an aspect of this processor changes. */
  32885. void addListener (AudioProcessorListener* newListener);
  32886. /** Removes a previously added listener. */
  32887. void removeListener (AudioProcessorListener* listenerToRemove);
  32888. /** Tells the processor to use this playhead object.
  32889. The processor will not take ownership of the object, so the caller must delete it when
  32890. it is no longer being used.
  32891. */
  32892. void setPlayHead (AudioPlayHead* newPlayHead) noexcept;
  32893. /** Not for public use - this is called before deleting an editor component. */
  32894. void editorBeingDeleted (AudioProcessorEditor* editor) noexcept;
  32895. /** Not for public use - this is called to initialise the processor before playing. */
  32896. void setPlayConfigDetails (int numIns, int numOuts,
  32897. double sampleRate,
  32898. int blockSize) noexcept;
  32899. protected:
  32900. /** Helper function that just converts an xml element into a binary blob.
  32901. Use this in your filter's getStateInformation() method if you want to
  32902. store its state as xml.
  32903. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  32904. from a binary blob.
  32905. */
  32906. static void copyXmlToBinary (const XmlElement& xml,
  32907. JUCE_NAMESPACE::MemoryBlock& destData);
  32908. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  32909. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  32910. an XmlElement object that the caller must delete when no longer needed.
  32911. */
  32912. static XmlElement* getXmlFromBinary (const void* data, int sizeInBytes);
  32913. /** @internal */
  32914. AudioPlayHead* playHead;
  32915. /** @internal */
  32916. void sendParamChangeMessageToListeners (int parameterIndex, float newValue);
  32917. private:
  32918. Array <AudioProcessorListener*> listeners;
  32919. Component::SafePointer<AudioProcessorEditor> activeEditor;
  32920. double sampleRate;
  32921. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  32922. bool suspended, nonRealtime;
  32923. CriticalSection callbackLock, listenerLock;
  32924. #if JUCE_DEBUG
  32925. BigInteger changingParams;
  32926. #endif
  32927. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessor);
  32928. };
  32929. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  32930. /*** End of inlined file: juce_AudioProcessor.h ***/
  32931. /*** Start of inlined file: juce_PluginDescription.h ***/
  32932. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  32933. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  32934. /**
  32935. A small class to represent some facts about a particular type of plugin.
  32936. This class is for storing and managing the details about a plugin without
  32937. actually having to load an instance of it.
  32938. A KnownPluginList contains a list of PluginDescription objects.
  32939. @see KnownPluginList
  32940. */
  32941. class JUCE_API PluginDescription
  32942. {
  32943. public:
  32944. PluginDescription();
  32945. PluginDescription (const PluginDescription& other);
  32946. PluginDescription& operator= (const PluginDescription& other);
  32947. ~PluginDescription();
  32948. /** The name of the plugin. */
  32949. String name;
  32950. /** A more descriptive name for the plugin.
  32951. This may be the same as the 'name' field, but some plugins may provide an
  32952. alternative name.
  32953. */
  32954. String descriptiveName;
  32955. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  32956. */
  32957. String pluginFormatName;
  32958. /** A category, such as "Dynamics", "Reverbs", etc.
  32959. */
  32960. String category;
  32961. /** The manufacturer. */
  32962. String manufacturerName;
  32963. /** The version. This string doesn't have any particular format. */
  32964. String version;
  32965. /** Either the file containing the plugin module, or some other unique way
  32966. of identifying it.
  32967. E.g. for an AU, this would be an ID string that the component manager
  32968. could use to retrieve the plugin. For a VST, it's the file path.
  32969. */
  32970. String fileOrIdentifier;
  32971. /** The last time the plugin file was changed.
  32972. This is handy when scanning for new or changed plugins.
  32973. */
  32974. Time lastFileModTime;
  32975. /** A unique ID for the plugin.
  32976. Note that this might not be unique between formats, e.g. a VST and some
  32977. other format might actually have the same id.
  32978. @see createIdentifierString
  32979. */
  32980. int uid;
  32981. /** True if the plugin identifies itself as a synthesiser. */
  32982. bool isInstrument;
  32983. /** The number of inputs. */
  32984. int numInputChannels;
  32985. /** The number of outputs. */
  32986. int numOutputChannels;
  32987. /** Returns true if the two descriptions refer the the same plugin.
  32988. This isn't quite as simple as them just having the same file (because of
  32989. shell plugins).
  32990. */
  32991. bool isDuplicateOf (const PluginDescription& other) const;
  32992. /** Returns a string that can be saved and used to uniquely identify the
  32993. plugin again.
  32994. This contains less info than the XML encoding, and is independent of the
  32995. plugin's file location, so can be used to store a plugin ID for use
  32996. across different machines.
  32997. */
  32998. String createIdentifierString() const;
  32999. /** Creates an XML object containing these details.
  33000. @see loadFromXml
  33001. */
  33002. XmlElement* createXml() const;
  33003. /** Reloads the info in this structure from an XML record that was previously
  33004. saved with createXML().
  33005. Returns true if the XML was a valid plugin description.
  33006. */
  33007. bool loadFromXml (const XmlElement& xml);
  33008. private:
  33009. JUCE_LEAK_DETECTOR (PluginDescription);
  33010. };
  33011. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  33012. /*** End of inlined file: juce_PluginDescription.h ***/
  33013. /**
  33014. Base class for an active instance of a plugin.
  33015. This derives from the AudioProcessor class, and adds some extra functionality
  33016. that helps when wrapping dynamically loaded plugins.
  33017. @see AudioProcessor, AudioPluginFormat
  33018. */
  33019. class JUCE_API AudioPluginInstance : public AudioProcessor
  33020. {
  33021. public:
  33022. /** Destructor.
  33023. Make sure that you delete any UI components that belong to this plugin before
  33024. deleting the plugin.
  33025. */
  33026. virtual ~AudioPluginInstance();
  33027. /** Fills-in the appropriate parts of this plugin description object.
  33028. */
  33029. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  33030. /** Returns a pointer to some kind of platform-specific data about the plugin.
  33031. E.g. For a VST, this value can be cast to an AEffect*. For an AudioUnit, it can be
  33032. cast to an AudioUnit handle.
  33033. */
  33034. virtual void* getPlatformSpecificData();
  33035. protected:
  33036. AudioPluginInstance();
  33037. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginInstance);
  33038. };
  33039. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  33040. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  33041. class PluginDescription;
  33042. /**
  33043. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  33044. Use the static getNumFormats() and getFormat() calls to find the types
  33045. of format that are available.
  33046. */
  33047. class JUCE_API AudioPluginFormat
  33048. {
  33049. public:
  33050. /** Destructor. */
  33051. virtual ~AudioPluginFormat();
  33052. /** Returns the format name.
  33053. E.g. "VST", "AudioUnit", etc.
  33054. */
  33055. virtual String getName() const = 0;
  33056. /** This tries to create descriptions for all the plugin types available in
  33057. a binary module file.
  33058. The file will be some kind of DLL or bundle.
  33059. Normally there will only be one type returned, but some plugins
  33060. (e.g. VST shells) can use a single DLL to create a set of different plugin
  33061. subtypes, so in that case, each subtype is returned as a separate object.
  33062. */
  33063. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  33064. const String& fileOrIdentifier) = 0;
  33065. /** Tries to recreate a type from a previously generated PluginDescription.
  33066. @see PluginDescription::createInstance
  33067. */
  33068. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  33069. /** Should do a quick check to see if this file or directory might be a plugin of
  33070. this format.
  33071. This is for searching for potential files, so it shouldn't actually try to
  33072. load the plugin or do anything time-consuming.
  33073. */
  33074. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  33075. /** Returns a readable version of the name of the plugin that this identifier refers to.
  33076. */
  33077. virtual String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  33078. /** Checks whether this plugin could possibly be loaded.
  33079. It doesn't actually need to load it, just to check whether the file or component
  33080. still exists.
  33081. */
  33082. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  33083. /** Searches a suggested set of directories for any plugins in this format.
  33084. The path might be ignored, e.g. by AUs, which are found by the OS rather
  33085. than manually.
  33086. */
  33087. virtual StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  33088. bool recursive) = 0;
  33089. /** Returns the typical places to look for this kind of plugin.
  33090. Note that if this returns no paths, it means that the format can't be scanned-for
  33091. (i.e. it's an internal format that doesn't live in files)
  33092. */
  33093. virtual FileSearchPath getDefaultLocationsToSearch() = 0;
  33094. protected:
  33095. AudioPluginFormat() noexcept;
  33096. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormat);
  33097. };
  33098. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  33099. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  33100. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  33101. /**
  33102. Implements a plugin format manager for AudioUnits.
  33103. */
  33104. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  33105. {
  33106. public:
  33107. AudioUnitPluginFormat();
  33108. ~AudioUnitPluginFormat();
  33109. String getName() const { return "AudioUnit"; }
  33110. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33111. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33112. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33113. String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  33114. StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  33115. bool doesPluginStillExist (const PluginDescription& desc);
  33116. FileSearchPath getDefaultLocationsToSearch();
  33117. private:
  33118. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginFormat);
  33119. };
  33120. #endif
  33121. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  33122. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  33123. #endif
  33124. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33125. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  33126. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33127. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33128. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  33129. // Sorry, this file is just a placeholder at the moment!...
  33130. /**
  33131. Implements a plugin format manager for DirectX plugins.
  33132. */
  33133. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  33134. {
  33135. public:
  33136. DirectXPluginFormat();
  33137. ~DirectXPluginFormat();
  33138. String getName() const { return "DirectX"; }
  33139. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33140. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33141. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33142. String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  33143. FileSearchPath getDefaultLocationsToSearch();
  33144. private:
  33145. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectXPluginFormat);
  33146. };
  33147. #endif
  33148. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33149. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  33150. #endif
  33151. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33152. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  33153. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33154. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33155. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  33156. // Sorry, this file is just a placeholder at the moment!...
  33157. /**
  33158. Implements a plugin format manager for DirectX plugins.
  33159. */
  33160. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  33161. {
  33162. public:
  33163. LADSPAPluginFormat();
  33164. ~LADSPAPluginFormat();
  33165. String getName() const { return "LADSPA"; }
  33166. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33167. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33168. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33169. String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  33170. FileSearchPath getDefaultLocationsToSearch();
  33171. private:
  33172. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LADSPAPluginFormat);
  33173. };
  33174. #endif
  33175. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33176. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  33177. #endif
  33178. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33179. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  33180. #ifdef __aeffect__
  33181. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33182. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33183. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  33184. events to the list.
  33185. This is used by both the VST hosting code and the plugin wrapper.
  33186. */
  33187. class VSTMidiEventList
  33188. {
  33189. public:
  33190. VSTMidiEventList()
  33191. : numEventsUsed (0), numEventsAllocated (0)
  33192. {
  33193. }
  33194. ~VSTMidiEventList()
  33195. {
  33196. freeEvents();
  33197. }
  33198. void clear()
  33199. {
  33200. numEventsUsed = 0;
  33201. if (events != nullptr)
  33202. events->numEvents = 0;
  33203. }
  33204. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  33205. {
  33206. ensureSize (numEventsUsed + 1);
  33207. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  33208. events->numEvents = ++numEventsUsed;
  33209. if (numBytes <= 4)
  33210. {
  33211. if (e->type == kVstSysExType)
  33212. {
  33213. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  33214. e->type = kVstMidiType;
  33215. e->byteSize = sizeof (VstMidiEvent);
  33216. e->noteLength = 0;
  33217. e->noteOffset = 0;
  33218. e->detune = 0;
  33219. e->noteOffVelocity = 0;
  33220. }
  33221. e->deltaFrames = frameOffset;
  33222. memcpy (e->midiData, midiData, numBytes);
  33223. }
  33224. else
  33225. {
  33226. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  33227. if (se->type == kVstSysExType)
  33228. delete[] se->sysexDump;
  33229. se->sysexDump = new char [numBytes];
  33230. memcpy (se->sysexDump, midiData, numBytes);
  33231. se->type = kVstSysExType;
  33232. se->byteSize = sizeof (VstMidiSysexEvent);
  33233. se->deltaFrames = frameOffset;
  33234. se->flags = 0;
  33235. se->dumpBytes = numBytes;
  33236. se->resvd1 = 0;
  33237. se->resvd2 = 0;
  33238. }
  33239. }
  33240. // Handy method to pull the events out of an event buffer supplied by the host
  33241. // or plugin.
  33242. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  33243. {
  33244. for (int i = 0; i < events->numEvents; ++i)
  33245. {
  33246. const VstEvent* const e = events->events[i];
  33247. if (e != nullptr)
  33248. {
  33249. if (e->type == kVstMidiType)
  33250. {
  33251. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  33252. 4, e->deltaFrames);
  33253. }
  33254. else if (e->type == kVstSysExType)
  33255. {
  33256. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  33257. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  33258. e->deltaFrames);
  33259. }
  33260. }
  33261. }
  33262. }
  33263. void ensureSize (int numEventsNeeded)
  33264. {
  33265. if (numEventsNeeded > numEventsAllocated)
  33266. {
  33267. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  33268. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  33269. if (events == nullptr)
  33270. events.calloc (size, 1);
  33271. else
  33272. events.realloc (size, 1);
  33273. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  33274. events->events[i] = allocateVSTEvent();
  33275. numEventsAllocated = numEventsNeeded;
  33276. }
  33277. }
  33278. void freeEvents()
  33279. {
  33280. if (events != nullptr)
  33281. {
  33282. for (int i = numEventsAllocated; --i >= 0;)
  33283. freeVSTEvent (events->events[i]);
  33284. events.free();
  33285. numEventsUsed = 0;
  33286. numEventsAllocated = 0;
  33287. }
  33288. }
  33289. HeapBlock <VstEvents> events;
  33290. private:
  33291. int numEventsUsed, numEventsAllocated;
  33292. static VstEvent* allocateVSTEvent()
  33293. {
  33294. VstEvent* const e = (VstEvent*) ::calloc (1, sizeof (VstMidiEvent) > sizeof (VstMidiSysexEvent) ? sizeof (VstMidiEvent)
  33295. : sizeof (VstMidiSysexEvent));
  33296. e->type = kVstMidiType;
  33297. e->byteSize = sizeof (VstMidiEvent);
  33298. return e;
  33299. }
  33300. static void freeVSTEvent (VstEvent* e)
  33301. {
  33302. if (e->type == kVstSysExType)
  33303. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  33304. ::free (e);
  33305. }
  33306. };
  33307. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33308. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33309. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  33310. #endif
  33311. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33312. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  33313. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33314. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33315. #if JUCE_PLUGINHOST_VST
  33316. /**
  33317. Implements a plugin format manager for VSTs.
  33318. */
  33319. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  33320. {
  33321. public:
  33322. VSTPluginFormat();
  33323. ~VSTPluginFormat();
  33324. String getName() const { return "VST"; }
  33325. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33326. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33327. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33328. String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  33329. StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  33330. bool doesPluginStillExist (const PluginDescription& desc);
  33331. FileSearchPath getDefaultLocationsToSearch();
  33332. private:
  33333. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  33334. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginFormat);
  33335. };
  33336. #endif
  33337. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33338. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  33339. #endif
  33340. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  33341. #endif
  33342. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33343. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  33344. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33345. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33346. /**
  33347. This maintains a list of known AudioPluginFormats.
  33348. @see AudioPluginFormat
  33349. */
  33350. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  33351. {
  33352. public:
  33353. AudioPluginFormatManager();
  33354. /** Destructor. */
  33355. ~AudioPluginFormatManager();
  33356. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  33357. /** Adds any formats that it knows about, e.g. VST.
  33358. */
  33359. void addDefaultFormats();
  33360. /** Returns the number of types of format that are available.
  33361. Use getFormat() to get one of them.
  33362. */
  33363. int getNumFormats();
  33364. /** Returns one of the available formats.
  33365. @see getNumFormats
  33366. */
  33367. AudioPluginFormat* getFormat (int index);
  33368. /** Adds a format to the list.
  33369. The object passed in will be owned and deleted by the manager.
  33370. */
  33371. void addFormat (AudioPluginFormat* format);
  33372. /** Tries to load the type for this description, by trying all the formats
  33373. that this manager knows about.
  33374. The caller is responsible for deleting the object that is returned.
  33375. If it can't load the plugin, it returns 0 and leaves a message in the
  33376. errorMessage string.
  33377. */
  33378. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  33379. String& errorMessage) const;
  33380. /** Checks that the file or component for this plugin actually still exists.
  33381. (This won't try to load the plugin)
  33382. */
  33383. bool doesPluginStillExist (const PluginDescription& description) const;
  33384. private:
  33385. OwnedArray <AudioPluginFormat> formats;
  33386. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormatManager);
  33387. };
  33388. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33389. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  33390. #endif
  33391. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  33392. #endif
  33393. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33394. /*** Start of inlined file: juce_KnownPluginList.h ***/
  33395. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33396. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33397. /*** Start of inlined file: juce_PopupMenu.h ***/
  33398. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  33399. #define __JUCE_POPUPMENU_JUCEHEADER__
  33400. /** Creates and displays a popup-menu.
  33401. To show a popup-menu, you create one of these, add some items to it, then
  33402. call its show() method, which returns the id of the item the user selects.
  33403. E.g. @code
  33404. void MyWidget::mouseDown (const MouseEvent& e)
  33405. {
  33406. PopupMenu m;
  33407. m.addItem (1, "item 1");
  33408. m.addItem (2, "item 2");
  33409. const int result = m.show();
  33410. if (result == 0)
  33411. {
  33412. // user dismissed the menu without picking anything
  33413. }
  33414. else if (result == 1)
  33415. {
  33416. // user picked item 1
  33417. }
  33418. else if (result == 2)
  33419. {
  33420. // user picked item 2
  33421. }
  33422. }
  33423. @endcode
  33424. Submenus are easy too: @code
  33425. void MyWidget::mouseDown (const MouseEvent& e)
  33426. {
  33427. PopupMenu subMenu;
  33428. subMenu.addItem (1, "item 1");
  33429. subMenu.addItem (2, "item 2");
  33430. PopupMenu mainMenu;
  33431. mainMenu.addItem (3, "item 3");
  33432. mainMenu.addSubMenu ("other choices", subMenu);
  33433. const int result = m.show();
  33434. ...etc
  33435. }
  33436. @endcode
  33437. */
  33438. class JUCE_API PopupMenu
  33439. {
  33440. public:
  33441. /** Creates an empty popup menu. */
  33442. PopupMenu();
  33443. /** Creates a copy of another menu. */
  33444. PopupMenu (const PopupMenu& other);
  33445. /** Destructor. */
  33446. ~PopupMenu();
  33447. /** Copies this menu from another one. */
  33448. PopupMenu& operator= (const PopupMenu& other);
  33449. /** Resets the menu, removing all its items. */
  33450. void clear();
  33451. /** Appends a new text item for this menu to show.
  33452. @param itemResultId the number that will be returned from the show() method
  33453. if the user picks this item. The value should never be
  33454. zero, because that's used to indicate that the user didn't
  33455. select anything.
  33456. @param itemText the text to show.
  33457. @param isEnabled if false, the item will be shown 'greyed-out' and can't be picked
  33458. @param isTicked if true, the item will be shown with a tick next to it
  33459. @param iconToUse if this is non-zero, it should be an image that will be
  33460. displayed to the left of the item. This method will take its
  33461. own copy of the image passed-in, so there's no need to keep
  33462. it hanging around.
  33463. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  33464. */
  33465. void addItem (int itemResultId,
  33466. const String& itemText,
  33467. bool isEnabled = true,
  33468. bool isTicked = false,
  33469. const Image& iconToUse = Image::null);
  33470. /** Adds an item that represents one of the commands in a command manager object.
  33471. @param commandManager the manager to use to trigger the command and get information
  33472. about it
  33473. @param commandID the ID of the command
  33474. @param displayName if this is non-empty, then this string will be used instead of
  33475. the command's registered name
  33476. */
  33477. void addCommandItem (ApplicationCommandManager* commandManager,
  33478. int commandID,
  33479. const String& displayName = String::empty);
  33480. /** Appends a text item with a special colour.
  33481. This is the same as addItem(), but specifies a colour to use for the
  33482. text, which will override the default colours that are used by the
  33483. current look-and-feel. See addItem() for a description of the parameters.
  33484. */
  33485. void addColouredItem (int itemResultId,
  33486. const String& itemText,
  33487. const Colour& itemTextColour,
  33488. bool isEnabled = true,
  33489. bool isTicked = false,
  33490. const Image& iconToUse = Image::null);
  33491. /** Appends a custom menu item that can't be used to trigger a result.
  33492. This will add a user-defined component to use as a menu item. Unlike the
  33493. addCustomItem() method that takes a PopupMenu::CustomComponent, this version
  33494. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  33495. delete the component when it's finished, so it's the caller's responsibility
  33496. to manage the component that is passed-in.
  33497. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  33498. detection of a mouse-click on your component, and use that to trigger the
  33499. menu ID specified in itemResultId. If this is false, the menu item can't
  33500. be triggered, so itemResultId is not used.
  33501. @see CustomComponent
  33502. */
  33503. void addCustomItem (int itemResultId,
  33504. Component* customComponent,
  33505. int idealWidth, int idealHeight,
  33506. bool triggerMenuItemAutomaticallyWhenClicked);
  33507. /** Appends a sub-menu.
  33508. If the menu that's passed in is empty, it will appear as an inactive item.
  33509. */
  33510. void addSubMenu (const String& subMenuName,
  33511. const PopupMenu& subMenu,
  33512. bool isEnabled = true,
  33513. const Image& iconToUse = Image::null,
  33514. bool isTicked = false);
  33515. /** Appends a separator to the menu, to help break it up into sections.
  33516. The menu class is smart enough not to display separators at the top or bottom
  33517. of the menu, and it will replace mutliple adjacent separators with a single
  33518. one, so your code can be quite free and easy about adding these, and it'll
  33519. always look ok.
  33520. */
  33521. void addSeparator();
  33522. /** Adds a non-clickable text item to the menu.
  33523. This is a bold-font items which can be used as a header to separate the items
  33524. into named groups.
  33525. */
  33526. void addSectionHeader (const String& title);
  33527. /** Returns the number of items that the menu currently contains.
  33528. (This doesn't count separators).
  33529. */
  33530. int getNumItems() const noexcept;
  33531. /** Returns true if the menu contains a command item that triggers the given command. */
  33532. bool containsCommandItem (int commandID) const;
  33533. /** Returns true if the menu contains any items that can be used. */
  33534. bool containsAnyActiveItems() const noexcept;
  33535. /** Class used to create a set of options to pass to the show() method.
  33536. You can chain together a series of calls to this class's methods to create
  33537. a set of whatever options you want to specify.
  33538. E.g. @code
  33539. PopupMenu menu;
  33540. ...
  33541. menu.showMenu (PopupMenu::Options().withMaximumWidth (100),
  33542. .withMaximumNumColumns (3)
  33543. .withTargetComponent (myComp));
  33544. @endcode
  33545. */
  33546. class JUCE_API Options
  33547. {
  33548. public:
  33549. Options();
  33550. const Options withTargetComponent (Component* targetComponent) const;
  33551. const Options withTargetScreenArea (const Rectangle<int>& targetArea) const;
  33552. const Options withMinimumWidth (int minWidth) const;
  33553. const Options withMaximumNumColumns (int maxNumColumns) const;
  33554. const Options withStandardItemHeight (int standardHeight) const;
  33555. const Options withItemThatMustBeVisible (int idOfItemToBeVisible) const;
  33556. private:
  33557. friend class PopupMenu;
  33558. Rectangle<int> targetArea;
  33559. Component* targetComponent;
  33560. int visibleItemID, minWidth, maxColumns, standardHeight;
  33561. };
  33562. #if JUCE_MODAL_LOOPS_PERMITTED
  33563. /** Displays the menu and waits for the user to pick something.
  33564. This will display the menu modally, and return the ID of the item that the
  33565. user picks. If they click somewhere off the menu to get rid of it without
  33566. choosing anything, this will return 0.
  33567. The current location of the mouse will be used as the position to show the
  33568. menu - to explicitly set the menu's position, use showAt() instead. Depending
  33569. on where this point is on the screen, the menu will appear above, below or
  33570. to the side of the point.
  33571. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  33572. then when the menu first appears, it will make sure
  33573. that this item is visible. So if the menu has too many
  33574. items to fit on the screen, it will be scrolled to a
  33575. position where this item is visible.
  33576. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  33577. than this if some items are too long to fit.
  33578. @param maximumNumColumns if there are too many items to fit on-screen in a single
  33579. vertical column, the menu may be laid out as a series of
  33580. columns - this is the maximum number allowed. To use the
  33581. default value for this (probably about 7), you can pass
  33582. in zero.
  33583. @param standardItemHeight if this is non-zero, it will be used as the standard
  33584. height for menu items (apart from custom items)
  33585. @param callback if this is non-zero, the menu will be launched asynchronously,
  33586. returning immediately, and the callback will receive a
  33587. call when the menu is either dismissed or has an item
  33588. selected. This object will be owned and deleted by the
  33589. system, so make sure that it works safely and that any
  33590. pointers that it uses are safely within scope.
  33591. @see showAt
  33592. */
  33593. int show (int itemIdThatMustBeVisible = 0,
  33594. int minimumWidth = 0,
  33595. int maximumNumColumns = 0,
  33596. int standardItemHeight = 0,
  33597. ModalComponentManager::Callback* callback = nullptr);
  33598. /** Displays the menu at a specific location.
  33599. This is the same as show(), but uses a specific location (in global screen
  33600. co-ordinates) rather than the current mouse position.
  33601. The screenAreaToAttachTo parameter indicates a screen area to which the menu
  33602. will be adjacent. Depending on where this is, the menu will decide which edge to
  33603. attach itself to, in order to fit itself fully on-screen. If you just want to
  33604. trigger a menu at a specific point, you can pass in a rectangle of size (0, 0)
  33605. with the position that you want.
  33606. @see show()
  33607. */
  33608. int showAt (const Rectangle<int>& screenAreaToAttachTo,
  33609. int itemIdThatMustBeVisible = 0,
  33610. int minimumWidth = 0,
  33611. int maximumNumColumns = 0,
  33612. int standardItemHeight = 0,
  33613. ModalComponentManager::Callback* callback = nullptr);
  33614. /** Displays the menu as if it's attached to a component such as a button.
  33615. This is similar to showAt(), but will position it next to the given component, e.g.
  33616. so that the menu's edge is aligned with that of the component. This is intended for
  33617. things like buttons that trigger a pop-up menu.
  33618. */
  33619. int showAt (Component* componentToAttachTo,
  33620. int itemIdThatMustBeVisible = 0,
  33621. int minimumWidth = 0,
  33622. int maximumNumColumns = 0,
  33623. int standardItemHeight = 0,
  33624. ModalComponentManager::Callback* callback = nullptr);
  33625. /** Displays and runs the menu modally, with a set of options.
  33626. */
  33627. int showMenu (const Options& options);
  33628. #endif
  33629. /** Runs the menu asynchronously, with a user-provided callback that will receive the result. */
  33630. void showMenuAsync (const Options& options,
  33631. ModalComponentManager::Callback* callback);
  33632. /** Closes any menus that are currently open.
  33633. This might be useful if you have a situation where your window is being closed
  33634. by some means other than a user action, and you'd like to make sure that menus
  33635. aren't left hanging around.
  33636. */
  33637. static bool JUCE_CALLTYPE dismissAllActiveMenus();
  33638. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  33639. This can be called before show() if you need a customised menu. Be careful
  33640. not to delete the LookAndFeel object before the menu has been deleted.
  33641. */
  33642. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  33643. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  33644. These constants can be used either via the LookAndFeel::setColour()
  33645. method for the look and feel that is set for this menu with setLookAndFeel()
  33646. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  33647. */
  33648. enum ColourIds
  33649. {
  33650. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  33651. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  33652. colour is specified when the item is added). */
  33653. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  33654. addSectionHeader() method). */
  33655. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  33656. highlighted menu item. */
  33657. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  33658. highlighted item. */
  33659. };
  33660. /**
  33661. Allows you to iterate through the items in a pop-up menu, and examine
  33662. their properties.
  33663. To use this, just create one and repeatedly call its next() method. When this
  33664. returns true, all the member variables of the iterator are filled-out with
  33665. information describing the menu item. When it returns false, the end of the
  33666. list has been reached.
  33667. */
  33668. class JUCE_API MenuItemIterator
  33669. {
  33670. public:
  33671. /** Creates an iterator that will scan through the items in the specified
  33672. menu.
  33673. Be careful not to add any items to a menu while it is being iterated,
  33674. or things could get out of step.
  33675. */
  33676. MenuItemIterator (const PopupMenu& menu);
  33677. /** Destructor. */
  33678. ~MenuItemIterator();
  33679. /** Returns true if there is another item, and sets up all this object's
  33680. member variables to reflect that item's properties.
  33681. */
  33682. bool next();
  33683. String itemName;
  33684. const PopupMenu* subMenu;
  33685. int itemId;
  33686. bool isSeparator;
  33687. bool isTicked;
  33688. bool isEnabled;
  33689. bool isCustomComponent;
  33690. bool isSectionHeader;
  33691. const Colour* customColour;
  33692. Image customImage;
  33693. ApplicationCommandManager* commandManager;
  33694. private:
  33695. const PopupMenu& menu;
  33696. int index;
  33697. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuItemIterator);
  33698. };
  33699. /** A user-defined copmonent that can be used as an item in a popup menu.
  33700. @see PopupMenu::addCustomItem
  33701. */
  33702. class JUCE_API CustomComponent : public Component,
  33703. public SingleThreadedReferenceCountedObject
  33704. {
  33705. public:
  33706. /** Creates a custom item.
  33707. If isTriggeredAutomatically is true, then the menu will automatically detect
  33708. a mouse-click on this component and use that to invoke the menu item. If it's
  33709. false, then it's up to your class to manually trigger the item when it wants to.
  33710. */
  33711. CustomComponent (bool isTriggeredAutomatically = true);
  33712. /** Destructor. */
  33713. ~CustomComponent();
  33714. /** Returns a rectangle with the size that this component would like to have.
  33715. Note that the size which this method returns isn't necessarily the one that
  33716. the menu will give it, as the items will be stretched to have a uniform width.
  33717. */
  33718. virtual void getIdealSize (int& idealWidth, int& idealHeight) = 0;
  33719. /** Dismisses the menu, indicating that this item has been chosen.
  33720. This will cause the menu to exit from its modal state, returning
  33721. this item's id as the result.
  33722. */
  33723. void triggerMenuItem();
  33724. /** Returns true if this item should be highlighted because the mouse is over it.
  33725. You can call this method in your paint() method to find out whether
  33726. to draw a highlight.
  33727. */
  33728. bool isItemHighlighted() const noexcept { return isHighlighted; }
  33729. /** @internal */
  33730. bool isTriggeredAutomatically() const noexcept { return triggeredAutomatically; }
  33731. /** @internal */
  33732. void setHighlighted (bool shouldBeHighlighted);
  33733. private:
  33734. bool isHighlighted, triggeredAutomatically;
  33735. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponent);
  33736. };
  33737. /** Appends a custom menu item.
  33738. This will add a user-defined component to use as a menu item. The component
  33739. passed in will be deleted by this menu when it's no longer needed.
  33740. @see CustomComponent
  33741. */
  33742. void addCustomItem (int itemResultId, CustomComponent* customComponent);
  33743. private:
  33744. class Item;
  33745. class ItemComponent;
  33746. class Window;
  33747. friend class MenuItemIterator;
  33748. friend class ItemComponent;
  33749. friend class Window;
  33750. friend class CustomComponent;
  33751. friend class MenuBarComponent;
  33752. friend class OwnedArray <Item>;
  33753. friend class OwnedArray <ItemComponent>;
  33754. friend class ScopedPointer <Window>;
  33755. OwnedArray <Item> items;
  33756. LookAndFeel* lookAndFeel;
  33757. bool separatorPending;
  33758. void addSeparatorIfPending();
  33759. Component* createWindow (const Options&, ApplicationCommandManager**) const;
  33760. int showWithOptionalCallback (const Options&, ModalComponentManager::Callback*, bool);
  33761. JUCE_LEAK_DETECTOR (PopupMenu);
  33762. };
  33763. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  33764. /*** End of inlined file: juce_PopupMenu.h ***/
  33765. /**
  33766. Manages a list of plugin types.
  33767. This can be easily edited, saved and loaded, and used to create instances of
  33768. the plugin types in it.
  33769. @see PluginListComponent
  33770. */
  33771. class JUCE_API KnownPluginList : public ChangeBroadcaster
  33772. {
  33773. public:
  33774. /** Creates an empty list.
  33775. */
  33776. KnownPluginList();
  33777. /** Destructor. */
  33778. ~KnownPluginList();
  33779. /** Clears the list. */
  33780. void clear();
  33781. /** Returns the number of types currently in the list.
  33782. @see getType
  33783. */
  33784. int getNumTypes() const noexcept { return types.size(); }
  33785. /** Returns one of the types.
  33786. @see getNumTypes
  33787. */
  33788. PluginDescription* getType (int index) const noexcept { return types [index]; }
  33789. /** Looks for a type in the list which comes from this file.
  33790. */
  33791. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const;
  33792. /** Looks for a type in the list which matches a plugin type ID.
  33793. The identifierString parameter must have been created by
  33794. PluginDescription::createIdentifierString().
  33795. */
  33796. PluginDescription* getTypeForIdentifierString (const String& identifierString) const;
  33797. /** Adds a type manually from its description. */
  33798. bool addType (const PluginDescription& type);
  33799. /** Removes a type. */
  33800. void removeType (int index);
  33801. /** Looks for all types that can be loaded from a given file, and adds them
  33802. to the list.
  33803. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  33804. re-tested if it's not already in the list, or if the file's modification
  33805. time has changed since the list was created. If dontRescanIfAlreadyInList is
  33806. false, the file will always be reloaded and tested.
  33807. Returns true if any new types were added, and all the types found in this
  33808. file (even if it was already known and hasn't been re-scanned) get returned
  33809. in the array.
  33810. */
  33811. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  33812. bool dontRescanIfAlreadyInList,
  33813. OwnedArray <PluginDescription>& typesFound,
  33814. AudioPluginFormat& formatToUse);
  33815. /** Returns true if the specified file is already known about and if it
  33816. hasn't been modified since our entry was created.
  33817. */
  33818. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const;
  33819. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  33820. If any types are found in the files, their descriptions are returned in the array.
  33821. */
  33822. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  33823. OwnedArray <PluginDescription>& typesFound);
  33824. /** Sort methods used to change the order of the plugins in the list.
  33825. */
  33826. enum SortMethod
  33827. {
  33828. defaultOrder = 0,
  33829. sortAlphabetically,
  33830. sortByCategory,
  33831. sortByManufacturer,
  33832. sortByFileSystemLocation
  33833. };
  33834. /** Adds all the plugin types to a popup menu so that the user can select one.
  33835. Depending on the sort method, it may add sub-menus for categories,
  33836. manufacturers, etc.
  33837. Use getIndexChosenByMenu() to find out the type that was chosen.
  33838. */
  33839. void addToMenu (PopupMenu& menu,
  33840. const SortMethod sortMethod) const;
  33841. /** Converts a menu item index that has been chosen into its index in this list.
  33842. Returns -1 if it's not an ID that was used.
  33843. @see addToMenu
  33844. */
  33845. int getIndexChosenByMenu (int menuResultCode) const;
  33846. /** Sorts the list. */
  33847. void sort (const SortMethod method);
  33848. /** Creates some XML that can be used to store the state of this list.
  33849. */
  33850. XmlElement* createXml() const;
  33851. /** Recreates the state of this list from its stored XML format.
  33852. */
  33853. void recreateFromXml (const XmlElement& xml);
  33854. private:
  33855. OwnedArray <PluginDescription> types;
  33856. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KnownPluginList);
  33857. };
  33858. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33859. /*** End of inlined file: juce_KnownPluginList.h ***/
  33860. #endif
  33861. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  33862. #endif
  33863. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  33864. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  33865. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  33866. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  33867. /**
  33868. Scans a directory for plugins, and adds them to a KnownPluginList.
  33869. To use one of these, create it and call scanNextFile() repeatedly, until
  33870. it returns false.
  33871. */
  33872. class JUCE_API PluginDirectoryScanner
  33873. {
  33874. public:
  33875. /**
  33876. Creates a scanner.
  33877. @param listToAddResultsTo this will get the new types added to it.
  33878. @param formatToLookFor this is the type of format that you want to look for
  33879. @param directoriesToSearch the path to search
  33880. @param searchRecursively true to search recursively
  33881. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  33882. be used as a file to store the names of any plugins
  33883. that crash during initialisation. If there are
  33884. any plugins listed in it, then these will always
  33885. be scanned after all other possible files have
  33886. been tried - in this way, even if there's a few
  33887. dodgy plugins in your path, then a couple of rescans
  33888. will still manage to find all the proper plugins.
  33889. It's probably best to choose a file in the user's
  33890. application data directory (alongside your app's
  33891. settings file) for this. The file format it uses
  33892. is just a list of filenames of the modules that
  33893. failed.
  33894. */
  33895. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  33896. AudioPluginFormat& formatToLookFor,
  33897. FileSearchPath directoriesToSearch,
  33898. bool searchRecursively,
  33899. const File& deadMansPedalFile);
  33900. /** Destructor. */
  33901. ~PluginDirectoryScanner();
  33902. /** Tries the next likely-looking file.
  33903. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  33904. re-tested if it's not already in the list, or if the file's modification
  33905. time has changed since the list was created. If dontRescanIfAlreadyInList is
  33906. false, the file will always be reloaded and tested.
  33907. Returns false when there are no more files to try.
  33908. */
  33909. bool scanNextFile (bool dontRescanIfAlreadyInList);
  33910. /** Skips over the next file without scanning it.
  33911. Returns false when there are no more files to try.
  33912. */
  33913. bool skipNextFile();
  33914. /** Returns the description of the plugin that will be scanned during the next
  33915. call to scanNextFile().
  33916. This is handy if you want to show the user which file is currently getting
  33917. scanned.
  33918. */
  33919. const String getNextPluginFileThatWillBeScanned() const;
  33920. /** Returns the estimated progress, between 0 and 1.
  33921. */
  33922. float getProgress() const { return progress; }
  33923. /** This returns a list of all the filenames of things that looked like being
  33924. a plugin file, but which failed to open for some reason.
  33925. */
  33926. const StringArray& getFailedFiles() const noexcept { return failedFiles; }
  33927. private:
  33928. KnownPluginList& list;
  33929. AudioPluginFormat& format;
  33930. StringArray filesOrIdentifiersToScan;
  33931. File deadMansPedalFile;
  33932. StringArray failedFiles;
  33933. int nextIndex;
  33934. float progress;
  33935. StringArray getDeadMansPedalFile();
  33936. void setDeadMansPedalFile (const StringArray& newContents);
  33937. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginDirectoryScanner);
  33938. };
  33939. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  33940. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  33941. #endif
  33942. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  33943. /*** Start of inlined file: juce_PluginListComponent.h ***/
  33944. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  33945. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  33946. /*** Start of inlined file: juce_ListBox.h ***/
  33947. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  33948. #define __JUCE_LISTBOX_JUCEHEADER__
  33949. /*** Start of inlined file: juce_Viewport.h ***/
  33950. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  33951. #define __JUCE_VIEWPORT_JUCEHEADER__
  33952. /*** Start of inlined file: juce_ScrollBar.h ***/
  33953. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  33954. #define __JUCE_SCROLLBAR_JUCEHEADER__
  33955. /*** Start of inlined file: juce_Button.h ***/
  33956. #ifndef __JUCE_BUTTON_JUCEHEADER__
  33957. #define __JUCE_BUTTON_JUCEHEADER__
  33958. /*** Start of inlined file: juce_TooltipWindow.h ***/
  33959. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  33960. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  33961. /*** Start of inlined file: juce_TooltipClient.h ***/
  33962. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33963. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33964. /**
  33965. Components that want to use pop-up tooltips should implement this interface.
  33966. A TooltipWindow will wait for the mouse to hover over a component that
  33967. implements the TooltipClient interface, and when it finds one, it will display
  33968. the tooltip returned by its getTooltip() method.
  33969. @see TooltipWindow, SettableTooltipClient
  33970. */
  33971. class JUCE_API TooltipClient
  33972. {
  33973. public:
  33974. /** Destructor. */
  33975. virtual ~TooltipClient() {}
  33976. /** Returns the string that this object wants to show as its tooltip. */
  33977. virtual const String getTooltip() = 0;
  33978. };
  33979. /**
  33980. An implementation of TooltipClient that stores the tooltip string and a method
  33981. for changing it.
  33982. This makes it easy to add a tooltip to a custom component, by simply adding this
  33983. as a base class and calling setTooltip().
  33984. Many of the Juce widgets already use this as a base class to implement their
  33985. tooltips.
  33986. @see TooltipClient, TooltipWindow
  33987. */
  33988. class JUCE_API SettableTooltipClient : public TooltipClient
  33989. {
  33990. public:
  33991. /** Destructor. */
  33992. virtual ~SettableTooltipClient() {}
  33993. /** Assigns a new tooltip to this object. */
  33994. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  33995. /** Returns the tooltip assigned to this object. */
  33996. virtual const String getTooltip() { return tooltipString; }
  33997. protected:
  33998. SettableTooltipClient() {}
  33999. private:
  34000. String tooltipString;
  34001. };
  34002. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  34003. /*** End of inlined file: juce_TooltipClient.h ***/
  34004. /**
  34005. A window that displays a pop-up tooltip when the mouse hovers over another component.
  34006. To enable tooltips in your app, just create a single instance of a TooltipWindow
  34007. object.
  34008. The TooltipWindow object will then stay invisible, waiting until the mouse
  34009. hovers for the specified length of time - it will then see if it's currently
  34010. over a component which implements the TooltipClient interface, and if so,
  34011. it will make itself visible to show the tooltip in the appropriate place.
  34012. @see TooltipClient, SettableTooltipClient
  34013. */
  34014. class JUCE_API TooltipWindow : public Component,
  34015. private Timer
  34016. {
  34017. public:
  34018. /** Creates a tooltip window.
  34019. Make sure your app only creates one instance of this class, otherwise you'll
  34020. get multiple overlaid tooltips appearing. The window will initially be invisible
  34021. and will make itself visible when it needs to display a tip.
  34022. To change the style of tooltips, see the LookAndFeel class for its tooltip
  34023. methods.
  34024. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  34025. otherwise the tooltip will be added to the given parent
  34026. component.
  34027. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  34028. before a tooltip will be shown
  34029. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  34030. */
  34031. explicit TooltipWindow (Component* parentComponent = nullptr,
  34032. int millisecondsBeforeTipAppears = 700);
  34033. /** Destructor. */
  34034. ~TooltipWindow();
  34035. /** Changes the time before the tip appears.
  34036. This lets you change the value that was set in the constructor.
  34037. */
  34038. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) noexcept;
  34039. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  34040. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34041. methods.
  34042. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34043. */
  34044. enum ColourIds
  34045. {
  34046. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  34047. textColourId = 0x1001c00, /**< The colour to use for the text. */
  34048. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  34049. };
  34050. private:
  34051. int millisecondsBeforeTipAppears;
  34052. Point<int> lastMousePos;
  34053. int mouseClicks;
  34054. unsigned int lastCompChangeTime, lastHideTime;
  34055. Component* lastComponentUnderMouse;
  34056. bool changedCompsSinceShown;
  34057. String tipShowing, lastTipUnderMouse;
  34058. void paint (Graphics& g);
  34059. void mouseEnter (const MouseEvent& e);
  34060. void timerCallback();
  34061. static String getTipFor (Component* c);
  34062. void showFor (const String& tip);
  34063. void hide();
  34064. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TooltipWindow);
  34065. };
  34066. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  34067. /*** End of inlined file: juce_TooltipWindow.h ***/
  34068. #if JUCE_VC6
  34069. #define Listener ButtonListener
  34070. #endif
  34071. /**
  34072. A base class for buttons.
  34073. This contains all the logic for button behaviours such as enabling/disabling,
  34074. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  34075. and radio groups, etc.
  34076. @see TextButton, DrawableButton, ToggleButton
  34077. */
  34078. class JUCE_API Button : public Component,
  34079. public SettableTooltipClient,
  34080. public ApplicationCommandManagerListener,
  34081. public ValueListener,
  34082. private KeyListener
  34083. {
  34084. protected:
  34085. /** Creates a button.
  34086. @param buttonName the text to put in the button (the component's name is also
  34087. initially set to this string, but these can be changed later
  34088. using the setName() and setButtonText() methods)
  34089. */
  34090. explicit Button (const String& buttonName);
  34091. public:
  34092. /** Destructor. */
  34093. virtual ~Button();
  34094. /** Changes the button's text.
  34095. @see getButtonText
  34096. */
  34097. void setButtonText (const String& newText);
  34098. /** Returns the text displayed in the button.
  34099. @see setButtonText
  34100. */
  34101. const String& getButtonText() const { return text; }
  34102. /** Returns true if the button is currently being held down by the mouse.
  34103. @see isOver
  34104. */
  34105. bool isDown() const noexcept;
  34106. /** Returns true if the mouse is currently over the button.
  34107. This will be also be true if the mouse is being held down.
  34108. @see isDown
  34109. */
  34110. bool isOver() const noexcept;
  34111. /** A button has an on/off state associated with it, and this changes that.
  34112. By default buttons are 'off' and for simple buttons that you click to perform
  34113. an action you won't change this. Toggle buttons, however will want to
  34114. change their state when turned on or off.
  34115. @param shouldBeOn whether to set the button's toggle state to be on or
  34116. off. If it's a member of a button group, this will
  34117. always try to turn it on, and to turn off any other
  34118. buttons in the group
  34119. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  34120. the button will be repainted but no notification will
  34121. be sent
  34122. @see getToggleState, setRadioGroupId
  34123. */
  34124. void setToggleState (bool shouldBeOn,
  34125. bool sendChangeNotification);
  34126. /** Returns true if the button in 'on'.
  34127. By default buttons are 'off' and for simple buttons that you click to perform
  34128. an action you won't change this. Toggle buttons, however will want to
  34129. change their state when turned on or off.
  34130. @see setToggleState
  34131. */
  34132. bool getToggleState() const noexcept { return isOn.getValue(); }
  34133. /** Returns the Value object that represents the botton's toggle state.
  34134. You can use this Value object to connect the button's state to external values or setters,
  34135. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34136. your own Value object.
  34137. @see getToggleState, Value
  34138. */
  34139. Value& getToggleStateValue() { return isOn; }
  34140. /** This tells the button to automatically flip the toggle state when
  34141. the button is clicked.
  34142. If set to true, then before the clicked() callback occurs, the toggle-state
  34143. of the button is flipped.
  34144. */
  34145. void setClickingTogglesState (bool shouldToggle) noexcept;
  34146. /** Returns true if this button is set to be an automatic toggle-button.
  34147. This returns the last value that was passed to setClickingTogglesState().
  34148. */
  34149. bool getClickingTogglesState() const noexcept;
  34150. /** Enables the button to act as a member of a mutually-exclusive group
  34151. of 'radio buttons'.
  34152. If the group ID is set to a non-zero number, then this button will
  34153. act as part of a group of buttons with the same ID, only one of
  34154. which can be 'on' at the same time. Note that when it's part of
  34155. a group, clicking a toggle-button that's 'on' won't turn it off.
  34156. To find other buttons with the same ID, this button will search through
  34157. its sibling components for ToggleButtons, so all the buttons for a
  34158. particular group must be placed inside the same parent component.
  34159. Set the group ID back to zero if you want it to act as a normal toggle
  34160. button again.
  34161. @see getRadioGroupId
  34162. */
  34163. void setRadioGroupId (int newGroupId);
  34164. /** Returns the ID of the group to which this button belongs.
  34165. (See setRadioGroupId() for an explanation of this).
  34166. */
  34167. int getRadioGroupId() const noexcept { return radioGroupId; }
  34168. /**
  34169. Used to receive callbacks when a button is clicked.
  34170. @see Button::addListener, Button::removeListener
  34171. */
  34172. class JUCE_API Listener
  34173. {
  34174. public:
  34175. /** Destructor. */
  34176. virtual ~Listener() {}
  34177. /** Called when the button is clicked. */
  34178. virtual void buttonClicked (Button* button) = 0;
  34179. /** Called when the button's state changes. */
  34180. virtual void buttonStateChanged (Button*) {}
  34181. };
  34182. /** Registers a listener to receive events when this button's state changes.
  34183. If the listener is already registered, this will not register it again.
  34184. @see removeListener
  34185. */
  34186. void addListener (Listener* newListener);
  34187. /** Removes a previously-registered button listener
  34188. @see addListener
  34189. */
  34190. void removeListener (Listener* listener);
  34191. /** Causes the button to act as if it's been clicked.
  34192. This will asynchronously make the button draw itself going down and up, and
  34193. will then call back the clicked() method as if mouse was clicked on it.
  34194. @see clicked
  34195. */
  34196. virtual void triggerClick();
  34197. /** Sets a command ID for this button to automatically invoke when it's clicked.
  34198. When the button is pressed, it will use the given manager to trigger the
  34199. command ID.
  34200. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  34201. before this button is. To disable the command triggering, call this method and
  34202. pass 0 for the parameters.
  34203. If generateTooltip is true, then the button's tooltip will be automatically
  34204. generated based on the name of this command and its current shortcut key.
  34205. @see addShortcut, getCommandID
  34206. */
  34207. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  34208. int commandID,
  34209. bool generateTooltip);
  34210. /** Returns the command ID that was set by setCommandToTrigger().
  34211. */
  34212. int getCommandID() const noexcept { return commandID; }
  34213. /** Assigns a shortcut key to trigger the button.
  34214. The button registers itself with its top-level parent component for keypresses.
  34215. Note that a different way of linking buttons to keypresses is by using the
  34216. setCommandToTrigger() method to invoke a command.
  34217. @see clearShortcuts
  34218. */
  34219. void addShortcut (const KeyPress& key);
  34220. /** Removes all key shortcuts that had been set for this button.
  34221. @see addShortcut
  34222. */
  34223. void clearShortcuts();
  34224. /** Returns true if the given keypress is a shortcut for this button.
  34225. @see addShortcut
  34226. */
  34227. bool isRegisteredForShortcut (const KeyPress& key) const;
  34228. /** Sets an auto-repeat speed for the button when it is held down.
  34229. (Auto-repeat is disabled by default).
  34230. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  34231. triggering the next click. If this is zero, auto-repeat
  34232. is disabled
  34233. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  34234. triggered
  34235. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  34236. get faster, the longer the button is held down, up to the
  34237. minimum interval specified here
  34238. */
  34239. void setRepeatSpeed (int initialDelayInMillisecs,
  34240. int repeatDelayInMillisecs,
  34241. int minimumDelayInMillisecs = -1) noexcept;
  34242. /** Sets whether the button click should happen when the mouse is pressed or released.
  34243. By default the button is only considered to have been clicked when the mouse is
  34244. released, but setting this to true will make it call the clicked() method as soon
  34245. as the button is pressed.
  34246. This is useful if the button is being used to show a pop-up menu, as it allows
  34247. the click to be used as a drag onto the menu.
  34248. */
  34249. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) noexcept;
  34250. /** Returns the number of milliseconds since the last time the button
  34251. went into the 'down' state.
  34252. */
  34253. uint32 getMillisecondsSinceButtonDown() const noexcept;
  34254. /** Sets the tooltip for this button.
  34255. @see TooltipClient, TooltipWindow
  34256. */
  34257. void setTooltip (const String& newTooltip);
  34258. // (implementation of the TooltipClient method)
  34259. const String getTooltip();
  34260. /** A combination of these flags are used by setConnectedEdges().
  34261. */
  34262. enum ConnectedEdgeFlags
  34263. {
  34264. ConnectedOnLeft = 1,
  34265. ConnectedOnRight = 2,
  34266. ConnectedOnTop = 4,
  34267. ConnectedOnBottom = 8
  34268. };
  34269. /** Hints about which edges of the button might be connected to adjoining buttons.
  34270. The value passed in is a bitwise combination of any of the values in the
  34271. ConnectedEdgeFlags enum.
  34272. E.g. if you are placing two buttons adjacent to each other, you could use this to
  34273. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  34274. without rounded corners on the edges that connect. It's only a hint, so the
  34275. LookAndFeel can choose to ignore it if it's not relevent for this type of
  34276. button.
  34277. */
  34278. void setConnectedEdges (int connectedEdgeFlags);
  34279. /** Returns the set of flags passed into setConnectedEdges(). */
  34280. int getConnectedEdgeFlags() const noexcept { return connectedEdgeFlags; }
  34281. /** Indicates whether the button adjoins another one on its left edge.
  34282. @see setConnectedEdges
  34283. */
  34284. bool isConnectedOnLeft() const noexcept { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  34285. /** Indicates whether the button adjoins another one on its right edge.
  34286. @see setConnectedEdges
  34287. */
  34288. bool isConnectedOnRight() const noexcept { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  34289. /** Indicates whether the button adjoins another one on its top edge.
  34290. @see setConnectedEdges
  34291. */
  34292. bool isConnectedOnTop() const noexcept { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  34293. /** Indicates whether the button adjoins another one on its bottom edge.
  34294. @see setConnectedEdges
  34295. */
  34296. bool isConnectedOnBottom() const noexcept { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  34297. /** Used by setState(). */
  34298. enum ButtonState
  34299. {
  34300. buttonNormal,
  34301. buttonOver,
  34302. buttonDown
  34303. };
  34304. /** Can be used to force the button into a particular state.
  34305. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  34306. from happening.
  34307. The state that you set here will only last until it is automatically changed when the mouse
  34308. enters or exits the button, or the mouse-button is pressed or released.
  34309. */
  34310. void setState (const ButtonState newState);
  34311. // These are deprecated - please use addListener() and removeListener() instead!
  34312. JUCE_DEPRECATED (void addButtonListener (Listener*));
  34313. JUCE_DEPRECATED (void removeButtonListener (Listener*));
  34314. protected:
  34315. /** This method is called when the button has been clicked.
  34316. Subclasses can override this to perform whatever they actions they need
  34317. to do.
  34318. Alternatively, a ButtonListener can be added to the button, and these listeners
  34319. will be called when the click occurs.
  34320. @see triggerClick
  34321. */
  34322. virtual void clicked();
  34323. /** This method is called when the button has been clicked.
  34324. By default it just calls clicked(), but you might want to override it to handle
  34325. things like clicking when a modifier key is pressed, etc.
  34326. @see ModifierKeys
  34327. */
  34328. virtual void clicked (const ModifierKeys& modifiers);
  34329. /** Subclasses should override this to actually paint the button's contents.
  34330. It's better to use this than the paint method, because it gives you information
  34331. about the over/down state of the button.
  34332. @param g the graphics context to use
  34333. @param isMouseOverButton true if the button is either in the 'over' or
  34334. 'down' state
  34335. @param isButtonDown true if the button should be drawn in the 'down' position
  34336. */
  34337. virtual void paintButton (Graphics& g,
  34338. bool isMouseOverButton,
  34339. bool isButtonDown) = 0;
  34340. /** Called when the button's up/down/over state changes.
  34341. Subclasses can override this if they need to do something special when the button
  34342. goes up or down.
  34343. @see isDown, isOver
  34344. */
  34345. virtual void buttonStateChanged();
  34346. /** @internal */
  34347. virtual void internalClickCallback (const ModifierKeys& modifiers);
  34348. /** @internal */
  34349. void handleCommandMessage (int commandId);
  34350. /** @internal */
  34351. void mouseEnter (const MouseEvent& e);
  34352. /** @internal */
  34353. void mouseExit (const MouseEvent& e);
  34354. /** @internal */
  34355. void mouseDown (const MouseEvent& e);
  34356. /** @internal */
  34357. void mouseDrag (const MouseEvent& e);
  34358. /** @internal */
  34359. void mouseUp (const MouseEvent& e);
  34360. /** @internal */
  34361. bool keyPressed (const KeyPress& key);
  34362. /** @internal */
  34363. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  34364. /** @internal */
  34365. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  34366. /** @internal */
  34367. void paint (Graphics& g);
  34368. /** @internal */
  34369. void parentHierarchyChanged();
  34370. /** @internal */
  34371. void visibilityChanged();
  34372. /** @internal */
  34373. void focusGained (FocusChangeType cause);
  34374. /** @internal */
  34375. void focusLost (FocusChangeType cause);
  34376. /** @internal */
  34377. void enablementChanged();
  34378. /** @internal */
  34379. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  34380. /** @internal */
  34381. void applicationCommandListChanged();
  34382. /** @internal */
  34383. void valueChanged (Value& value);
  34384. private:
  34385. Array <KeyPress> shortcuts;
  34386. WeakReference<Component> keySource;
  34387. String text;
  34388. ListenerList <Listener> buttonListeners;
  34389. class RepeatTimer;
  34390. friend class RepeatTimer;
  34391. friend class ScopedPointer <RepeatTimer>;
  34392. ScopedPointer <RepeatTimer> repeatTimer;
  34393. uint32 buttonPressTime, lastRepeatTime;
  34394. ApplicationCommandManager* commandManagerToUse;
  34395. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  34396. int radioGroupId, commandID, connectedEdgeFlags;
  34397. ButtonState buttonState;
  34398. Value isOn;
  34399. bool lastToggleState : 1;
  34400. bool clickTogglesState : 1;
  34401. bool needsToRelease : 1;
  34402. bool needsRepainting : 1;
  34403. bool isKeyDown : 1;
  34404. bool triggerOnMouseDown : 1;
  34405. bool generateTooltip : 1;
  34406. void repeatTimerCallback();
  34407. RepeatTimer& getRepeatTimer();
  34408. ButtonState updateState();
  34409. ButtonState updateState (bool isOver, bool isDown);
  34410. bool isShortcutPressed() const;
  34411. void turnOffOtherButtonsInGroup (bool sendChangeNotification);
  34412. void flashButtonState();
  34413. void sendClickMessage (const ModifierKeys& modifiers);
  34414. void sendStateMessage();
  34415. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Button);
  34416. };
  34417. #ifndef DOXYGEN
  34418. /** This typedef is just for compatibility with old code and VC6 - newer code should use Button::Listener instead. */
  34419. typedef Button::Listener ButtonListener;
  34420. #endif
  34421. #if JUCE_VC6
  34422. #undef Listener
  34423. #endif
  34424. #endif // __JUCE_BUTTON_JUCEHEADER__
  34425. /*** End of inlined file: juce_Button.h ***/
  34426. /**
  34427. A scrollbar component.
  34428. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  34429. sets the range of values it can represent. Then you can use setCurrentRange() to
  34430. change the position and size of the scrollbar's 'thumb'.
  34431. Registering a ScrollBar::Listener with the scrollbar will allow you to find out when
  34432. the user moves it, and you can use the getCurrentRangeStart() to find out where
  34433. they moved it to.
  34434. The scrollbar will adjust its own visibility according to whether its thumb size
  34435. allows it to actually be scrolled.
  34436. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  34437. instead of handling a scrollbar directly.
  34438. @see ScrollBar::Listener
  34439. */
  34440. class JUCE_API ScrollBar : public Component,
  34441. public AsyncUpdater,
  34442. private Timer
  34443. {
  34444. public:
  34445. /** Creates a Scrollbar.
  34446. @param isVertical whether it should be a vertical or horizontal bar
  34447. @param buttonsAreVisible whether to show the up/down or left/right buttons
  34448. */
  34449. ScrollBar (bool isVertical,
  34450. bool buttonsAreVisible = true);
  34451. /** Destructor. */
  34452. ~ScrollBar();
  34453. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  34454. bool isVertical() const noexcept { return vertical; }
  34455. /** Changes the scrollbar's direction.
  34456. You'll also need to resize the bar appropriately - this just changes its internal
  34457. layout.
  34458. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  34459. */
  34460. void setOrientation (bool shouldBeVertical);
  34461. /** Shows or hides the scrollbar's buttons. */
  34462. void setButtonVisibility (bool buttonsAreVisible);
  34463. /** Tells the scrollbar whether to make itself invisible when not needed.
  34464. The default behaviour is for a scrollbar to become invisible when the thumb
  34465. fills the whole of its range (i.e. when it can't be moved). Setting this
  34466. value to false forces the bar to always be visible.
  34467. @see autoHides()
  34468. */
  34469. void setAutoHide (bool shouldHideWhenFullRange);
  34470. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  34471. as its maximum range.
  34472. @see setAutoHide
  34473. */
  34474. bool autoHides() const noexcept;
  34475. /** Sets the minimum and maximum values that the bar will move between.
  34476. The bar's thumb will always be constrained so that the entire thumb lies
  34477. within this range.
  34478. @see setCurrentRange
  34479. */
  34480. void setRangeLimits (const Range<double>& newRangeLimit);
  34481. /** Sets the minimum and maximum values that the bar will move between.
  34482. The bar's thumb will always be constrained so that the entire thumb lies
  34483. within this range.
  34484. @see setCurrentRange
  34485. */
  34486. void setRangeLimits (double minimum, double maximum);
  34487. /** Returns the current limits on the thumb position.
  34488. @see setRangeLimits
  34489. */
  34490. const Range<double> getRangeLimit() const noexcept { return totalRange; }
  34491. /** Returns the lower value that the thumb can be set to.
  34492. This is the value set by setRangeLimits().
  34493. */
  34494. double getMinimumRangeLimit() const noexcept { return totalRange.getStart(); }
  34495. /** Returns the upper value that the thumb can be set to.
  34496. This is the value set by setRangeLimits().
  34497. */
  34498. double getMaximumRangeLimit() const noexcept { return totalRange.getEnd(); }
  34499. /** Changes the position of the scrollbar's 'thumb'.
  34500. If this method call actually changes the scrollbar's position, it will trigger an
  34501. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  34502. are registered.
  34503. @see getCurrentRange. setCurrentRangeStart
  34504. */
  34505. void setCurrentRange (const Range<double>& newRange);
  34506. /** Changes the position of the scrollbar's 'thumb'.
  34507. This sets both the position and size of the thumb - to just set the position without
  34508. changing the size, you can use setCurrentRangeStart().
  34509. If this method call actually changes the scrollbar's position, it will trigger an
  34510. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  34511. are registered.
  34512. @param newStart the top (or left) of the thumb, in the range
  34513. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  34514. value is beyond these limits, it will be clipped.
  34515. @param newSize the size of the thumb, such that
  34516. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  34517. size is beyond these limits, it will be clipped.
  34518. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  34519. */
  34520. void setCurrentRange (double newStart, double newSize);
  34521. /** Moves the bar's thumb position.
  34522. This will move the thumb position without changing the thumb size. Note
  34523. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  34524. If this method call actually changes the scrollbar's position, it will trigger an
  34525. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  34526. are registered.
  34527. @see setCurrentRange
  34528. */
  34529. void setCurrentRangeStart (double newStart);
  34530. /** Returns the current thumb range.
  34531. @see getCurrentRange, setCurrentRange
  34532. */
  34533. const Range<double> getCurrentRange() const noexcept { return visibleRange; }
  34534. /** Returns the position of the top of the thumb.
  34535. @see getCurrentRange, setCurrentRangeStart
  34536. */
  34537. double getCurrentRangeStart() const noexcept { return visibleRange.getStart(); }
  34538. /** Returns the current size of the thumb.
  34539. @see getCurrentRange, setCurrentRange
  34540. */
  34541. double getCurrentRangeSize() const noexcept { return visibleRange.getLength(); }
  34542. /** Sets the amount by which the up and down buttons will move the bar.
  34543. The value here is in terms of the total range, and is added or subtracted
  34544. from the thumb position when the user clicks an up/down (or left/right) button.
  34545. */
  34546. void setSingleStepSize (double newSingleStepSize);
  34547. /** Moves the scrollbar by a number of single-steps.
  34548. This will move the bar by a multiple of its single-step interval (as
  34549. specified using the setSingleStepSize() method).
  34550. A positive value here will move the bar down or to the right, a negative
  34551. value moves it up or to the left.
  34552. */
  34553. void moveScrollbarInSteps (int howManySteps);
  34554. /** Moves the scroll bar up or down in pages.
  34555. This will move the bar by a multiple of its current thumb size, effectively
  34556. doing a page-up or down.
  34557. A positive value here will move the bar down or to the right, a negative
  34558. value moves it up or to the left.
  34559. */
  34560. void moveScrollbarInPages (int howManyPages);
  34561. /** Scrolls to the top (or left).
  34562. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  34563. */
  34564. void scrollToTop();
  34565. /** Scrolls to the bottom (or right).
  34566. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  34567. */
  34568. void scrollToBottom();
  34569. /** Changes the delay before the up and down buttons autorepeat when they are held
  34570. down.
  34571. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  34572. @see Button::setRepeatSpeed
  34573. */
  34574. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  34575. int repeatDelayInMillisecs,
  34576. int minimumDelayInMillisecs = -1);
  34577. /** A set of colour IDs to use to change the colour of various aspects of the component.
  34578. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34579. methods.
  34580. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34581. */
  34582. enum ColourIds
  34583. {
  34584. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  34585. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  34586. 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. */
  34587. };
  34588. /**
  34589. A class for receiving events from a ScrollBar.
  34590. You can register a ScrollBar::Listener with a ScrollBar using the ScrollBar::addListener()
  34591. method, and it will be called when the bar's position changes.
  34592. @see ScrollBar::addListener, ScrollBar::removeListener
  34593. */
  34594. class JUCE_API Listener
  34595. {
  34596. public:
  34597. /** Destructor. */
  34598. virtual ~Listener() {}
  34599. /** Called when a ScrollBar is moved.
  34600. @param scrollBarThatHasMoved the bar that has moved
  34601. @param newRangeStart the new range start of this bar
  34602. */
  34603. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  34604. double newRangeStart) = 0;
  34605. };
  34606. /** Registers a listener that will be called when the scrollbar is moved. */
  34607. void addListener (Listener* listener);
  34608. /** Deregisters a previously-registered listener. */
  34609. void removeListener (Listener* listener);
  34610. /** @internal */
  34611. bool keyPressed (const KeyPress& key);
  34612. /** @internal */
  34613. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34614. /** @internal */
  34615. void lookAndFeelChanged();
  34616. /** @internal */
  34617. void handleAsyncUpdate();
  34618. /** @internal */
  34619. void mouseDown (const MouseEvent& e);
  34620. /** @internal */
  34621. void mouseDrag (const MouseEvent& e);
  34622. /** @internal */
  34623. void mouseUp (const MouseEvent& e);
  34624. /** @internal */
  34625. void paint (Graphics& g);
  34626. /** @internal */
  34627. void resized();
  34628. private:
  34629. Range <double> totalRange, visibleRange;
  34630. double singleStepSize, dragStartRange;
  34631. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  34632. int dragStartMousePos, lastMousePos;
  34633. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  34634. bool vertical, isDraggingThumb, autohides;
  34635. class ScrollbarButton;
  34636. friend class ScopedPointer<ScrollbarButton>;
  34637. ScopedPointer<ScrollbarButton> upButton, downButton;
  34638. ListenerList <Listener> listeners;
  34639. void updateThumbPosition();
  34640. void timerCallback();
  34641. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollBar);
  34642. };
  34643. /** This typedef is just for compatibility with old code - newer code should use the ScrollBar::Listener class directly. */
  34644. typedef ScrollBar::Listener ScrollBarListener;
  34645. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  34646. /*** End of inlined file: juce_ScrollBar.h ***/
  34647. /**
  34648. A Viewport is used to contain a larger child component, and allows the child
  34649. to be automatically scrolled around.
  34650. To use a Viewport, just create one and set the component that goes inside it
  34651. using the setViewedComponent() method. When the child component changes size,
  34652. the Viewport will adjust its scrollbars accordingly.
  34653. A subclass of the viewport can be created which will receive calls to its
  34654. visibleAreaChanged() method when the subcomponent changes position or size.
  34655. */
  34656. class JUCE_API Viewport : public Component,
  34657. private ComponentListener,
  34658. private ScrollBar::Listener
  34659. {
  34660. public:
  34661. /** Creates a Viewport.
  34662. The viewport is initially empty - use the setViewedComponent() method to
  34663. add a child component for it to manage.
  34664. */
  34665. explicit Viewport (const String& componentName = String::empty);
  34666. /** Destructor. */
  34667. ~Viewport();
  34668. /** Sets the component that this viewport will contain and scroll around.
  34669. This will add the given component to this Viewport and position it at (0, 0).
  34670. (Don't add or remove any child components directly using the normal
  34671. Component::addChildComponent() methods).
  34672. @param newViewedComponent the component to add to this viewport, or null to remove
  34673. the current component.
  34674. @param deleteComponentWhenNoLongerNeeded if true, the component will be deleted
  34675. automatically when the viewport is deleted or when a different
  34676. component is added. If false, the caller must manage the lifetime
  34677. of the component
  34678. @see getViewedComponent
  34679. */
  34680. void setViewedComponent (Component* newViewedComponent,
  34681. bool deleteComponentWhenNoLongerNeeded = true);
  34682. /** Returns the component that's currently being used inside the Viewport.
  34683. @see setViewedComponent
  34684. */
  34685. Component* getViewedComponent() const noexcept { return contentComp; }
  34686. /** Changes the position of the viewed component.
  34687. The inner component will be moved so that the pixel at the top left of
  34688. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  34689. within the inner component.
  34690. This will update the scrollbars and might cause a call to visibleAreaChanged().
  34691. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  34692. */
  34693. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  34694. /** Changes the position of the viewed component.
  34695. The inner component will be moved so that the pixel at the top left of
  34696. the viewport will be the pixel at the specified coordinates within the
  34697. inner component.
  34698. This will update the scrollbars and might cause a call to visibleAreaChanged().
  34699. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  34700. */
  34701. void setViewPosition (const Point<int>& newPosition);
  34702. /** Changes the view position as a proportion of the distance it can move.
  34703. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  34704. visible area in the top-left, and (1, 1) would put it as far down and
  34705. to the right as it's possible to go whilst keeping the child component
  34706. on-screen.
  34707. */
  34708. void setViewPositionProportionately (double proportionX, double proportionY);
  34709. /** If the specified position is at the edges of the viewport, this method scrolls
  34710. the viewport to bring that position nearer to the centre.
  34711. Call this if you're dragging an object inside a viewport and want to make it scroll
  34712. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  34713. useful when auto-scrolling.
  34714. @param mouseX the x position, relative to the Viewport's top-left
  34715. @param mouseY the y position, relative to the Viewport's top-left
  34716. @param distanceFromEdge specifies how close to an edge the position needs to be
  34717. before the viewport should scroll in that direction
  34718. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  34719. to scroll by.
  34720. @returns true if the viewport was scrolled
  34721. */
  34722. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  34723. /** Returns the position within the child component of the top-left of its visible area.
  34724. */
  34725. const Point<int> getViewPosition() const noexcept { return lastVisibleArea.getPosition(); }
  34726. /** Returns the position within the child component of the top-left of its visible area.
  34727. @see getViewWidth, setViewPosition
  34728. */
  34729. int getViewPositionX() const noexcept { return lastVisibleArea.getX(); }
  34730. /** Returns the position within the child component of the top-left of its visible area.
  34731. @see getViewHeight, setViewPosition
  34732. */
  34733. int getViewPositionY() const noexcept { return lastVisibleArea.getY(); }
  34734. /** Returns the width of the visible area of the child component.
  34735. This may be less than the width of this Viewport if there's a vertical scrollbar
  34736. or if the child component is itself smaller.
  34737. */
  34738. int getViewWidth() const noexcept { return lastVisibleArea.getWidth(); }
  34739. /** Returns the height of the visible area of the child component.
  34740. This may be less than the height of this Viewport if there's a horizontal scrollbar
  34741. or if the child component is itself smaller.
  34742. */
  34743. int getViewHeight() const noexcept { return lastVisibleArea.getHeight(); }
  34744. /** Returns the width available within this component for the contents.
  34745. This will be the width of the viewport component minus the width of a
  34746. vertical scrollbar (if visible).
  34747. */
  34748. int getMaximumVisibleWidth() const;
  34749. /** Returns the height available within this component for the contents.
  34750. This will be the height of the viewport component minus the space taken up
  34751. by a horizontal scrollbar (if visible).
  34752. */
  34753. int getMaximumVisibleHeight() const;
  34754. /** Callback method that is called when the visible area changes.
  34755. This will be called when the visible area is moved either be scrolling or
  34756. by calls to setViewPosition(), etc.
  34757. */
  34758. virtual void visibleAreaChanged (const Rectangle<int>& newVisibleArea);
  34759. /** Turns scrollbars on or off.
  34760. If set to false, the scrollbars won't ever appear. When true (the default)
  34761. they will appear only when needed.
  34762. */
  34763. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  34764. bool showHorizontalScrollbarIfNeeded);
  34765. /** True if the vertical scrollbar is enabled.
  34766. @see setScrollBarsShown
  34767. */
  34768. bool isVerticalScrollBarShown() const noexcept { return showVScrollbar; }
  34769. /** True if the horizontal scrollbar is enabled.
  34770. @see setScrollBarsShown
  34771. */
  34772. bool isHorizontalScrollBarShown() const noexcept { return showHScrollbar; }
  34773. /** Changes the width of the scrollbars.
  34774. If this isn't specified, the default width from the LookAndFeel class will be used.
  34775. @see LookAndFeel::getDefaultScrollbarWidth
  34776. */
  34777. void setScrollBarThickness (int thickness);
  34778. /** Returns the thickness of the scrollbars.
  34779. @see setScrollBarThickness
  34780. */
  34781. int getScrollBarThickness() const;
  34782. /** Changes the distance that a single-step click on a scrollbar button
  34783. will move the viewport.
  34784. */
  34785. void setSingleStepSizes (int stepX, int stepY);
  34786. /** Shows or hides the buttons on any scrollbars that are used.
  34787. @see ScrollBar::setButtonVisibility
  34788. */
  34789. void setScrollBarButtonVisibility (bool buttonsVisible);
  34790. /** Returns a pointer to the scrollbar component being used.
  34791. Handy if you need to customise the bar somehow.
  34792. */
  34793. ScrollBar* getVerticalScrollBar() noexcept { return &verticalScrollBar; }
  34794. /** Returns a pointer to the scrollbar component being used.
  34795. Handy if you need to customise the bar somehow.
  34796. */
  34797. ScrollBar* getHorizontalScrollBar() noexcept { return &horizontalScrollBar; }
  34798. /** @internal */
  34799. void resized();
  34800. /** @internal */
  34801. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  34802. /** @internal */
  34803. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34804. /** @internal */
  34805. bool keyPressed (const KeyPress& key);
  34806. /** @internal */
  34807. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  34808. /** @internal */
  34809. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34810. private:
  34811. WeakReference<Component> contentComp;
  34812. Rectangle<int> lastVisibleArea;
  34813. int scrollBarThickness;
  34814. int singleStepX, singleStepY;
  34815. bool showHScrollbar, showVScrollbar, deleteContent;
  34816. Component contentHolder;
  34817. ScrollBar verticalScrollBar;
  34818. ScrollBar horizontalScrollBar;
  34819. void updateVisibleArea();
  34820. void deleteContentComp();
  34821. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  34822. // If you get an error here, it's because this method's parameters have changed! See the new definition above..
  34823. virtual int visibleAreaChanged (int, int, int, int) { return 0; }
  34824. #endif
  34825. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Viewport);
  34826. };
  34827. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  34828. /*** End of inlined file: juce_Viewport.h ***/
  34829. class ListViewport;
  34830. /**
  34831. A subclass of this is used to drive a ListBox.
  34832. @see ListBox
  34833. */
  34834. class JUCE_API ListBoxModel
  34835. {
  34836. public:
  34837. /** Destructor. */
  34838. virtual ~ListBoxModel() {}
  34839. /** This has to return the number of items in the list.
  34840. @see ListBox::getNumRows()
  34841. */
  34842. virtual int getNumRows() = 0;
  34843. /** This method must be implemented to draw a row of the list.
  34844. */
  34845. virtual void paintListBoxItem (int rowNumber,
  34846. Graphics& g,
  34847. int width, int height,
  34848. bool rowIsSelected) = 0;
  34849. /** This is used to create or update a custom component to go in a row of the list.
  34850. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  34851. and handle mouse clicks with listBoxItemClicked().
  34852. This method will be called whenever a custom component might need to be updated - e.g.
  34853. when the table is changed, or TableListBox::updateContent() is called.
  34854. If you don't need a custom component for the specified row, then return 0.
  34855. If you do want a custom component, and the existingComponentToUpdate is null, then
  34856. this method must create a suitable new component and return it.
  34857. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  34858. by this method. In this case, the method must either update it to make sure it's correctly representing
  34859. the given row (which may be different from the one that the component was created for), or it can
  34860. delete this component and return a new one.
  34861. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  34862. */
  34863. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  34864. Component* existingComponentToUpdate);
  34865. /** This can be overridden to react to the user clicking on a row.
  34866. @see listBoxItemDoubleClicked
  34867. */
  34868. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  34869. /** This can be overridden to react to the user double-clicking on a row.
  34870. @see listBoxItemClicked
  34871. */
  34872. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  34873. /** This can be overridden to react to the user double-clicking on a part of the list where
  34874. there are no rows.
  34875. @see listBoxItemClicked
  34876. */
  34877. virtual void backgroundClicked();
  34878. /** Override this to be informed when rows are selected or deselected.
  34879. This will be called whenever a row is selected or deselected. If a range of
  34880. rows is selected all at once, this will just be called once for that event.
  34881. @param lastRowSelected the last row that the user selected. If no
  34882. rows are currently selected, this may be -1.
  34883. */
  34884. virtual void selectedRowsChanged (int lastRowSelected);
  34885. /** Override this to be informed when the delete key is pressed.
  34886. If no rows are selected when they press the key, this won't be called.
  34887. @param lastRowSelected the last row that had been selected when they pressed the
  34888. key - if there are multiple selections, this might not be
  34889. very useful
  34890. */
  34891. virtual void deleteKeyPressed (int lastRowSelected);
  34892. /** Override this to be informed when the return key is pressed.
  34893. If no rows are selected when they press the key, this won't be called.
  34894. @param lastRowSelected the last row that had been selected when they pressed the
  34895. key - if there are multiple selections, this might not be
  34896. very useful
  34897. */
  34898. virtual void returnKeyPressed (int lastRowSelected);
  34899. /** Override this to be informed when the list is scrolled.
  34900. This might be caused by the user moving the scrollbar, or by programmatic changes
  34901. to the list position.
  34902. */
  34903. virtual void listWasScrolled();
  34904. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  34905. If this returns a non-null variant then when the user drags a row, the listbox will
  34906. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  34907. a drag-and-drop operation, using this string as the source description, with the listbox
  34908. itself as the source component.
  34909. @see DragAndDropContainer::startDragging
  34910. */
  34911. virtual const var getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  34912. /** You can override this to provide tool tips for specific rows.
  34913. @see TooltipClient
  34914. */
  34915. virtual const String getTooltipForRow (int row);
  34916. };
  34917. /**
  34918. A list of items that can be scrolled vertically.
  34919. To create a list, you'll need to create a subclass of ListBoxModel. This can
  34920. either paint each row of the list and respond to events via callbacks, or for
  34921. more specialised tasks, it can supply a custom component to fill each row.
  34922. @see ComboBox, TableListBox
  34923. */
  34924. class JUCE_API ListBox : public Component,
  34925. public SettableTooltipClient
  34926. {
  34927. public:
  34928. /** Creates a ListBox.
  34929. The model pointer passed-in can be null, in which case you can set it later
  34930. with setModel().
  34931. */
  34932. ListBox (const String& componentName = String::empty,
  34933. ListBoxModel* model = 0);
  34934. /** Destructor. */
  34935. ~ListBox();
  34936. /** Changes the current data model to display. */
  34937. void setModel (ListBoxModel* newModel);
  34938. /** Returns the current list model. */
  34939. ListBoxModel* getModel() const noexcept { return model; }
  34940. /** Causes the list to refresh its content.
  34941. Call this when the number of rows in the list changes, or if you want it
  34942. to call refreshComponentForRow() on all the row components.
  34943. This must only be called from the main message thread.
  34944. */
  34945. void updateContent();
  34946. /** Turns on multiple-selection of rows.
  34947. By default this is disabled.
  34948. When your row component gets clicked you'll need to call the
  34949. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  34950. clicked and to get it to do the appropriate selection based on whether
  34951. the ctrl/shift keys are held down.
  34952. */
  34953. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  34954. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  34955. This function is here primarily for the ComboBox class to use, but might be
  34956. useful for some other purpose too.
  34957. */
  34958. void setMouseMoveSelectsRows (bool shouldSelect);
  34959. /** Selects a row.
  34960. If the row is already selected, this won't do anything.
  34961. @param rowNumber the row to select
  34962. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  34963. the selected row is off-screen, it'll scroll to make
  34964. sure that row is on-screen
  34965. @param deselectOthersFirst if true and there are multiple selections, these will
  34966. first be deselected before this item is selected
  34967. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  34968. deselectAllRows, selectRangeOfRows
  34969. */
  34970. void selectRow (int rowNumber,
  34971. bool dontScrollToShowThisRow = false,
  34972. bool deselectOthersFirst = true);
  34973. /** Selects a set of rows.
  34974. This will add these rows to the current selection, so you might need to
  34975. clear the current selection first with deselectAllRows()
  34976. @param firstRow the first row to select (inclusive)
  34977. @param lastRow the last row to select (inclusive)
  34978. */
  34979. void selectRangeOfRows (int firstRow,
  34980. int lastRow);
  34981. /** Deselects a row.
  34982. If it's not currently selected, this will do nothing.
  34983. @see selectRow, deselectAllRows
  34984. */
  34985. void deselectRow (int rowNumber);
  34986. /** Deselects any currently selected rows.
  34987. @see deselectRow
  34988. */
  34989. void deselectAllRows();
  34990. /** Selects or deselects a row.
  34991. If the row's currently selected, this deselects it, and vice-versa.
  34992. */
  34993. void flipRowSelection (int rowNumber);
  34994. /** Returns a sparse set indicating the rows that are currently selected.
  34995. @see setSelectedRows
  34996. */
  34997. const SparseSet<int> getSelectedRows() const;
  34998. /** Sets the rows that should be selected, based on an explicit set of ranges.
  34999. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  35000. method will be called. If it's false, no notification will be sent to the model.
  35001. @see getSelectedRows
  35002. */
  35003. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  35004. bool sendNotificationEventToModel = true);
  35005. /** Checks whether a row is selected.
  35006. */
  35007. bool isRowSelected (int rowNumber) const;
  35008. /** Returns the number of rows that are currently selected.
  35009. @see getSelectedRow, isRowSelected, getLastRowSelected
  35010. */
  35011. int getNumSelectedRows() const;
  35012. /** Returns the row number of a selected row.
  35013. This will return the row number of the Nth selected row. The row numbers returned will
  35014. be sorted in order from low to high.
  35015. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  35016. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  35017. selected
  35018. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  35019. */
  35020. int getSelectedRow (int index = 0) const;
  35021. /** Returns the last row that the user selected.
  35022. This isn't the same as the highest row number that is currently selected - if the user
  35023. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  35024. If nothing is selected, it will return -1.
  35025. */
  35026. int getLastRowSelected() const;
  35027. /** Multiply-selects rows based on the modifier keys.
  35028. If no modifier keys are down, this will select the given row and
  35029. deselect any others.
  35030. If the ctrl (or command on the Mac) key is down, it'll flip the
  35031. state of the selected row.
  35032. If the shift key is down, it'll select up to the given row from the
  35033. last row selected.
  35034. @see selectRow
  35035. */
  35036. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  35037. const ModifierKeys& modifiers,
  35038. bool isMouseUpEvent);
  35039. /** Scrolls the list to a particular position.
  35040. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  35041. 1.0 scrolls to the bottom.
  35042. If the total number of rows all fit onto the screen at once, then this
  35043. method won't do anything.
  35044. @see getVerticalPosition
  35045. */
  35046. void setVerticalPosition (double newProportion);
  35047. /** Returns the current vertical position as a proportion of the total.
  35048. This can be used in conjunction with setVerticalPosition() to save and restore
  35049. the list's position. It returns a value in the range 0 to 1.
  35050. @see setVerticalPosition
  35051. */
  35052. double getVerticalPosition() const;
  35053. /** Scrolls if necessary to make sure that a particular row is visible.
  35054. */
  35055. void scrollToEnsureRowIsOnscreen (int row);
  35056. /** Returns a pointer to the scrollbar.
  35057. (Unlikely to be useful for most people).
  35058. */
  35059. ScrollBar* getVerticalScrollBar() const noexcept;
  35060. /** Returns a pointer to the scrollbar.
  35061. (Unlikely to be useful for most people).
  35062. */
  35063. ScrollBar* getHorizontalScrollBar() const noexcept;
  35064. /** Finds the row index that contains a given x,y position.
  35065. The position is relative to the ListBox's top-left.
  35066. If no row exists at this position, the method will return -1.
  35067. @see getComponentForRowNumber
  35068. */
  35069. int getRowContainingPosition (int x, int y) const noexcept;
  35070. /** Finds a row index that would be the most suitable place to insert a new
  35071. item for a given position.
  35072. This is useful when the user is e.g. dragging and dropping onto the listbox,
  35073. because it lets you easily choose the best position to insert the item that
  35074. they drop, based on where they drop it.
  35075. If the position is out of range, this will return -1. If the position is
  35076. beyond the end of the list, it will return getNumRows() to indicate the end
  35077. of the list.
  35078. @see getComponentForRowNumber
  35079. */
  35080. int getInsertionIndexForPosition (int x, int y) const noexcept;
  35081. /** Returns the position of one of the rows, relative to the top-left of
  35082. the listbox.
  35083. This may be off-screen, and the range of the row number that is passed-in is
  35084. not checked to see if it's a valid row.
  35085. */
  35086. const Rectangle<int> getRowPosition (int rowNumber,
  35087. bool relativeToComponentTopLeft) const noexcept;
  35088. /** Finds the row component for a given row in the list.
  35089. The component returned will have been created using createRowComponent().
  35090. If the component for this row is off-screen or if the row is out-of-range,
  35091. this will return 0.
  35092. @see getRowContainingPosition
  35093. */
  35094. Component* getComponentForRowNumber (int rowNumber) const noexcept;
  35095. /** Returns the row number that the given component represents.
  35096. If the component isn't one of the list's rows, this will return -1.
  35097. */
  35098. int getRowNumberOfComponent (Component* rowComponent) const noexcept;
  35099. /** Returns the width of a row (which may be less than the width of this component
  35100. if there's a scrollbar).
  35101. */
  35102. int getVisibleRowWidth() const noexcept;
  35103. /** Sets the height of each row in the list.
  35104. The default height is 22 pixels.
  35105. @see getRowHeight
  35106. */
  35107. void setRowHeight (int newHeight);
  35108. /** Returns the height of a row in the list.
  35109. @see setRowHeight
  35110. */
  35111. int getRowHeight() const noexcept { return rowHeight; }
  35112. /** Returns the number of rows actually visible.
  35113. This is the number of whole rows which will fit on-screen, so the value might
  35114. be more than the actual number of rows in the list.
  35115. */
  35116. int getNumRowsOnScreen() const noexcept;
  35117. /** A set of colour IDs to use to change the colour of various aspects of the label.
  35118. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35119. methods.
  35120. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35121. */
  35122. enum ColourIds
  35123. {
  35124. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  35125. Make this transparent if you don't want the background to be filled. */
  35126. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  35127. Make this transparent to not have an outline. */
  35128. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  35129. };
  35130. /** Sets the thickness of a border that will be drawn around the box.
  35131. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  35132. @see outlineColourId
  35133. */
  35134. void setOutlineThickness (int outlineThickness);
  35135. /** Returns the thickness of outline that will be drawn around the listbox.
  35136. @see setOutlineColour
  35137. */
  35138. int getOutlineThickness() const noexcept { return outlineThickness; }
  35139. /** Sets a component that the list should use as a header.
  35140. This will position the given component at the top of the list, maintaining the
  35141. height of the component passed-in, but rescaling it horizontally to match the
  35142. width of the items in the listbox.
  35143. The component will be deleted when setHeaderComponent() is called with a
  35144. different component, or when the listbox is deleted.
  35145. */
  35146. void setHeaderComponent (Component* newHeaderComponent);
  35147. /** Changes the width of the rows in the list.
  35148. This can be used to make the list's row components wider than the list itself - the
  35149. width of the rows will be either the width of the list or this value, whichever is
  35150. greater, and if the rows become wider than the list, a horizontal scrollbar will
  35151. appear.
  35152. The default value for this is 0, which means that the rows will always
  35153. be the same width as the list.
  35154. */
  35155. void setMinimumContentWidth (int newMinimumWidth);
  35156. /** Returns the space currently available for the row items, taking into account
  35157. borders, scrollbars, etc.
  35158. */
  35159. int getVisibleContentWidth() const noexcept;
  35160. /** Repaints one of the rows.
  35161. This is a lightweight alternative to calling updateContent, and just causes a
  35162. repaint of the row's area.
  35163. */
  35164. void repaintRow (int rowNumber) noexcept;
  35165. /** This fairly obscure method creates an image that just shows the currently
  35166. selected row components.
  35167. It's a handy method for doing drag-and-drop, as it can be passed to the
  35168. DragAndDropContainer for use as the drag image.
  35169. Note that it will make the row components temporarily invisible, so if you're
  35170. using custom components this could affect them if they're sensitive to that
  35171. sort of thing.
  35172. @see Component::createComponentSnapshot
  35173. */
  35174. virtual const Image createSnapshotOfSelectedRows (int& x, int& y);
  35175. /** Returns the viewport that this ListBox uses.
  35176. You may need to use this to change parameters such as whether scrollbars
  35177. are shown, etc.
  35178. */
  35179. Viewport* getViewport() const noexcept;
  35180. /** @internal */
  35181. bool keyPressed (const KeyPress& key);
  35182. /** @internal */
  35183. bool keyStateChanged (bool isKeyDown);
  35184. /** @internal */
  35185. void paint (Graphics& g);
  35186. /** @internal */
  35187. void paintOverChildren (Graphics& g);
  35188. /** @internal */
  35189. void resized();
  35190. /** @internal */
  35191. void visibilityChanged();
  35192. /** @internal */
  35193. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  35194. /** @internal */
  35195. void mouseMove (const MouseEvent&);
  35196. /** @internal */
  35197. void mouseExit (const MouseEvent&);
  35198. /** @internal */
  35199. void mouseUp (const MouseEvent&);
  35200. /** @internal */
  35201. void colourChanged();
  35202. /** @internal */
  35203. void startDragAndDrop (const MouseEvent& e, const var& dragDescription, bool allowDraggingToOtherWindows = true);
  35204. private:
  35205. friend class ListViewport;
  35206. friend class TableListBox;
  35207. ListBoxModel* model;
  35208. ScopedPointer<ListViewport> viewport;
  35209. ScopedPointer<Component> headerComponent;
  35210. int totalItems, rowHeight, minimumRowWidth;
  35211. int outlineThickness;
  35212. int lastRowSelected;
  35213. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  35214. SparseSet <int> selected;
  35215. void selectRowInternal (int rowNumber,
  35216. bool dontScrollToShowThisRow,
  35217. bool deselectOthersFirst,
  35218. bool isMouseClick);
  35219. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBox);
  35220. };
  35221. #endif // __JUCE_LISTBOX_JUCEHEADER__
  35222. /*** End of inlined file: juce_ListBox.h ***/
  35223. /*** Start of inlined file: juce_TextButton.h ***/
  35224. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  35225. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  35226. /**
  35227. A button that uses the standard lozenge-shaped background with a line of
  35228. text on it.
  35229. @see Button, DrawableButton
  35230. */
  35231. class JUCE_API TextButton : public Button
  35232. {
  35233. public:
  35234. /** Creates a TextButton.
  35235. @param buttonName the text to put in the button (the component's name is also
  35236. initially set to this string, but these can be changed later
  35237. using the setName() and setButtonText() methods)
  35238. @param toolTip an optional string to use as a toolip
  35239. @see Button
  35240. */
  35241. TextButton (const String& buttonName = String::empty,
  35242. const String& toolTip = String::empty);
  35243. /** Destructor. */
  35244. ~TextButton();
  35245. /** A set of colour IDs to use to change the colour of various aspects of the button.
  35246. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35247. methods.
  35248. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35249. */
  35250. enum ColourIds
  35251. {
  35252. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  35253. 'off'). The look-and-feel class might re-interpret this to add
  35254. effects, etc. */
  35255. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  35256. 'on'). The look-and-feel class might re-interpret this to add
  35257. effects, etc. */
  35258. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  35259. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  35260. };
  35261. /** Resizes the button to fit neatly around its current text.
  35262. If newHeight is >= 0, the button's height will be changed to this
  35263. value. If it's less than zero, its height will be unaffected.
  35264. */
  35265. void changeWidthToFitText (int newHeight = -1);
  35266. /** This can be overridden to use different fonts than the default one.
  35267. Note that you'll need to set the font's size appropriately, too.
  35268. */
  35269. virtual const Font getFont();
  35270. protected:
  35271. /** @internal */
  35272. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  35273. /** @internal */
  35274. void colourChanged();
  35275. private:
  35276. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextButton);
  35277. };
  35278. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  35279. /*** End of inlined file: juce_TextButton.h ***/
  35280. /**
  35281. A component displaying a list of plugins, with options to scan for them,
  35282. add, remove and sort them.
  35283. */
  35284. class JUCE_API PluginListComponent : public Component,
  35285. public ListBoxModel,
  35286. public ChangeListener,
  35287. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  35288. public Timer
  35289. {
  35290. public:
  35291. /**
  35292. Creates the list component.
  35293. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  35294. The properties file, if supplied, is used to store the user's last search paths.
  35295. */
  35296. PluginListComponent (KnownPluginList& listToRepresent,
  35297. const File& deadMansPedalFile,
  35298. PropertiesFile* propertiesToUse);
  35299. /** Destructor. */
  35300. ~PluginListComponent();
  35301. /** @internal */
  35302. void resized();
  35303. /** @internal */
  35304. bool isInterestedInFileDrag (const StringArray& files);
  35305. /** @internal */
  35306. void filesDropped (const StringArray& files, int, int);
  35307. /** @internal */
  35308. int getNumRows();
  35309. /** @internal */
  35310. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  35311. /** @internal */
  35312. void deleteKeyPressed (int lastRowSelected);
  35313. /** @internal */
  35314. void buttonClicked (Button* b);
  35315. /** @internal */
  35316. void changeListenerCallback (ChangeBroadcaster*);
  35317. /** @internal */
  35318. void timerCallback();
  35319. private:
  35320. KnownPluginList& list;
  35321. File deadMansPedalFile;
  35322. ListBox listBox;
  35323. TextButton optionsButton;
  35324. PropertiesFile* propertiesToUse;
  35325. int typeToScan;
  35326. void scanFor (AudioPluginFormat* format);
  35327. static void optionsMenuStaticCallback (int result, PluginListComponent*);
  35328. void optionsMenuCallback (int result);
  35329. void updateList();
  35330. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginListComponent);
  35331. };
  35332. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35333. /*** End of inlined file: juce_PluginListComponent.h ***/
  35334. #endif
  35335. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  35336. #endif
  35337. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  35338. #endif
  35339. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  35340. #endif
  35341. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35342. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  35343. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35344. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35345. /**
  35346. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  35347. Use one of these objects if you want to wire-up a set of AudioProcessors
  35348. and play back the result.
  35349. Processors can be added to the graph as "nodes" using addNode(), and once
  35350. added, you can connect any of their input or output channels to other
  35351. nodes using addConnection().
  35352. To play back a graph through an audio device, you might want to use an
  35353. AudioProcessorPlayer object.
  35354. */
  35355. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  35356. public AsyncUpdater
  35357. {
  35358. public:
  35359. /** Creates an empty graph.
  35360. */
  35361. AudioProcessorGraph();
  35362. /** Destructor.
  35363. Any processor objects that have been added to the graph will also be deleted.
  35364. */
  35365. ~AudioProcessorGraph();
  35366. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  35367. To create a node, call AudioProcessorGraph::addNode().
  35368. */
  35369. class JUCE_API Node : public ReferenceCountedObject
  35370. {
  35371. public:
  35372. /** The ID number assigned to this node.
  35373. This is assigned by the graph that owns it, and can't be changed.
  35374. */
  35375. const uint32 nodeId;
  35376. /** The actual processor object that this node represents. */
  35377. AudioProcessor* getProcessor() const noexcept { return processor; }
  35378. /** A set of user-definable properties that are associated with this node.
  35379. This can be used to attach values to the node for whatever purpose seems
  35380. useful. For example, you might store an x and y position if your application
  35381. is displaying the nodes on-screen.
  35382. */
  35383. NamedValueSet properties;
  35384. /** A convenient typedef for referring to a pointer to a node object.
  35385. */
  35386. typedef ReferenceCountedObjectPtr <Node> Ptr;
  35387. private:
  35388. friend class AudioProcessorGraph;
  35389. const ScopedPointer<AudioProcessor> processor;
  35390. bool isPrepared;
  35391. Node (uint32 nodeId, AudioProcessor* processor) noexcept;
  35392. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  35393. void unprepare();
  35394. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Node);
  35395. };
  35396. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  35397. To create a connection, use AudioProcessorGraph::addConnection().
  35398. */
  35399. struct JUCE_API Connection
  35400. {
  35401. public:
  35402. Connection (uint32 sourceNodeId, int sourceChannelIndex,
  35403. uint32 destNodeId, int destChannelIndex) noexcept;
  35404. /** The ID number of the node which is the input source for this connection.
  35405. @see AudioProcessorGraph::getNodeForId
  35406. */
  35407. uint32 sourceNodeId;
  35408. /** The index of the output channel of the source node from which this
  35409. connection takes its data.
  35410. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35411. it is referring to the source node's midi output. Otherwise, it is the zero-based
  35412. index of an audio output channel in the source node.
  35413. */
  35414. int sourceChannelIndex;
  35415. /** The ID number of the node which is the destination for this connection.
  35416. @see AudioProcessorGraph::getNodeForId
  35417. */
  35418. uint32 destNodeId;
  35419. /** The index of the input channel of the destination node to which this
  35420. connection delivers its data.
  35421. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35422. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  35423. index of an audio input channel in the destination node.
  35424. */
  35425. int destChannelIndex;
  35426. private:
  35427. JUCE_LEAK_DETECTOR (Connection);
  35428. };
  35429. /** Deletes all nodes and connections from this graph.
  35430. Any processor objects in the graph will be deleted.
  35431. */
  35432. void clear();
  35433. /** Returns the number of nodes in the graph. */
  35434. int getNumNodes() const { return nodes.size(); }
  35435. /** Returns a pointer to one of the nodes in the graph.
  35436. This will return 0 if the index is out of range.
  35437. @see getNodeForId
  35438. */
  35439. Node* getNode (const int index) const { return nodes [index]; }
  35440. /** Searches the graph for a node with the given ID number and returns it.
  35441. If no such node was found, this returns 0.
  35442. @see getNode
  35443. */
  35444. Node* getNodeForId (const uint32 nodeId) const;
  35445. /** Adds a node to the graph.
  35446. This creates a new node in the graph, for the specified processor. Once you have
  35447. added a processor to the graph, the graph owns it and will delete it later when
  35448. it is no longer needed.
  35449. The optional nodeId parameter lets you specify an ID to use for the node, but
  35450. if the value is already in use, this new node will overwrite the old one.
  35451. If this succeeds, it returns a pointer to the newly-created node.
  35452. */
  35453. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  35454. /** Deletes a node within the graph which has the specified ID.
  35455. This will also delete any connections that are attached to this node.
  35456. */
  35457. bool removeNode (uint32 nodeId);
  35458. /** Returns the number of connections in the graph. */
  35459. int getNumConnections() const { return connections.size(); }
  35460. /** Returns a pointer to one of the connections in the graph. */
  35461. const Connection* getConnection (int index) const { return connections [index]; }
  35462. /** Searches for a connection between some specified channels.
  35463. If no such connection is found, this returns 0.
  35464. */
  35465. const Connection* getConnectionBetween (uint32 sourceNodeId,
  35466. int sourceChannelIndex,
  35467. uint32 destNodeId,
  35468. int destChannelIndex) const;
  35469. /** Returns true if there is a connection between any of the channels of
  35470. two specified nodes.
  35471. */
  35472. bool isConnected (uint32 possibleSourceNodeId,
  35473. uint32 possibleDestNodeId) const;
  35474. /** Returns true if it would be legal to connect the specified points.
  35475. */
  35476. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  35477. uint32 destNodeId, int destChannelIndex) const;
  35478. /** Attempts to connect two specified channels of two nodes.
  35479. If this isn't allowed (e.g. because you're trying to connect a midi channel
  35480. to an audio one or other such nonsense), then it'll return false.
  35481. */
  35482. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  35483. uint32 destNodeId, int destChannelIndex);
  35484. /** Deletes the connection with the specified index.
  35485. Returns true if a connection was actually deleted.
  35486. */
  35487. void removeConnection (int index);
  35488. /** Deletes any connection between two specified points.
  35489. Returns true if a connection was actually deleted.
  35490. */
  35491. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  35492. uint32 destNodeId, int destChannelIndex);
  35493. /** Removes all connections from the specified node.
  35494. */
  35495. bool disconnectNode (uint32 nodeId);
  35496. /** Performs a sanity checks of all the connections.
  35497. This might be useful if some of the processors are doing things like changing
  35498. their channel counts, which could render some connections obsolete.
  35499. */
  35500. bool removeIllegalConnections();
  35501. /** A special number that represents the midi channel of a node.
  35502. This is used as a channel index value if you want to refer to the midi input
  35503. or output instead of an audio channel.
  35504. */
  35505. static const int midiChannelIndex;
  35506. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  35507. in order to use the audio that comes into and out of the graph itself.
  35508. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  35509. node in the graph which delivers the audio that is coming into the parent
  35510. graph. This allows you to stream the data to other nodes and process the
  35511. incoming audio.
  35512. Likewise, one of these in "output" mode can be sent data which it will add to
  35513. the sum of data being sent to the graph's output.
  35514. @see AudioProcessorGraph
  35515. */
  35516. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  35517. {
  35518. public:
  35519. /** Specifies the mode in which this processor will operate.
  35520. */
  35521. enum IODeviceType
  35522. {
  35523. audioInputNode, /**< In this mode, the processor has output channels
  35524. representing all the audio input channels that are
  35525. coming into its parent audio graph. */
  35526. audioOutputNode, /**< In this mode, the processor has input channels
  35527. representing all the audio output channels that are
  35528. going out of its parent audio graph. */
  35529. midiInputNode, /**< In this mode, the processor has a midi output which
  35530. delivers the same midi data that is arriving at its
  35531. parent graph. */
  35532. midiOutputNode /**< In this mode, the processor has a midi input and
  35533. any data sent to it will be passed out of the parent
  35534. graph. */
  35535. };
  35536. /** Returns the mode of this processor. */
  35537. IODeviceType getType() const { return type; }
  35538. /** Returns the parent graph to which this processor belongs, or 0 if it
  35539. hasn't yet been added to one. */
  35540. AudioProcessorGraph* getParentGraph() const { return graph; }
  35541. /** True if this is an audio or midi input. */
  35542. bool isInput() const;
  35543. /** True if this is an audio or midi output. */
  35544. bool isOutput() const;
  35545. AudioGraphIOProcessor (const IODeviceType type);
  35546. ~AudioGraphIOProcessor();
  35547. const String getName() const;
  35548. void fillInPluginDescription (PluginDescription& d) const;
  35549. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  35550. void releaseResources();
  35551. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  35552. const String getInputChannelName (int channelIndex) const;
  35553. const String getOutputChannelName (int channelIndex) const;
  35554. bool isInputChannelStereoPair (int index) const;
  35555. bool isOutputChannelStereoPair (int index) const;
  35556. bool acceptsMidi() const;
  35557. bool producesMidi() const;
  35558. bool hasEditor() const;
  35559. AudioProcessorEditor* createEditor();
  35560. int getNumParameters();
  35561. const String getParameterName (int);
  35562. float getParameter (int);
  35563. const String getParameterText (int);
  35564. void setParameter (int, float);
  35565. int getNumPrograms();
  35566. int getCurrentProgram();
  35567. void setCurrentProgram (int);
  35568. const String getProgramName (int);
  35569. void changeProgramName (int, const String&);
  35570. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  35571. void setStateInformation (const void* data, int sizeInBytes);
  35572. /** @internal */
  35573. void setParentGraph (AudioProcessorGraph* graph);
  35574. private:
  35575. const IODeviceType type;
  35576. AudioProcessorGraph* graph;
  35577. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioGraphIOProcessor);
  35578. };
  35579. // AudioProcessor methods:
  35580. const String getName() const;
  35581. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  35582. void releaseResources();
  35583. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  35584. const String getInputChannelName (int channelIndex) const;
  35585. const String getOutputChannelName (int channelIndex) const;
  35586. bool isInputChannelStereoPair (int index) const;
  35587. bool isOutputChannelStereoPair (int index) const;
  35588. bool acceptsMidi() const;
  35589. bool producesMidi() const;
  35590. bool hasEditor() const { return false; }
  35591. AudioProcessorEditor* createEditor() { return nullptr; }
  35592. int getNumParameters() { return 0; }
  35593. const String getParameterName (int) { return String::empty; }
  35594. float getParameter (int) { return 0; }
  35595. const String getParameterText (int) { return String::empty; }
  35596. void setParameter (int, float) { }
  35597. int getNumPrograms() { return 0; }
  35598. int getCurrentProgram() { return 0; }
  35599. void setCurrentProgram (int) { }
  35600. const String getProgramName (int) { return String::empty; }
  35601. void changeProgramName (int, const String&) { }
  35602. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  35603. void setStateInformation (const void* data, int sizeInBytes);
  35604. /** @internal */
  35605. void handleAsyncUpdate();
  35606. private:
  35607. ReferenceCountedArray <Node> nodes;
  35608. OwnedArray <Connection> connections;
  35609. uint32 lastNodeId;
  35610. AudioSampleBuffer renderingBuffers;
  35611. OwnedArray <MidiBuffer> midiBuffers;
  35612. CriticalSection renderLock;
  35613. Array<void*> renderingOps;
  35614. friend class AudioGraphIOProcessor;
  35615. AudioSampleBuffer* currentAudioInputBuffer;
  35616. AudioSampleBuffer currentAudioOutputBuffer;
  35617. MidiBuffer* currentMidiInputBuffer;
  35618. MidiBuffer currentMidiOutputBuffer;
  35619. void clearRenderingSequence();
  35620. void buildRenderingSequence();
  35621. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  35622. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorGraph);
  35623. };
  35624. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35625. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  35626. #endif
  35627. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  35628. #endif
  35629. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35630. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  35631. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35632. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35633. /**
  35634. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  35635. To use one of these, just make it the callback used by your AudioIODevice, and
  35636. give it a processor to use by calling setProcessor().
  35637. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  35638. input to send both streams through the processor.
  35639. @see AudioProcessor, AudioProcessorGraph
  35640. */
  35641. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  35642. public MidiInputCallback
  35643. {
  35644. public:
  35645. /**
  35646. */
  35647. AudioProcessorPlayer();
  35648. /** Destructor. */
  35649. virtual ~AudioProcessorPlayer();
  35650. /** Sets the processor that should be played.
  35651. The processor that is passed in will not be deleted or owned by this object.
  35652. To stop anything playing, pass in 0 to this method.
  35653. */
  35654. void setProcessor (AudioProcessor* processorToPlay);
  35655. /** Returns the current audio processor that is being played.
  35656. */
  35657. AudioProcessor* getCurrentProcessor() const { return processor; }
  35658. /** Returns a midi message collector that you can pass midi messages to if you
  35659. want them to be injected into the midi stream that is being sent to the
  35660. processor.
  35661. */
  35662. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  35663. /** @internal */
  35664. void audioDeviceIOCallback (const float** inputChannelData,
  35665. int totalNumInputChannels,
  35666. float** outputChannelData,
  35667. int totalNumOutputChannels,
  35668. int numSamples);
  35669. /** @internal */
  35670. void audioDeviceAboutToStart (AudioIODevice* device);
  35671. /** @internal */
  35672. void audioDeviceStopped();
  35673. /** @internal */
  35674. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  35675. private:
  35676. AudioProcessor* processor;
  35677. CriticalSection lock;
  35678. double sampleRate;
  35679. int blockSize;
  35680. bool isPrepared;
  35681. int numInputChans, numOutputChans;
  35682. float* channels [128];
  35683. AudioSampleBuffer tempBuffer;
  35684. MidiBuffer incomingMidi;
  35685. MidiMessageCollector messageCollector;
  35686. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorPlayer);
  35687. };
  35688. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35689. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  35690. #endif
  35691. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35692. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  35693. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35694. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35695. /*** Start of inlined file: juce_PropertyPanel.h ***/
  35696. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  35697. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  35698. /*** Start of inlined file: juce_PropertyComponent.h ***/
  35699. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35700. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35701. class EditableProperty;
  35702. /**
  35703. A base class for a component that goes in a PropertyPanel and displays one of
  35704. an item's properties.
  35705. Subclasses of this are used to display a property in various forms, e.g. a
  35706. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  35707. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  35708. A subclass must implement the refresh() method which will be called to tell the
  35709. component to update itself, and is also responsible for calling this it when the
  35710. item that it refers to is changed.
  35711. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  35712. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  35713. */
  35714. class JUCE_API PropertyComponent : public Component,
  35715. public SettableTooltipClient
  35716. {
  35717. public:
  35718. /** Creates a PropertyComponent.
  35719. @param propertyName the name is stored as this component's name, and is
  35720. used as the name displayed next to this component in
  35721. a property panel
  35722. @param preferredHeight the height that the component should be given - some
  35723. items may need to be larger than a normal row height.
  35724. This value can also be set if a subclass changes the
  35725. preferredHeight member variable.
  35726. */
  35727. PropertyComponent (const String& propertyName,
  35728. int preferredHeight = 25);
  35729. /** Destructor. */
  35730. ~PropertyComponent();
  35731. /** Returns this item's preferred height.
  35732. This value is specified either in the constructor or by a subclass changing the
  35733. preferredHeight member variable.
  35734. */
  35735. int getPreferredHeight() const noexcept { return preferredHeight; }
  35736. void setPreferredHeight (int newHeight) noexcept { preferredHeight = newHeight; }
  35737. /** Updates the property component if the item it refers to has changed.
  35738. A subclass must implement this method, and other objects may call it to
  35739. force it to refresh itself.
  35740. The subclass should be economical in the amount of work is done, so for
  35741. example it should check whether it really needs to do a repaint rather than
  35742. just doing one every time this method is called, as it may be called when
  35743. the value being displayed hasn't actually changed.
  35744. */
  35745. virtual void refresh() = 0;
  35746. /** The default paint method fills the background and draws a label for the
  35747. item's name.
  35748. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  35749. */
  35750. void paint (Graphics& g);
  35751. /** The default resize method positions any child component to the right of this
  35752. one, based on the look and feel's default label size.
  35753. */
  35754. void resized();
  35755. /** By default, this just repaints the component. */
  35756. void enablementChanged();
  35757. protected:
  35758. /** Used by the PropertyPanel to determine how high this component needs to be.
  35759. A subclass can update this value in its constructor but shouldn't alter it later
  35760. as changes won't necessarily be picked up.
  35761. */
  35762. int preferredHeight;
  35763. private:
  35764. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyComponent);
  35765. };
  35766. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35767. /*** End of inlined file: juce_PropertyComponent.h ***/
  35768. /**
  35769. A panel that holds a list of PropertyComponent objects.
  35770. This panel displays a list of PropertyComponents, and allows them to be organised
  35771. into collapsible sections.
  35772. To use, simply create one of these and add your properties to it with addProperties()
  35773. or addSection().
  35774. @see PropertyComponent
  35775. */
  35776. class JUCE_API PropertyPanel : public Component
  35777. {
  35778. public:
  35779. /** Creates an empty property panel. */
  35780. PropertyPanel();
  35781. /** Destructor. */
  35782. ~PropertyPanel();
  35783. /** Deletes all property components from the panel.
  35784. */
  35785. void clear();
  35786. /** Adds a set of properties to the panel.
  35787. The components in the list will be owned by this object and will be automatically
  35788. deleted later on when no longer needed.
  35789. These properties are added without them being inside a named section. If you
  35790. want them to be kept together in a collapsible section, use addSection() instead.
  35791. */
  35792. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  35793. /** Adds a set of properties to the panel.
  35794. These properties are added at the bottom of the list, under a section heading with
  35795. a plus/minus button that allows it to be opened and closed.
  35796. The components in the list will be owned by this object and will be automatically
  35797. deleted later on when no longer needed.
  35798. To add properies without them being in a section, use addProperties().
  35799. */
  35800. void addSection (const String& sectionTitle,
  35801. const Array <PropertyComponent*>& newPropertyComponents,
  35802. bool shouldSectionInitiallyBeOpen = true);
  35803. /** Calls the refresh() method of all PropertyComponents in the panel */
  35804. void refreshAll() const;
  35805. /** Returns a list of all the names of sections in the panel.
  35806. These are the sections that have been added with addSection().
  35807. */
  35808. StringArray getSectionNames() const;
  35809. /** Returns true if the section at this index is currently open.
  35810. The index is from 0 up to the number of items returned by getSectionNames().
  35811. */
  35812. bool isSectionOpen (int sectionIndex) const;
  35813. /** Opens or closes one of the sections.
  35814. The index is from 0 up to the number of items returned by getSectionNames().
  35815. */
  35816. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  35817. /** Enables or disables one of the sections.
  35818. The index is from 0 up to the number of items returned by getSectionNames().
  35819. */
  35820. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  35821. /** Saves the current state of open/closed sections so it can be restored later.
  35822. The caller is responsible for deleting the object that is returned.
  35823. To restore this state, use restoreOpennessState().
  35824. @see restoreOpennessState
  35825. */
  35826. XmlElement* getOpennessState() const;
  35827. /** Restores a previously saved arrangement of open/closed sections.
  35828. This will try to restore a snapshot of the panel's state that was created by
  35829. the getOpennessState() method. If any of the sections named in the original
  35830. XML aren't present, they will be ignored.
  35831. @see getOpennessState
  35832. */
  35833. void restoreOpennessState (const XmlElement& newState);
  35834. /** Sets a message to be displayed when there are no properties in the panel.
  35835. The default message is "nothing selected".
  35836. */
  35837. void setMessageWhenEmpty (const String& newMessage);
  35838. /** Returns the message that is displayed when there are no properties.
  35839. @see setMessageWhenEmpty
  35840. */
  35841. const String& getMessageWhenEmpty() const;
  35842. /** @internal */
  35843. void paint (Graphics& g);
  35844. /** @internal */
  35845. void resized();
  35846. private:
  35847. Viewport viewport;
  35848. class PropertyHolderComponent;
  35849. PropertyHolderComponent* propertyHolderComponent;
  35850. String messageWhenEmpty;
  35851. void updatePropHolderLayout() const;
  35852. void updatePropHolderLayout (int width) const;
  35853. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyPanel);
  35854. };
  35855. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  35856. /*** End of inlined file: juce_PropertyPanel.h ***/
  35857. /**
  35858. A type of UI component that displays the parameters of an AudioProcessor as
  35859. a simple list of sliders.
  35860. This can be used for showing an editor for a processor that doesn't supply
  35861. its own custom editor.
  35862. @see AudioProcessor
  35863. */
  35864. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  35865. {
  35866. public:
  35867. GenericAudioProcessorEditor (AudioProcessor* owner);
  35868. ~GenericAudioProcessorEditor();
  35869. void paint (Graphics& g);
  35870. void resized();
  35871. private:
  35872. PropertyPanel panel;
  35873. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GenericAudioProcessorEditor);
  35874. };
  35875. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35876. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  35877. #endif
  35878. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  35879. /*** Start of inlined file: juce_Sampler.h ***/
  35880. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  35881. #define __JUCE_SAMPLER_JUCEHEADER__
  35882. /*** Start of inlined file: juce_Synthesiser.h ***/
  35883. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  35884. #define __JUCE_SYNTHESISER_JUCEHEADER__
  35885. /**
  35886. Describes one of the sounds that a Synthesiser can play.
  35887. A synthesiser can contain one or more sounds, and a sound can choose which
  35888. midi notes and channels can trigger it.
  35889. The SynthesiserSound is a passive class that just describes what the sound is -
  35890. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  35891. more than one SynthesiserVoice to play the same sound at the same time.
  35892. @see Synthesiser, SynthesiserVoice
  35893. */
  35894. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  35895. {
  35896. protected:
  35897. SynthesiserSound();
  35898. public:
  35899. /** Destructor. */
  35900. virtual ~SynthesiserSound();
  35901. /** Returns true if this sound should be played when a given midi note is pressed.
  35902. The Synthesiser will use this information when deciding which sounds to trigger
  35903. for a given note.
  35904. */
  35905. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  35906. /** Returns true if the sound should be triggered by midi events on a given channel.
  35907. The Synthesiser will use this information when deciding which sounds to trigger
  35908. for a given note.
  35909. */
  35910. virtual bool appliesToChannel (const int midiChannel) = 0;
  35911. /**
  35912. */
  35913. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  35914. private:
  35915. JUCE_LEAK_DETECTOR (SynthesiserSound);
  35916. };
  35917. /**
  35918. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  35919. A voice plays a single sound at a time, and a synthesiser holds an array of
  35920. voices so that it can play polyphonically.
  35921. @see Synthesiser, SynthesiserSound
  35922. */
  35923. class JUCE_API SynthesiserVoice
  35924. {
  35925. public:
  35926. /** Creates a voice. */
  35927. SynthesiserVoice();
  35928. /** Destructor. */
  35929. virtual ~SynthesiserVoice();
  35930. /** Returns the midi note that this voice is currently playing.
  35931. Returns a value less than 0 if no note is playing.
  35932. */
  35933. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  35934. /** Returns the sound that this voice is currently playing.
  35935. Returns 0 if it's not playing.
  35936. */
  35937. SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  35938. /** Must return true if this voice object is capable of playing the given sound.
  35939. If there are different classes of sound, and different classes of voice, a voice can
  35940. choose which ones it wants to take on.
  35941. A typical implementation of this method may just return true if there's only one type
  35942. of voice and sound, or it might check the type of the sound object passed-in and
  35943. see if it's one that it understands.
  35944. */
  35945. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  35946. /** Called to start a new note.
  35947. This will be called during the rendering callback, so must be fast and thread-safe.
  35948. */
  35949. virtual void startNote (const int midiNoteNumber,
  35950. const float velocity,
  35951. SynthesiserSound* sound,
  35952. const int currentPitchWheelPosition) = 0;
  35953. /** Called to stop a note.
  35954. This will be called during the rendering callback, so must be fast and thread-safe.
  35955. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  35956. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  35957. and allow the synth to reassign it another sound.
  35958. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  35959. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  35960. finishes playing (during the rendering callback), it must make sure that it calls
  35961. clearCurrentNote().
  35962. */
  35963. virtual void stopNote (const bool allowTailOff) = 0;
  35964. /** Called to let the voice know that the pitch wheel has been moved.
  35965. This will be called during the rendering callback, so must be fast and thread-safe.
  35966. */
  35967. virtual void pitchWheelMoved (const int newValue) = 0;
  35968. /** Called to let the voice know that a midi controller has been moved.
  35969. This will be called during the rendering callback, so must be fast and thread-safe.
  35970. */
  35971. virtual void controllerMoved (const int controllerNumber,
  35972. const int newValue) = 0;
  35973. /** Renders the next block of data for this voice.
  35974. The output audio data must be added to the current contents of the buffer provided.
  35975. Only the region of the buffer between startSample and (startSample + numSamples)
  35976. should be altered by this method.
  35977. If the voice is currently silent, it should just return without doing anything.
  35978. If the sound that the voice is playing finishes during the course of this rendered
  35979. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  35980. The size of the blocks that are rendered can change each time it is called, and may
  35981. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  35982. the voice's methods will be called to tell it about note and controller events.
  35983. */
  35984. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  35985. int startSample,
  35986. int numSamples) = 0;
  35987. /** Returns true if the voice is currently playing a sound which is mapped to the given
  35988. midi channel.
  35989. If it's not currently playing, this will return false.
  35990. */
  35991. bool isPlayingChannel (int midiChannel) const;
  35992. /** Changes the voice's reference sample rate.
  35993. The rate is set so that subclasses know the output rate and can set their pitch
  35994. accordingly.
  35995. This method is called by the synth, and subclasses can access the current rate with
  35996. the currentSampleRate member.
  35997. */
  35998. void setCurrentPlaybackSampleRate (double newRate);
  35999. protected:
  36000. /** Returns the current target sample rate at which rendering is being done.
  36001. This is available for subclasses so they can pitch things correctly.
  36002. */
  36003. double getSampleRate() const { return currentSampleRate; }
  36004. /** Resets the state of this voice after a sound has finished playing.
  36005. The subclass must call this when it finishes playing a note and becomes available
  36006. to play new ones.
  36007. It must either call it in the stopNote() method, or if the voice is tailing off,
  36008. then it should call it later during the renderNextBlock method, as soon as it
  36009. finishes its tail-off.
  36010. It can also be called at any time during the render callback if the sound happens
  36011. to have finished, e.g. if it's playing a sample and the sample finishes.
  36012. */
  36013. void clearCurrentNote();
  36014. private:
  36015. friend class Synthesiser;
  36016. double currentSampleRate;
  36017. int currentlyPlayingNote;
  36018. uint32 noteOnTime;
  36019. SynthesiserSound::Ptr currentlyPlayingSound;
  36020. bool keyIsDown; // the voice may still be playing when the key is not down (i.e. sustain pedal)
  36021. bool sostenutoPedalDown;
  36022. JUCE_LEAK_DETECTOR (SynthesiserVoice);
  36023. };
  36024. /**
  36025. Base class for a musical device that can play sounds.
  36026. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  36027. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  36028. which can play back one of these sounds.
  36029. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  36030. set of sounds, and a set of voices it can use to play them. If you only give it
  36031. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  36032. have available.
  36033. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  36034. events that go in will be scanned for note on/off messages, and these are used to
  36035. start and stop the voices playing the appropriate sounds.
  36036. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  36037. noteOff() and other controller methods.
  36038. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  36039. what the target playback rate is. This value is passed on to the voices so that
  36040. they can pitch their output correctly.
  36041. */
  36042. class JUCE_API Synthesiser
  36043. {
  36044. public:
  36045. /** Creates a new synthesiser.
  36046. You'll need to add some sounds and voices before it'll make any sound..
  36047. */
  36048. Synthesiser();
  36049. /** Destructor. */
  36050. virtual ~Synthesiser();
  36051. /** Deletes all voices. */
  36052. void clearVoices();
  36053. /** Returns the number of voices that have been added. */
  36054. int getNumVoices() const { return voices.size(); }
  36055. /** Returns one of the voices that have been added. */
  36056. SynthesiserVoice* getVoice (int index) const;
  36057. /** Adds a new voice to the synth.
  36058. All the voices should be the same class of object and are treated equally.
  36059. The object passed in will be managed by the synthesiser, which will delete
  36060. it later on when no longer needed. The caller should not retain a pointer to the
  36061. voice.
  36062. */
  36063. void addVoice (SynthesiserVoice* newVoice);
  36064. /** Deletes one of the voices. */
  36065. void removeVoice (int index);
  36066. /** Deletes all sounds. */
  36067. void clearSounds();
  36068. /** Returns the number of sounds that have been added to the synth. */
  36069. int getNumSounds() const { return sounds.size(); }
  36070. /** Returns one of the sounds. */
  36071. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  36072. /** Adds a new sound to the synthesiser.
  36073. The object passed in is reference counted, so will be deleted when it is removed
  36074. from the synthesiser, and when no voices are still using it.
  36075. */
  36076. void addSound (const SynthesiserSound::Ptr& newSound);
  36077. /** Removes and deletes one of the sounds. */
  36078. void removeSound (int index);
  36079. /** If set to true, then the synth will try to take over an existing voice if
  36080. it runs out and needs to play another note.
  36081. The value of this boolean is passed into findFreeVoice(), so the result will
  36082. depend on the implementation of this method.
  36083. */
  36084. void setNoteStealingEnabled (bool shouldStealNotes);
  36085. /** Returns true if note-stealing is enabled.
  36086. @see setNoteStealingEnabled
  36087. */
  36088. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  36089. /** Triggers a note-on event.
  36090. The default method here will find all the sounds that want to be triggered by
  36091. this note/channel. For each sound, it'll try to find a free voice, and use the
  36092. voice to start playing the sound.
  36093. Subclasses might want to override this if they need a more complex algorithm.
  36094. This method will be called automatically according to the midi data passed into
  36095. renderNextBlock(), but may be called explicitly too.
  36096. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  36097. */
  36098. virtual void noteOn (int midiChannel,
  36099. int midiNoteNumber,
  36100. float velocity);
  36101. /** Triggers a note-off event.
  36102. This will turn off any voices that are playing a sound for the given note/channel.
  36103. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  36104. (if they can do). If this is false, the notes will all be cut off immediately.
  36105. This method will be called automatically according to the midi data passed into
  36106. renderNextBlock(), but may be called explicitly too.
  36107. The midiChannel parameter is the channel, between 1 and 16 inclusive.
  36108. */
  36109. virtual void noteOff (int midiChannel,
  36110. int midiNoteNumber,
  36111. bool allowTailOff);
  36112. /** Turns off all notes.
  36113. This will turn off any voices that are playing a sound on the given midi channel.
  36114. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  36115. which channel they're playing. Otherwise it represents a valid midi channel, from
  36116. 1 to 16 inclusive.
  36117. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  36118. (if they can do). If this is false, the notes will all be cut off immediately.
  36119. This method will be called automatically according to the midi data passed into
  36120. renderNextBlock(), but may be called explicitly too.
  36121. */
  36122. virtual void allNotesOff (int midiChannel,
  36123. bool allowTailOff);
  36124. /** Sends a pitch-wheel message.
  36125. This will send a pitch-wheel message to any voices that are playing sounds on
  36126. the given midi channel.
  36127. This method will be called automatically according to the midi data passed into
  36128. renderNextBlock(), but may be called explicitly too.
  36129. @param midiChannel the midi channel, from 1 to 16 inclusive
  36130. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  36131. */
  36132. virtual void handlePitchWheel (int midiChannel,
  36133. int wheelValue);
  36134. /** Sends a midi controller message.
  36135. This will send a midi controller message to any voices that are playing sounds on
  36136. the given midi channel.
  36137. This method will be called automatically according to the midi data passed into
  36138. renderNextBlock(), but may be called explicitly too.
  36139. @param midiChannel the midi channel, from 1 to 16 inclusive
  36140. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  36141. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  36142. */
  36143. virtual void handleController (int midiChannel,
  36144. int controllerNumber,
  36145. int controllerValue);
  36146. virtual void handleSustainPedal (int midiChannel, bool isDown);
  36147. virtual void handleSostenutoPedal (int midiChannel, bool isDown);
  36148. virtual void handleSoftPedal (int midiChannel, bool isDown);
  36149. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  36150. render.
  36151. This value is propagated to the voices so that they can use it to render the correct
  36152. pitches.
  36153. */
  36154. void setCurrentPlaybackSampleRate (double sampleRate);
  36155. /** Creates the next block of audio output.
  36156. This will process the next numSamples of data from all the voices, and add that output
  36157. to the audio block supplied, starting from the offset specified. Note that the
  36158. data will be added to the current contents of the buffer, so you should clear it
  36159. before calling this method if necessary.
  36160. The midi events in the inputMidi buffer are parsed for note and controller events,
  36161. and these are used to trigger the voices. Note that the startSample offset applies
  36162. both to the audio output buffer and the midi input buffer, so any midi events
  36163. with timestamps outside the specified region will be ignored.
  36164. */
  36165. void renderNextBlock (AudioSampleBuffer& outputAudio,
  36166. const MidiBuffer& inputMidi,
  36167. int startSample,
  36168. int numSamples);
  36169. protected:
  36170. /** This is used to control access to the rendering callback and the note trigger methods. */
  36171. CriticalSection lock;
  36172. OwnedArray <SynthesiserVoice> voices;
  36173. ReferenceCountedArray <SynthesiserSound> sounds;
  36174. /** The last pitch-wheel values for each midi channel. */
  36175. int lastPitchWheelValues [16];
  36176. /** Searches through the voices to find one that's not currently playing, and which
  36177. can play the given sound.
  36178. Returns 0 if all voices are busy and stealing isn't enabled.
  36179. This can be overridden to implement custom voice-stealing algorithms.
  36180. */
  36181. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  36182. const bool stealIfNoneAvailable) const;
  36183. /** Starts a specified voice playing a particular sound.
  36184. You'll probably never need to call this, it's used internally by noteOn(), but
  36185. may be needed by subclasses for custom behaviours.
  36186. */
  36187. void startVoice (SynthesiserVoice* voice,
  36188. SynthesiserSound* sound,
  36189. int midiChannel,
  36190. int midiNoteNumber,
  36191. float velocity);
  36192. private:
  36193. double sampleRate;
  36194. uint32 lastNoteOnCounter;
  36195. bool shouldStealNotes;
  36196. BigInteger sustainPedalsDown;
  36197. void handleMidiEvent (const MidiMessage& m);
  36198. void stopVoice (SynthesiserVoice* voice, bool allowTailOff);
  36199. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  36200. // Note the new parameters for this method.
  36201. virtual int findFreeVoice (const bool) const { return 0; }
  36202. #endif
  36203. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser);
  36204. };
  36205. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  36206. /*** End of inlined file: juce_Synthesiser.h ***/
  36207. /**
  36208. A subclass of SynthesiserSound that represents a sampled audio clip.
  36209. This is a pretty basic sampler, and just attempts to load the whole audio stream
  36210. into memory.
  36211. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36212. give it some SampledSound objects to play.
  36213. @see SamplerVoice, Synthesiser, SynthesiserSound
  36214. */
  36215. class JUCE_API SamplerSound : public SynthesiserSound
  36216. {
  36217. public:
  36218. /** Creates a sampled sound from an audio reader.
  36219. This will attempt to load the audio from the source into memory and store
  36220. it in this object.
  36221. @param name a name for the sample
  36222. @param source the audio to load. This object can be safely deleted by the
  36223. caller after this constructor returns
  36224. @param midiNotes the set of midi keys that this sound should be played on. This
  36225. is used by the SynthesiserSound::appliesToNote() method
  36226. @param midiNoteForNormalPitch the midi note at which the sample should be played
  36227. with its natural rate. All other notes will be pitched
  36228. up or down relative to this one
  36229. @param attackTimeSecs the attack (fade-in) time, in seconds
  36230. @param releaseTimeSecs the decay (fade-out) time, in seconds
  36231. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  36232. source, in seconds
  36233. */
  36234. SamplerSound (const String& name,
  36235. AudioFormatReader& source,
  36236. const BigInteger& midiNotes,
  36237. int midiNoteForNormalPitch,
  36238. double attackTimeSecs,
  36239. double releaseTimeSecs,
  36240. double maxSampleLengthSeconds);
  36241. /** Destructor. */
  36242. ~SamplerSound();
  36243. /** Returns the sample's name */
  36244. const String& getName() const { return name; }
  36245. /** Returns the audio sample data.
  36246. This could be 0 if there was a problem loading it.
  36247. */
  36248. AudioSampleBuffer* getAudioData() const { return data; }
  36249. bool appliesToNote (const int midiNoteNumber);
  36250. bool appliesToChannel (const int midiChannel);
  36251. private:
  36252. friend class SamplerVoice;
  36253. String name;
  36254. ScopedPointer <AudioSampleBuffer> data;
  36255. double sourceSampleRate;
  36256. BigInteger midiNotes;
  36257. int length, attackSamples, releaseSamples;
  36258. int midiRootNote;
  36259. JUCE_LEAK_DETECTOR (SamplerSound);
  36260. };
  36261. /**
  36262. A subclass of SynthesiserVoice that can play a SamplerSound.
  36263. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36264. give it some SampledSound objects to play.
  36265. @see SamplerSound, Synthesiser, SynthesiserVoice
  36266. */
  36267. class JUCE_API SamplerVoice : public SynthesiserVoice
  36268. {
  36269. public:
  36270. /** Creates a SamplerVoice.
  36271. */
  36272. SamplerVoice();
  36273. /** Destructor. */
  36274. ~SamplerVoice();
  36275. bool canPlaySound (SynthesiserSound* sound);
  36276. void startNote (const int midiNoteNumber,
  36277. const float velocity,
  36278. SynthesiserSound* sound,
  36279. const int currentPitchWheelPosition);
  36280. void stopNote (const bool allowTailOff);
  36281. void pitchWheelMoved (const int newValue);
  36282. void controllerMoved (const int controllerNumber,
  36283. const int newValue);
  36284. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  36285. private:
  36286. double pitchRatio;
  36287. double sourceSamplePosition;
  36288. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  36289. bool isInAttack, isInRelease;
  36290. JUCE_LEAK_DETECTOR (SamplerVoice);
  36291. };
  36292. #endif // __JUCE_SAMPLER_JUCEHEADER__
  36293. /*** End of inlined file: juce_Sampler.h ***/
  36294. #endif
  36295. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  36296. #endif
  36297. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36298. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  36299. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36300. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36301. /** Manages a list of ActionListeners, and can send them messages.
  36302. To quickly add methods to your class that can add/remove action
  36303. listeners and broadcast to them, you can derive from this.
  36304. @see ActionListener, ChangeListener
  36305. */
  36306. class JUCE_API ActionBroadcaster
  36307. {
  36308. public:
  36309. /** Creates an ActionBroadcaster. */
  36310. ActionBroadcaster();
  36311. /** Destructor. */
  36312. virtual ~ActionBroadcaster();
  36313. /** Adds a listener to the list.
  36314. Trying to add a listener that's already on the list will have no effect.
  36315. */
  36316. void addActionListener (ActionListener* listener);
  36317. /** Removes a listener from the list.
  36318. If the listener isn't on the list, this won't have any effect.
  36319. */
  36320. void removeActionListener (ActionListener* listener);
  36321. /** Removes all listeners from the list. */
  36322. void removeAllActionListeners();
  36323. /** Broadcasts a message to all the registered listeners.
  36324. @see ActionListener::actionListenerCallback
  36325. */
  36326. void sendActionMessage (const String& message) const;
  36327. private:
  36328. class CallbackReceiver : public MessageListener
  36329. {
  36330. public:
  36331. CallbackReceiver();
  36332. void handleMessage (const Message&);
  36333. ActionBroadcaster* owner;
  36334. };
  36335. friend class CallbackReceiver;
  36336. CallbackReceiver callback;
  36337. SortedSet <ActionListener*> actionListeners;
  36338. CriticalSection actionListenerLock;
  36339. JUCE_DECLARE_NON_COPYABLE (ActionBroadcaster);
  36340. };
  36341. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36342. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  36343. #endif
  36344. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  36345. #endif
  36346. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  36347. #endif
  36348. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  36349. #endif
  36350. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  36351. #endif
  36352. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  36353. #endif
  36354. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36355. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  36356. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36357. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36358. class InterprocessConnectionServer;
  36359. class MemoryBlock;
  36360. /**
  36361. Manages a simple two-way messaging connection to another process, using either
  36362. a socket or a named pipe as the transport medium.
  36363. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  36364. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  36365. and incoming messages will result in a callback via the messageReceived()
  36366. method.
  36367. To open a pipe and wait for another client to connect to it, use the createPipe()
  36368. method.
  36369. To act as a socket server and create connections for one or more client, see the
  36370. InterprocessConnectionServer class.
  36371. @see InterprocessConnectionServer, Socket, NamedPipe
  36372. */
  36373. class JUCE_API InterprocessConnection : public Thread,
  36374. private MessageListener
  36375. {
  36376. public:
  36377. /** Creates a connection.
  36378. Connections are created manually, connecting them with the connectToSocket()
  36379. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  36380. when a client wants to connect.
  36381. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  36382. connectionLost() and messageReceived() methods will
  36383. always be made using the message thread; if false,
  36384. these will be called immediately on the connection's
  36385. own thread.
  36386. @param magicMessageHeaderNumber a magic number to use in the header to check the
  36387. validity of the data blocks being sent and received. This
  36388. can be any number, but the sender and receiver must obviously
  36389. use matching values or they won't recognise each other.
  36390. */
  36391. InterprocessConnection (bool callbacksOnMessageThread = true,
  36392. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  36393. /** Destructor. */
  36394. ~InterprocessConnection();
  36395. /** Tries to connect this object to a socket.
  36396. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  36397. object waiting to receive client connections on this port number.
  36398. @param hostName the host computer, either a network address or name
  36399. @param portNumber the socket port number to try to connect to
  36400. @param timeOutMillisecs how long to keep trying before giving up
  36401. @returns true if the connection is established successfully
  36402. @see Socket
  36403. */
  36404. bool connectToSocket (const String& hostName,
  36405. int portNumber,
  36406. int timeOutMillisecs);
  36407. /** Tries to connect the object to an existing named pipe.
  36408. For this to work, another process on the same computer must already have opened
  36409. an InterprocessConnection object and used createPipe() to create a pipe for this
  36410. to connect to.
  36411. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36412. @returns true if it connects successfully.
  36413. @see createPipe, NamedPipe
  36414. */
  36415. bool connectToPipe (const String& pipeName,
  36416. int pipeReceiveMessageTimeoutMs = -1);
  36417. /** Tries to create a new pipe for other processes to connect to.
  36418. This creates a pipe with the given name, so that other processes can use
  36419. connectToPipe() to connect to the other end.
  36420. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36421. If another process is already using this pipe, this will fail and return false.
  36422. */
  36423. bool createPipe (const String& pipeName,
  36424. int pipeReceiveMessageTimeoutMs = -1);
  36425. /** Disconnects and closes any currently-open sockets or pipes. */
  36426. void disconnect();
  36427. /** True if a socket or pipe is currently active. */
  36428. bool isConnected() const;
  36429. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  36430. StreamingSocket* getSocket() const noexcept { return socket; }
  36431. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  36432. NamedPipe* getPipe() const noexcept { return pipe; }
  36433. /** Returns the name of the machine at the other end of this connection.
  36434. This will return an empty string if the other machine isn't known for
  36435. some reason.
  36436. */
  36437. String getConnectedHostName() const;
  36438. /** Tries to send a message to the other end of this connection.
  36439. This will fail if it's not connected, or if there's some kind of write error. If
  36440. it succeeds, the connection object at the other end will receive the message by
  36441. a callback to its messageReceived() method.
  36442. @see messageReceived
  36443. */
  36444. bool sendMessage (const MemoryBlock& message);
  36445. /** Called when the connection is first connected.
  36446. If the connection was created with the callbacksOnMessageThread flag set, then
  36447. this will be called on the message thread; otherwise it will be called on a server
  36448. thread.
  36449. */
  36450. virtual void connectionMade() = 0;
  36451. /** Called when the connection is broken.
  36452. If the connection was created with the callbacksOnMessageThread flag set, then
  36453. this will be called on the message thread; otherwise it will be called on a server
  36454. thread.
  36455. */
  36456. virtual void connectionLost() = 0;
  36457. /** Called when a message arrives.
  36458. When the object at the other end of this connection sends us a message with sendMessage(),
  36459. this callback is used to deliver it to us.
  36460. If the connection was created with the callbacksOnMessageThread flag set, then
  36461. this will be called on the message thread; otherwise it will be called on a server
  36462. thread.
  36463. @see sendMessage
  36464. */
  36465. virtual void messageReceived (const MemoryBlock& message) = 0;
  36466. private:
  36467. CriticalSection pipeAndSocketLock;
  36468. ScopedPointer <StreamingSocket> socket;
  36469. ScopedPointer <NamedPipe> pipe;
  36470. bool callbackConnectionState;
  36471. const bool useMessageThread;
  36472. const uint32 magicMessageHeader;
  36473. int pipeReceiveMessageTimeout;
  36474. friend class InterprocessConnectionServer;
  36475. void initialiseWithSocket (StreamingSocket* socket_);
  36476. void initialiseWithPipe (NamedPipe* pipe_);
  36477. void handleMessage (const Message& message);
  36478. void connectionMadeInt();
  36479. void connectionLostInt();
  36480. void deliverDataInt (const MemoryBlock& data);
  36481. bool readNextMessageInt();
  36482. void run();
  36483. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnection);
  36484. };
  36485. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36486. /*** End of inlined file: juce_InterprocessConnection.h ***/
  36487. #endif
  36488. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36489. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  36490. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36491. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36492. /**
  36493. An object that waits for client sockets to connect to a port on this host, and
  36494. creates InterprocessConnection objects for each one.
  36495. To use this, create a class derived from it which implements the createConnectionObject()
  36496. method, so that it creates suitable connection objects for each client that tries
  36497. to connect.
  36498. @see InterprocessConnection
  36499. */
  36500. class JUCE_API InterprocessConnectionServer : private Thread
  36501. {
  36502. public:
  36503. /** Creates an uninitialised server object.
  36504. */
  36505. InterprocessConnectionServer();
  36506. /** Destructor. */
  36507. ~InterprocessConnectionServer();
  36508. /** Starts an internal thread which listens on the given port number.
  36509. While this is running, in another process tries to connect with the
  36510. InterprocessConnection::connectToSocket() method, this object will call
  36511. createConnectionObject() to create a connection to that client.
  36512. Use stop() to stop the thread running.
  36513. @see createConnectionObject, stop
  36514. */
  36515. bool beginWaitingForSocket (int portNumber);
  36516. /** Terminates the listener thread, if it's active.
  36517. @see beginWaitingForSocket
  36518. */
  36519. void stop();
  36520. protected:
  36521. /** Creates a suitable connection object for a client process that wants to
  36522. connect to this one.
  36523. This will be called by the listener thread when a client process tries
  36524. to connect, and must return a new InterprocessConnection object that will
  36525. then run as this end of the connection.
  36526. @see InterprocessConnection
  36527. */
  36528. virtual InterprocessConnection* createConnectionObject() = 0;
  36529. private:
  36530. ScopedPointer <StreamingSocket> socket;
  36531. void run();
  36532. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnectionServer);
  36533. };
  36534. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36535. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  36536. #endif
  36537. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  36538. #endif
  36539. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  36540. #endif
  36541. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  36542. #endif
  36543. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36544. /*** Start of inlined file: juce_MessageManager.h ***/
  36545. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36546. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36547. class Component;
  36548. class MessageManagerLock;
  36549. class ThreadPoolJob;
  36550. class ActionListener;
  36551. class ActionBroadcaster;
  36552. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  36553. */
  36554. typedef void* (MessageCallbackFunction) (void* userData);
  36555. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  36556. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  36557. */
  36558. class JUCE_API MessageManager
  36559. {
  36560. public:
  36561. /** Returns the global instance of the MessageManager. */
  36562. static MessageManager* getInstance() noexcept;
  36563. /** Runs the event dispatch loop until a stop message is posted.
  36564. This method is only intended to be run by the application's startup routine,
  36565. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  36566. @see stopDispatchLoop
  36567. */
  36568. void runDispatchLoop();
  36569. /** Sends a signal that the dispatch loop should terminate.
  36570. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  36571. will be interrupted and will return.
  36572. @see runDispatchLoop
  36573. */
  36574. void stopDispatchLoop();
  36575. /** Returns true if the stopDispatchLoop() method has been called.
  36576. */
  36577. bool hasStopMessageBeenSent() const noexcept { return quitMessagePosted; }
  36578. #if JUCE_MODAL_LOOPS_PERMITTED
  36579. /** Synchronously dispatches messages until a given time has elapsed.
  36580. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  36581. otherwise returns true.
  36582. */
  36583. bool runDispatchLoopUntil (int millisecondsToRunFor);
  36584. #endif
  36585. /** Calls a function using the message-thread.
  36586. This can be used by any thread to cause this function to be called-back
  36587. by the message thread. If it's the message-thread that's calling this method,
  36588. then the function will just be called; if another thread is calling, a message
  36589. will be posted to the queue, and this method will block until that message
  36590. is delivered, the function is called, and the result is returned.
  36591. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  36592. thread has a critical section locked, which an unrelated message callback then tries to lock
  36593. before the message thread gets round to processing this callback.
  36594. @param callback the function to call - its signature must be @code
  36595. void* myCallbackFunction (void*) @endcode
  36596. @param userData a user-defined pointer that will be passed to the function that gets called
  36597. @returns the value that the callback function returns.
  36598. @see MessageManagerLock
  36599. */
  36600. void* callFunctionOnMessageThread (MessageCallbackFunction* callback, void* userData);
  36601. /** Returns true if the caller-thread is the message thread. */
  36602. bool isThisTheMessageThread() const noexcept;
  36603. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  36604. (Best to ignore this method unless you really know what you're doing..)
  36605. @see getCurrentMessageThread
  36606. */
  36607. void setCurrentThreadAsMessageThread();
  36608. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  36609. (Best to ignore this method unless you really know what you're doing..)
  36610. @see setCurrentMessageThread
  36611. */
  36612. Thread::ThreadID getCurrentMessageThread() const noexcept { return messageThreadId; }
  36613. /** Returns true if the caller thread has currenltly got the message manager locked.
  36614. see the MessageManagerLock class for more info about this.
  36615. This will be true if the caller is the message thread, because that automatically
  36616. gains a lock while a message is being dispatched.
  36617. */
  36618. bool currentThreadHasLockedMessageManager() const noexcept;
  36619. /** Sends a message to all other JUCE applications that are running.
  36620. @param messageText the string that will be passed to the actionListenerCallback()
  36621. method of the broadcast listeners in the other app.
  36622. @see registerBroadcastListener, ActionListener
  36623. */
  36624. static void broadcastMessage (const String& messageText);
  36625. /** Registers a listener to get told about broadcast messages.
  36626. The actionListenerCallback() callback's string parameter
  36627. is the message passed into broadcastMessage().
  36628. @see broadcastMessage
  36629. */
  36630. void registerBroadcastListener (ActionListener* listener);
  36631. /** Deregisters a broadcast listener. */
  36632. void deregisterBroadcastListener (ActionListener* listener);
  36633. #ifndef DOXYGEN
  36634. // Internal methods - do not use!
  36635. void deliverMessage (Message*);
  36636. void deliverBroadcastMessage (const String&);
  36637. ~MessageManager() noexcept;
  36638. #endif
  36639. private:
  36640. MessageManager() noexcept;
  36641. friend class MessageListener;
  36642. friend class ChangeBroadcaster;
  36643. friend class ActionBroadcaster;
  36644. friend class CallbackMessage;
  36645. static MessageManager* instance;
  36646. SortedSet <const MessageListener*> messageListeners;
  36647. ScopedPointer <ActionBroadcaster> broadcaster;
  36648. friend class JUCEApplication;
  36649. bool quitMessagePosted, quitMessageReceived;
  36650. Thread::ThreadID messageThreadId;
  36651. friend class MessageManagerLock;
  36652. Thread::ThreadID volatile threadWithLock;
  36653. CriticalSection lockingLock;
  36654. void postMessageToQueue (Message* message);
  36655. static bool postMessageToSystemQueue (Message*);
  36656. static void* exitModalLoopCallback (void*);
  36657. static void doPlatformSpecificInitialisation();
  36658. static void doPlatformSpecificShutdown();
  36659. static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  36660. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager);
  36661. };
  36662. /** Used to make sure that the calling thread has exclusive access to the message loop.
  36663. Because it's not thread-safe to call any of the Component or other UI classes
  36664. from threads other than the message thread, one of these objects can be used to
  36665. lock the message loop and allow this to be done. The message thread will be
  36666. suspended for the lifetime of the MessageManagerLock object, so create one on
  36667. the stack like this: @code
  36668. void MyThread::run()
  36669. {
  36670. someData = 1234;
  36671. const MessageManagerLock mmLock;
  36672. // the event loop will now be locked so it's safe to make a few calls..
  36673. myComponent->setBounds (newBounds);
  36674. myComponent->repaint();
  36675. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  36676. }
  36677. @endcode
  36678. Obviously be careful not to create one of these and leave it lying around, or
  36679. your app will grind to a halt!
  36680. Another caveat is that using this in conjunction with other CriticalSections
  36681. can create lots of interesting ways of producing a deadlock! In particular, if
  36682. your message thread calls stopThread() for a thread that uses these locks,
  36683. you'll get an (occasional) deadlock..
  36684. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  36685. */
  36686. class JUCE_API MessageManagerLock
  36687. {
  36688. public:
  36689. /** Tries to acquire a lock on the message manager.
  36690. The constructor attempts to gain a lock on the message loop, and the lock will be
  36691. kept for the lifetime of this object.
  36692. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  36693. this method will keep checking whether the thread has been given the
  36694. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  36695. without gaining the lock. If you pass a thread, you must check whether the lock was
  36696. successful by calling lockWasGained(). If this is false, your thread is being told to
  36697. die, so you should take evasive action.
  36698. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  36699. careful when doing this, because it's very easy to deadlock if your message thread
  36700. attempts to call stopThread() on a thread just as that thread attempts to get the
  36701. message lock.
  36702. If the calling thread already has the lock, nothing will be done, so it's safe and
  36703. quick to use these locks recursively.
  36704. E.g.
  36705. @code
  36706. void run()
  36707. {
  36708. ...
  36709. while (! threadShouldExit())
  36710. {
  36711. MessageManagerLock mml (Thread::getCurrentThread());
  36712. if (! mml.lockWasGained())
  36713. return; // another thread is trying to kill us!
  36714. ..do some locked stuff here..
  36715. }
  36716. ..and now the MM is now unlocked..
  36717. }
  36718. @endcode
  36719. */
  36720. MessageManagerLock (Thread* threadToCheckForExitSignal = 0);
  36721. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  36722. instead of a thread.
  36723. See the MessageManagerLock (Thread*) constructor for details on how this works.
  36724. */
  36725. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  36726. /** Releases the current thread's lock on the message manager.
  36727. Make sure this object is created and deleted by the same thread,
  36728. otherwise there are no guarantees what will happen!
  36729. */
  36730. ~MessageManagerLock() noexcept;
  36731. /** Returns true if the lock was successfully acquired.
  36732. (See the constructor that takes a Thread for more info).
  36733. */
  36734. bool lockWasGained() const noexcept { return locked; }
  36735. private:
  36736. class BlockingMessage;
  36737. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  36738. ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  36739. bool locked;
  36740. void init (Thread* thread, ThreadPoolJob* job);
  36741. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock);
  36742. };
  36743. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36744. /*** End of inlined file: juce_MessageManager.h ***/
  36745. #endif
  36746. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  36747. /*** Start of inlined file: juce_MultiTimer.h ***/
  36748. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  36749. #define __JUCE_MULTITIMER_JUCEHEADER__
  36750. /**
  36751. A type of timer class that can run multiple timers with different frequencies,
  36752. all of which share a single callback.
  36753. This class is very similar to the Timer class, but allows you run multiple
  36754. separate timers, where each one has a unique ID number. The methods in this
  36755. class are exactly equivalent to those in Timer, but with the addition of
  36756. this ID number.
  36757. To use it, you need to create a subclass of MultiTimer, implementing the
  36758. timerCallback() method. Then you can start timers with startTimer(), and
  36759. each time the callback is triggered, it passes in the ID of the timer that
  36760. caused it.
  36761. @see Timer
  36762. */
  36763. class JUCE_API MultiTimer
  36764. {
  36765. protected:
  36766. /** Creates a MultiTimer.
  36767. When created, no timers are running, so use startTimer() to start things off.
  36768. */
  36769. MultiTimer() noexcept;
  36770. /** Creates a copy of another timer.
  36771. Note that this timer will not contain any running timers, even if the one you're
  36772. copying from was running.
  36773. */
  36774. MultiTimer (const MultiTimer& other) noexcept;
  36775. public:
  36776. /** Destructor. */
  36777. virtual ~MultiTimer();
  36778. /** The user-defined callback routine that actually gets called by each of the
  36779. timers that are running.
  36780. It's perfectly ok to call startTimer() or stopTimer() from within this
  36781. callback to change the subsequent intervals.
  36782. */
  36783. virtual void timerCallback (int timerId) = 0;
  36784. /** Starts a timer and sets the length of interval required.
  36785. If the timer is already started, this will reset it, so the
  36786. time between calling this method and the next timer callback
  36787. will not be less than the interval length passed in.
  36788. @param timerId a unique Id number that identifies the timer to
  36789. start. This is the id that will be passed back
  36790. to the timerCallback() method when this timer is
  36791. triggered
  36792. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  36793. rounded up to 1)
  36794. */
  36795. void startTimer (int timerId, int intervalInMilliseconds) noexcept;
  36796. /** Stops a timer.
  36797. If a timer has been started with the given ID number, it will be cancelled.
  36798. No more callbacks will be made for the specified timer after this method returns.
  36799. If this is called from a different thread, any callbacks that may
  36800. be currently executing may be allowed to finish before the method
  36801. returns.
  36802. */
  36803. void stopTimer (int timerId) noexcept;
  36804. /** Checks whether a timer has been started for a specified ID.
  36805. @returns true if a timer with the given ID is running.
  36806. */
  36807. bool isTimerRunning (int timerId) const noexcept;
  36808. /** Returns the interval for a specified timer ID.
  36809. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  36810. is running for the ID number specified.
  36811. */
  36812. int getTimerInterval (int timerId) const noexcept;
  36813. private:
  36814. class MultiTimerCallback;
  36815. SpinLock timerListLock;
  36816. OwnedArray <MultiTimerCallback> timers;
  36817. MultiTimer& operator= (const MultiTimer&);
  36818. };
  36819. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  36820. /*** End of inlined file: juce_MultiTimer.h ***/
  36821. #endif
  36822. #ifndef __JUCE_TIMER_JUCEHEADER__
  36823. #endif
  36824. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  36825. /*** Start of inlined file: juce_ArrowButton.h ***/
  36826. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  36827. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  36828. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  36829. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36830. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36831. /**
  36832. An effect filter that adds a drop-shadow behind the image's content.
  36833. (This will only work on images/components that aren't opaque, of course).
  36834. When added to a component, this effect will draw a soft-edged
  36835. shadow based on what gets drawn inside it. The shadow will also
  36836. be applied to the component's children.
  36837. For speed, this doesn't use a proper gaussian blur, but cheats by
  36838. using a simple bilinear filter. If you need a really high-quality
  36839. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  36840. @see Component::setComponentEffect
  36841. */
  36842. class JUCE_API DropShadowEffect : public ImageEffectFilter
  36843. {
  36844. public:
  36845. /** Creates a default drop-shadow effect.
  36846. To customise the shadow's appearance, use the setShadowProperties()
  36847. method.
  36848. */
  36849. DropShadowEffect();
  36850. /** Destructor. */
  36851. ~DropShadowEffect();
  36852. /** Sets up parameters affecting the shadow's appearance.
  36853. @param newRadius the (approximate) radius of the blur used
  36854. @param newOpacity the opacity with which the shadow is rendered
  36855. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  36856. component's contents
  36857. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  36858. component's contents
  36859. */
  36860. void setShadowProperties (float newRadius,
  36861. float newOpacity,
  36862. int newShadowOffsetX,
  36863. int newShadowOffsetY);
  36864. /** @internal */
  36865. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  36866. private:
  36867. int offsetX, offsetY;
  36868. float radius, opacity;
  36869. JUCE_LEAK_DETECTOR (DropShadowEffect);
  36870. };
  36871. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36872. /*** End of inlined file: juce_DropShadowEffect.h ***/
  36873. /**
  36874. A button with an arrow in it.
  36875. @see Button
  36876. */
  36877. class JUCE_API ArrowButton : public Button
  36878. {
  36879. public:
  36880. /** Creates an ArrowButton.
  36881. @param buttonName the name to give the button
  36882. @param arrowDirection the direction the arrow should point in, where 0.0 is
  36883. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  36884. @param arrowColour the colour to use for the arrow
  36885. */
  36886. ArrowButton (const String& buttonName,
  36887. float arrowDirection,
  36888. const Colour& arrowColour);
  36889. /** Destructor. */
  36890. ~ArrowButton();
  36891. protected:
  36892. /** @internal */
  36893. void paintButton (Graphics& g,
  36894. bool isMouseOverButton,
  36895. bool isButtonDown);
  36896. /** @internal */
  36897. void buttonStateChanged();
  36898. private:
  36899. Colour colour;
  36900. DropShadowEffect shadow;
  36901. Path path;
  36902. int offset;
  36903. void updateShadowAndOffset();
  36904. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ArrowButton);
  36905. };
  36906. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  36907. /*** End of inlined file: juce_ArrowButton.h ***/
  36908. #endif
  36909. #ifndef __JUCE_BUTTON_JUCEHEADER__
  36910. #endif
  36911. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36912. /*** Start of inlined file: juce_DrawableButton.h ***/
  36913. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36914. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36915. /*** Start of inlined file: juce_Drawable.h ***/
  36916. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  36917. #define __JUCE_DRAWABLE_JUCEHEADER__
  36918. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  36919. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36920. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36921. /**
  36922. Expresses a coordinate as a dynamically evaluated expression.
  36923. @see RelativePoint, RelativeRectangle
  36924. */
  36925. class JUCE_API RelativeCoordinate
  36926. {
  36927. public:
  36928. /** Creates a zero coordinate. */
  36929. RelativeCoordinate();
  36930. RelativeCoordinate (const Expression& expression);
  36931. RelativeCoordinate (const RelativeCoordinate& other);
  36932. RelativeCoordinate& operator= (const RelativeCoordinate& other);
  36933. /** Creates an absolute position from the parent origin on either the X or Y axis.
  36934. @param absoluteDistanceFromOrigin the distance from the origin
  36935. */
  36936. RelativeCoordinate (double absoluteDistanceFromOrigin);
  36937. /** Recreates a coordinate from a string description.
  36938. The string will be parsed by ExpressionParser::parse().
  36939. @param stringVersion the expression to use
  36940. @see toString
  36941. */
  36942. RelativeCoordinate (const String& stringVersion);
  36943. /** Destructor. */
  36944. ~RelativeCoordinate();
  36945. bool operator== (const RelativeCoordinate& other) const noexcept;
  36946. bool operator!= (const RelativeCoordinate& other) const noexcept;
  36947. /** Calculates the absolute position of this coordinate.
  36948. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  36949. be needed to calculate the result.
  36950. */
  36951. double resolve (const Expression::Scope* evaluationScope) const;
  36952. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  36953. This will recursively check any coordinates upon which this one depends.
  36954. */
  36955. bool references (const String& coordName, const Expression::Scope* evaluationScope) const;
  36956. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  36957. bool isRecursive (const Expression::Scope* evaluationScope) const;
  36958. /** Returns true if this coordinate depends on any other coordinates for its position. */
  36959. bool isDynamic() const;
  36960. /** Changes the value of this coord to make it resolve to the specified position.
  36961. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  36962. or relative position to whatever value is necessary to make its resultant position
  36963. match the position that is provided.
  36964. */
  36965. void moveToAbsolute (double absoluteTargetPosition, const Expression::Scope* evaluationScope);
  36966. /** Returns the expression that defines this coordinate. */
  36967. const Expression& getExpression() const { return term; }
  36968. /** Returns a string which represents this coordinate.
  36969. For details of the string syntax, see the constructor notes.
  36970. */
  36971. String toString() const;
  36972. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  36973. As well as avoiding using string literals in your code, using these preset values
  36974. has the advantage that all instances of the same string will share the same, reference-counted
  36975. String object, so if you have thousands of points which all refer to the same
  36976. anchor points, this can save a significant amount of memory allocation.
  36977. */
  36978. struct Strings
  36979. {
  36980. static const String parent; /**< "parent" */
  36981. static const String left; /**< "left" */
  36982. static const String right; /**< "right" */
  36983. static const String top; /**< "top" */
  36984. static const String bottom; /**< "bottom" */
  36985. static const String x; /**< "x" */
  36986. static const String y; /**< "y" */
  36987. static const String width; /**< "width" */
  36988. static const String height; /**< "height" */
  36989. };
  36990. struct StandardStrings
  36991. {
  36992. enum Type
  36993. {
  36994. left, right, top, bottom,
  36995. x, y, width, height,
  36996. parent,
  36997. unknown
  36998. };
  36999. static Type getTypeOf (const String& s) noexcept;
  37000. };
  37001. private:
  37002. Expression term;
  37003. };
  37004. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  37005. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  37006. /*** Start of inlined file: juce_RelativeCoordinatePositioner.h ***/
  37007. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37008. #define __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37009. /*** Start of inlined file: juce_RelativePoint.h ***/
  37010. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  37011. #define __JUCE_RELATIVEPOINT_JUCEHEADER__
  37012. /**
  37013. An X-Y position stored as a pair of RelativeCoordinate values.
  37014. @see RelativeCoordinate, RelativeRectangle
  37015. */
  37016. class JUCE_API RelativePoint
  37017. {
  37018. public:
  37019. /** Creates a point at the origin. */
  37020. RelativePoint();
  37021. /** Creates an absolute point, relative to the origin. */
  37022. RelativePoint (const Point<float>& absolutePoint);
  37023. /** Creates an absolute point, relative to the origin. */
  37024. RelativePoint (float absoluteX, float absoluteY);
  37025. /** Creates an absolute point from two coordinates. */
  37026. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  37027. /** Creates a point from a stringified representation.
  37028. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  37029. strings is explained in the RelativeCoordinate class.
  37030. @see toString
  37031. */
  37032. RelativePoint (const String& stringVersion);
  37033. bool operator== (const RelativePoint& other) const noexcept;
  37034. bool operator!= (const RelativePoint& other) const noexcept;
  37035. /** Calculates the absolute position of this point.
  37036. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  37037. be needed to calculate the result.
  37038. */
  37039. const Point<float> resolve (const Expression::Scope* evaluationContext) const;
  37040. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  37041. Calling this will leave any anchor points unchanged, but will set any absolute
  37042. or relative positions to whatever values are necessary to make the resultant position
  37043. match the position that is provided.
  37044. */
  37045. void moveToAbsolute (const Point<float>& newPos, const Expression::Scope* evaluationContext);
  37046. /** Returns a string which represents this point.
  37047. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  37048. coordinates, see the RelativeCoordinate constructor notes.
  37049. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  37050. */
  37051. String toString() const;
  37052. /** Returns true if this point depends on any other coordinates for its position. */
  37053. bool isDynamic() const;
  37054. // The actual X and Y coords...
  37055. RelativeCoordinate x, y;
  37056. };
  37057. #endif // __JUCE_RELATIVEPOINT_JUCEHEADER__
  37058. /*** End of inlined file: juce_RelativePoint.h ***/
  37059. /*** Start of inlined file: juce_MarkerList.h ***/
  37060. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  37061. #define __JUCE_MARKERLIST_JUCEHEADER__
  37062. class Component;
  37063. /**
  37064. Holds a set of named marker points along a one-dimensional axis.
  37065. This class is used to store sets of X and Y marker points in components.
  37066. @see Component::getMarkers().
  37067. */
  37068. class JUCE_API MarkerList
  37069. {
  37070. public:
  37071. /** Creates an empty marker list. */
  37072. MarkerList();
  37073. /** Creates a copy of another marker list. */
  37074. MarkerList (const MarkerList& other);
  37075. /** Copies another marker list to this one. */
  37076. MarkerList& operator= (const MarkerList& other);
  37077. /** Destructor. */
  37078. ~MarkerList();
  37079. /** Represents a marker in a MarkerList. */
  37080. class JUCE_API Marker
  37081. {
  37082. public:
  37083. /** Creates a copy of another Marker. */
  37084. Marker (const Marker& other);
  37085. /** Creates a Marker with a given name and position. */
  37086. Marker (const String& name, const RelativeCoordinate& position);
  37087. /** The marker's name. */
  37088. String name;
  37089. /** The marker's position.
  37090. The expression used to define the coordinate may use the names of other
  37091. markers, so that markers can be linked in arbitrary ways, but be careful
  37092. not to create recursive loops of markers whose positions are based on each
  37093. other! It can also refer to "parent.right" and "parent.bottom" so that you
  37094. can set markers which are relative to the size of the component that contains
  37095. them.
  37096. To resolve the coordinate, you can use the MarkerList::getMarkerPosition() method.
  37097. */
  37098. RelativeCoordinate position;
  37099. /** Returns true if both the names and positions of these two markers match. */
  37100. bool operator== (const Marker&) const noexcept;
  37101. /** Returns true if either the name or position of these two markers differ. */
  37102. bool operator!= (const Marker&) const noexcept;
  37103. };
  37104. /** Returns the number of markers in the list. */
  37105. int getNumMarkers() const noexcept;
  37106. /** Returns one of the markers in the list, by its index. */
  37107. const Marker* getMarker (int index) const noexcept;
  37108. /** Returns a named marker, or 0 if no such name is found.
  37109. Note that name comparisons are case-sensitive.
  37110. */
  37111. const Marker* getMarker (const String& name) const noexcept;
  37112. /** Evaluates the given marker and returns its absolute position.
  37113. The parent component must be supplied in case the marker's expression refers to
  37114. the size of its parent component.
  37115. */
  37116. double getMarkerPosition (const Marker& marker, Component* parentComponent) const;
  37117. /** Sets the position of a marker.
  37118. If the name already exists, then the existing marker is moved; if it doesn't exist, then a
  37119. new marker is added.
  37120. */
  37121. void setMarker (const String& name, const RelativeCoordinate& position);
  37122. /** Deletes the marker at the given list index. */
  37123. void removeMarker (int index);
  37124. /** Deletes the marker with the given name. */
  37125. void removeMarker (const String& name);
  37126. /** Returns true if all the markers in these two lists match exactly. */
  37127. bool operator== (const MarkerList& other) const noexcept;
  37128. /** Returns true if not all the markers in these two lists match exactly. */
  37129. bool operator!= (const MarkerList& other) const noexcept;
  37130. /**
  37131. A class for receiving events when changes are made to a MarkerList.
  37132. You can register a MarkerList::Listener with a MarkerList using the MarkerList::addListener()
  37133. method, and it will be called when markers are moved, added, or deleted.
  37134. @see MarkerList::addListener, MarkerList::removeListener
  37135. */
  37136. class JUCE_API Listener
  37137. {
  37138. public:
  37139. /** Destructor. */
  37140. virtual ~Listener() {}
  37141. /** Called when something in the given marker list changes. */
  37142. virtual void markersChanged (MarkerList* markerList) = 0;
  37143. /** Called when the given marker list is being deleted. */
  37144. virtual void markerListBeingDeleted (MarkerList* markerList);
  37145. };
  37146. /** Registers a listener that will be called when the markers are changed. */
  37147. void addListener (Listener* listener);
  37148. /** Deregisters a previously-registered listener. */
  37149. void removeListener (Listener* listener);
  37150. /** Synchronously calls markersChanged() on all the registered listeners. */
  37151. void markersHaveChanged();
  37152. /** Forms a wrapper around a ValueTree that can be used for storing a MarkerList. */
  37153. class ValueTreeWrapper
  37154. {
  37155. public:
  37156. ValueTreeWrapper (const ValueTree& state);
  37157. ValueTree& getState() noexcept { return state; }
  37158. int getNumMarkers() const;
  37159. ValueTree getMarkerState (int index) const;
  37160. ValueTree getMarkerState (const String& name) const;
  37161. bool containsMarker (const ValueTree& state) const;
  37162. MarkerList::Marker getMarker (const ValueTree& state) const;
  37163. void setMarker (const MarkerList::Marker& marker, UndoManager* undoManager);
  37164. void removeMarker (const ValueTree& state, UndoManager* undoManager);
  37165. void applyTo (MarkerList& markerList);
  37166. void readFrom (const MarkerList& markerList, UndoManager* undoManager);
  37167. static const Identifier markerTag, nameProperty, posProperty;
  37168. private:
  37169. ValueTree state;
  37170. };
  37171. private:
  37172. OwnedArray<Marker> markers;
  37173. ListenerList<Listener> listeners;
  37174. JUCE_LEAK_DETECTOR (MarkerList);
  37175. };
  37176. #endif // __JUCE_MARKERLIST_JUCEHEADER__
  37177. /*** End of inlined file: juce_MarkerList.h ***/
  37178. /**
  37179. Base class for Component::Positioners that are based upon relative coordinates.
  37180. */
  37181. class JUCE_API RelativeCoordinatePositionerBase : public Component::Positioner,
  37182. public ComponentListener,
  37183. public MarkerList::Listener
  37184. {
  37185. public:
  37186. RelativeCoordinatePositionerBase (Component& component_);
  37187. ~RelativeCoordinatePositionerBase();
  37188. void componentMovedOrResized (Component&, bool, bool);
  37189. void componentParentHierarchyChanged (Component&);
  37190. void componentChildrenChanged (Component& component);
  37191. void componentBeingDeleted (Component& component);
  37192. void markersChanged (MarkerList*);
  37193. void markerListBeingDeleted (MarkerList* markerList);
  37194. void apply();
  37195. bool addCoordinate (const RelativeCoordinate& coord);
  37196. bool addPoint (const RelativePoint& point);
  37197. /** Used for resolving a RelativeCoordinate expression in the context of a component. */
  37198. class ComponentScope : public Expression::Scope
  37199. {
  37200. public:
  37201. ComponentScope (Component& component_);
  37202. Expression getSymbolValue (const String& symbol) const;
  37203. void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  37204. String getScopeUID() const;
  37205. protected:
  37206. Component& component;
  37207. Component* findSiblingComponent (const String& componentID) const;
  37208. const MarkerList::Marker* findMarker (const String& name, MarkerList*& list) const;
  37209. private:
  37210. JUCE_DECLARE_NON_COPYABLE (ComponentScope);
  37211. };
  37212. protected:
  37213. virtual bool registerCoordinates() = 0;
  37214. virtual void applyToComponentBounds() = 0;
  37215. private:
  37216. class DependencyFinderScope;
  37217. friend class DependencyFinderScope;
  37218. Array <Component*> sourceComponents;
  37219. Array <MarkerList*> sourceMarkerLists;
  37220. bool registeredOk;
  37221. void registerComponentListener (Component& comp);
  37222. void registerMarkerListListener (MarkerList* const list);
  37223. void unregisterListeners();
  37224. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeCoordinatePositionerBase);
  37225. };
  37226. #endif // __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37227. /*** End of inlined file: juce_RelativeCoordinatePositioner.h ***/
  37228. /*** Start of inlined file: juce_ComponentBuilder.h ***/
  37229. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37230. #define __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37231. /**
  37232. Loads and maintains a tree of Components from a ValueTree that represents them.
  37233. To allow the state of a tree of components to be saved as a ValueTree and re-loaded,
  37234. this class lets you register a set of type-handlers for the different components that
  37235. are involved, and then uses these types to re-create a set of components from its
  37236. stored state.
  37237. Essentially, to use this, you need to create a ComponentBuilder with your ValueTree,
  37238. then use registerTypeHandler() to give it a set of type handlers that can cope with
  37239. all the items in your tree. Then you can call getComponent() to build the component.
  37240. Once you've got the component you can either take it and delete the ComponentBuilder
  37241. object, or if you keep the ComponentBuilder around, it'll monitor any changes in the
  37242. ValueTree and automatically update the component to reflect these changes.
  37243. */
  37244. class JUCE_API ComponentBuilder : public ValueTree::Listener
  37245. {
  37246. public:
  37247. /** Creates a ComponentBuilder that will use the given state.
  37248. Once you've created your builder, you should use registerTypeHandler() to register some
  37249. type handlers for it, and then you can call createComponent() or getManagedComponent()
  37250. to get the actual component.
  37251. */
  37252. explicit ComponentBuilder (const ValueTree& state);
  37253. /** Destructor. */
  37254. ~ComponentBuilder();
  37255. /** Returns the ValueTree that this builder is working with. */
  37256. ValueTree& getState() noexcept { return state; }
  37257. /** Returns the ValueTree that this builder is working with. */
  37258. const ValueTree& getState() const noexcept { return state; }
  37259. /** Returns the builder's component (creating it if necessary).
  37260. The first time that this method is called, the builder will attempt to create a component
  37261. from the ValueTree, so you must have registered some suitable type handlers before calling
  37262. this. If there's a problem and the component can't be created, this method returns 0.
  37263. The component that is returned is owned by this ComponentBuilder, so you can put it inside
  37264. your own parent components, but don't delete it! The ComponentBuilder will delete it automatically
  37265. when the builder is destroyed. If you want to get a component that you can delete yourself,
  37266. call createComponent() instead.
  37267. The ComponentBuilder will update this component if any changes are made to the ValueTree, so if
  37268. there's a chance that the tree might change, be careful not to keep any pointers to sub-components,
  37269. as they may be changed or removed.
  37270. */
  37271. Component* getManagedComponent();
  37272. /** Creates and returns a new instance of the component that the ValueTree represents.
  37273. The caller is responsible for using and deleting the object that is returned. Unlike
  37274. getManagedComponent(), the component that is returned will not be updated by the builder.
  37275. */
  37276. Component* createComponent();
  37277. /**
  37278. The class is a base class for objects that manage the loading of a type of component
  37279. from a ValueTree.
  37280. To store and re-load a tree of components as a ValueTree, each component type must have
  37281. a TypeHandler to represent it.
  37282. @see ComponentBuilder::registerTypeHandler(), Drawable::registerDrawableTypeHandlers()
  37283. */
  37284. class JUCE_API TypeHandler
  37285. {
  37286. public:
  37287. /** Creates a TypeHandler.
  37288. The valueTreeType must be the type name of the ValueTrees that this handler can parse.
  37289. */
  37290. explicit TypeHandler (const Identifier& valueTreeType);
  37291. /** Destructor. */
  37292. virtual ~TypeHandler();
  37293. /** Returns the type of the ValueTrees that this handler can parse. */
  37294. const Identifier& getType() const noexcept { return valueTreeType; }
  37295. /** Returns the builder that this type is registered with. */
  37296. ComponentBuilder* getBuilder() const noexcept;
  37297. /** This method must create a new component from the given state, add it to the specified
  37298. parent component (which may be null), and return it.
  37299. The ValueTree will have been pre-checked to make sure that its type matches the type
  37300. that this handler supports.
  37301. There's no need to set the new Component's ID to match that of the state - the builder
  37302. will take care of that itself.
  37303. */
  37304. virtual Component* addNewComponentFromState (const ValueTree& state, Component* parent) = 0;
  37305. /** This method must update an existing component from a new ValueTree state.
  37306. A component that has been created with addNewComponentFromState() may need to be updated
  37307. if the ValueTree changes, so this method is used to do that. Your implementation must do
  37308. whatever's necessary to update the component from the new state provided.
  37309. The ValueTree will have been pre-checked to make sure that its type matches the type
  37310. that this handler supports, and the component will have been created by this type's
  37311. addNewComponentFromState() method.
  37312. */
  37313. virtual void updateComponentFromState (Component* component, const ValueTree& state) = 0;
  37314. private:
  37315. friend class ComponentBuilder;
  37316. ComponentBuilder* builder;
  37317. const Identifier valueTreeType;
  37318. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypeHandler);
  37319. };
  37320. /** Adds a type handler that the builder can use when trying to load components.
  37321. @see Drawable::registerDrawableTypeHandlers()
  37322. */
  37323. void registerTypeHandler (TypeHandler* type);
  37324. /** Tries to find a registered type handler that can load a component from the given ValueTree. */
  37325. TypeHandler* getHandlerForState (const ValueTree& state) const;
  37326. /** Returns the number of registered type handlers.
  37327. @see getHandler, registerTypeHandler
  37328. */
  37329. int getNumHandlers() const noexcept;
  37330. /** Returns one of the registered type handlers.
  37331. @see getNumHandlers, registerTypeHandler
  37332. */
  37333. TypeHandler* getHandler (int index) const noexcept;
  37334. /** This class is used when references to images need to be stored in ValueTrees.
  37335. An instance of an ImageProvider provides a mechanism for converting an Image to/from
  37336. a reference, which may be a file, URL, ID string, or whatever system is appropriate in
  37337. your app.
  37338. When you're loading components from a ValueTree that may need a way of loading images, you
  37339. should call ComponentBuilder::setImageProvider() to supply a suitable provider before
  37340. trying to load the component.
  37341. @see ComponentBuilder::setImageProvider()
  37342. */
  37343. class JUCE_API ImageProvider
  37344. {
  37345. public:
  37346. ImageProvider() {}
  37347. virtual ~ImageProvider() {}
  37348. /** Retrieves the image associated with this identifier, which could be any
  37349. kind of string, number, filename, etc.
  37350. The image that is returned will be owned by the caller, but it may come
  37351. from the ImageCache.
  37352. */
  37353. virtual Image getImageForIdentifier (const var& imageIdentifier) = 0;
  37354. /** Returns an identifier to be used to refer to a given image.
  37355. This is used when a reference to an image is stored in a ValueTree.
  37356. */
  37357. virtual var getIdentifierForImage (const Image& image) = 0;
  37358. };
  37359. /** Gives the builder an ImageProvider object that the type handlers can use when
  37360. loading images from stored references.
  37361. The object that is passed in is not owned by the builder, so the caller must delete
  37362. it when it is no longer needed, but not while the builder may still be using it. To
  37363. clear the image provider, just call setImageProvider (nullptr).
  37364. */
  37365. void setImageProvider (ImageProvider* newImageProvider) noexcept;
  37366. /** Returns the current image provider that this builder is using, or 0 if none has been set. */
  37367. ImageProvider* getImageProvider() const noexcept;
  37368. /** Updates the children of a parent component by updating them from the children of
  37369. a given ValueTree.
  37370. */
  37371. void updateChildComponents (Component& parent, const ValueTree& children);
  37372. /** An identifier for the property of the ValueTrees that is used to store a unique ID
  37373. for that component.
  37374. */
  37375. static const Identifier idProperty;
  37376. /** @internal */
  37377. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& property);
  37378. /** @internal */
  37379. void valueTreeChildAdded (ValueTree& parentTree, ValueTree& childWhichHasBeenAdded);
  37380. /** @internal */
  37381. void valueTreeChildRemoved (ValueTree& parentTree, ValueTree& childWhichHasBeenRemoved);
  37382. /** @internal */
  37383. void valueTreeChildOrderChanged (ValueTree& parentTree);
  37384. /** @internal */
  37385. void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged);
  37386. private:
  37387. ValueTree state;
  37388. OwnedArray <TypeHandler> types;
  37389. ScopedPointer<Component> component;
  37390. ImageProvider* imageProvider;
  37391. #if JUCE_DEBUG
  37392. WeakReference<Component> componentRef;
  37393. #endif
  37394. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBuilder);
  37395. };
  37396. #endif // __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37397. /*** End of inlined file: juce_ComponentBuilder.h ***/
  37398. class DrawableComposite;
  37399. /**
  37400. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  37401. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37402. */
  37403. class JUCE_API Drawable : public Component
  37404. {
  37405. protected:
  37406. /** The base class can't be instantiated directly.
  37407. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37408. */
  37409. Drawable();
  37410. public:
  37411. /** Destructor. */
  37412. virtual ~Drawable();
  37413. /** Creates a deep copy of this Drawable object.
  37414. Use this to create a new copy of this and any sub-objects in the tree.
  37415. */
  37416. virtual Drawable* createCopy() const = 0;
  37417. /** Renders this Drawable object.
  37418. Note that the preferred way to render a drawable in future is by using it
  37419. as a component and adding it to a parent, so you might want to consider that
  37420. before using this method.
  37421. @see drawWithin
  37422. */
  37423. void draw (Graphics& g, float opacity,
  37424. const AffineTransform& transform = AffineTransform::identity) const;
  37425. /** Renders the Drawable at a given offset within the Graphics context.
  37426. The co-ordinates passed-in are used to translate the object relative to its own
  37427. origin before drawing it - this is basically a quick way of saying:
  37428. @code
  37429. draw (g, AffineTransform::translation (x, y)).
  37430. @endcode
  37431. Note that the preferred way to render a drawable in future is by using it
  37432. as a component and adding it to a parent, so you might want to consider that
  37433. before using this method.
  37434. */
  37435. void drawAt (Graphics& g, float x, float y, float opacity) const;
  37436. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  37437. changing its aspect-ratio.
  37438. The object can placed arbitrarily within the rectangle based on a Justification type,
  37439. and can either be made as big as possible, or just reduced to fit.
  37440. Note that the preferred way to render a drawable in future is by using it
  37441. as a component and adding it to a parent, so you might want to consider that
  37442. before using this method.
  37443. @param g the graphics context to render onto
  37444. @param destArea the target rectangle to fit the drawable into
  37445. @param placement defines the alignment and rescaling to use to fit
  37446. this object within the target rectangle.
  37447. @param opacity the opacity to use, in the range 0 to 1.0
  37448. */
  37449. void drawWithin (Graphics& g,
  37450. const Rectangle<float>& destArea,
  37451. const RectanglePlacement& placement,
  37452. float opacity) const;
  37453. /** Resets any transformations on this drawable, and positions its origin within
  37454. its parent component.
  37455. */
  37456. void setOriginWithOriginalSize (const Point<float>& originWithinParent);
  37457. /** Sets a transform for this drawable that will position it within the specified
  37458. area of its parent component.
  37459. */
  37460. void setTransformToFit (const Rectangle<float>& areaInParent, const RectanglePlacement& placement);
  37461. /** Returns the DrawableComposite that contains this object, if there is one. */
  37462. DrawableComposite* getParent() const;
  37463. /** Tries to turn some kind of image file into a drawable.
  37464. The data could be an image that the ImageFileFormat class understands, or it
  37465. could be SVG.
  37466. */
  37467. static Drawable* createFromImageData (const void* data, size_t numBytes);
  37468. /** Tries to turn a stream containing some kind of image data into a drawable.
  37469. The data could be an image that the ImageFileFormat class understands, or it
  37470. could be SVG.
  37471. */
  37472. static Drawable* createFromImageDataStream (InputStream& dataSource);
  37473. /** Tries to turn a file containing some kind of image data into a drawable.
  37474. The data could be an image that the ImageFileFormat class understands, or it
  37475. could be SVG.
  37476. */
  37477. static Drawable* createFromImageFile (const File& file);
  37478. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  37479. into a Drawable tree.
  37480. The object returned must be deleted by the caller. If something goes wrong
  37481. while parsing, it may return 0.
  37482. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  37483. implementation, but it can return the basic vector objects.
  37484. */
  37485. static Drawable* createFromSVG (const XmlElement& svgDocument);
  37486. /** Tries to create a Drawable from a previously-saved ValueTree.
  37487. The ValueTree must have been created by the createValueTree() method.
  37488. If there are any images used within the drawable, you'll need to provide a valid
  37489. ImageProvider object that can be used to retrieve these images from whatever type
  37490. of identifier is used to represent them.
  37491. Internally, this uses a ComponentBuilder, and registerDrawableTypeHandlers().
  37492. */
  37493. static Drawable* createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider);
  37494. /** Creates a ValueTree to represent this Drawable.
  37495. The ValueTree that is returned can be turned back into a Drawable with createFromValueTree().
  37496. If there are any images used in this drawable, you'll need to provide a valid ImageProvider
  37497. object that can be used to create storable representations of them.
  37498. */
  37499. virtual ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const = 0;
  37500. /** Returns the area that this drawble covers.
  37501. The result is expressed in this drawable's own coordinate space, and does not take
  37502. into account any transforms that may be applied to the component.
  37503. */
  37504. virtual Rectangle<float> getDrawableBounds() const = 0;
  37505. /** Internal class used to manage ValueTrees that represent Drawables. */
  37506. class ValueTreeWrapperBase
  37507. {
  37508. public:
  37509. ValueTreeWrapperBase (const ValueTree& state);
  37510. ValueTree& getState() noexcept { return state; }
  37511. String getID() const;
  37512. void setID (const String& newID);
  37513. ValueTree state;
  37514. };
  37515. /** Registers a set of ComponentBuilder::TypeHandler objects that can be used to
  37516. load all the different Drawable types from a saved state.
  37517. @see ComponentBuilder::registerTypeHandler()
  37518. */
  37519. static void registerDrawableTypeHandlers (ComponentBuilder& componentBuilder);
  37520. protected:
  37521. friend class DrawableComposite;
  37522. friend class DrawableShape;
  37523. /** @internal */
  37524. void transformContextToCorrectOrigin (Graphics& g);
  37525. /** @internal */
  37526. void parentHierarchyChanged();
  37527. /** @internal */
  37528. void setBoundsToEnclose (const Rectangle<float>& area);
  37529. Point<int> originRelativeToComponent;
  37530. #ifndef DOXYGEN
  37531. /** Internal utility class used by Drawables. */
  37532. template <class DrawableType>
  37533. class Positioner : public RelativeCoordinatePositionerBase
  37534. {
  37535. public:
  37536. Positioner (DrawableType& component_)
  37537. : RelativeCoordinatePositionerBase (component_),
  37538. owner (component_)
  37539. {}
  37540. bool registerCoordinates() { return owner.registerCoordinates (*this); }
  37541. void applyToComponentBounds()
  37542. {
  37543. ComponentScope scope (getComponent());
  37544. owner.recalculateCoordinates (&scope);
  37545. }
  37546. void applyNewBounds (const Rectangle<int>&)
  37547. {
  37548. jassertfalse; // drawables can't be resized directly!
  37549. }
  37550. private:
  37551. DrawableType& owner;
  37552. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  37553. };
  37554. #endif
  37555. private:
  37556. void nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform);
  37557. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Drawable);
  37558. };
  37559. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  37560. /*** End of inlined file: juce_Drawable.h ***/
  37561. /**
  37562. A button that displays a Drawable.
  37563. Up to three Drawable objects can be given to this button, to represent the
  37564. 'normal', 'over' and 'down' states.
  37565. @see Button
  37566. */
  37567. class JUCE_API DrawableButton : public Button
  37568. {
  37569. public:
  37570. enum ButtonStyle
  37571. {
  37572. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  37573. ImageRaw, /**< The button will just display the images in their normal size and position.
  37574. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  37575. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  37576. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  37577. };
  37578. /** Creates a DrawableButton.
  37579. After creating one of these, use setImages() to specify the drawables to use.
  37580. @param buttonName the name to give the component
  37581. @param buttonStyle the layout to use
  37582. @see ButtonStyle, setButtonStyle, setImages
  37583. */
  37584. DrawableButton (const String& buttonName,
  37585. ButtonStyle buttonStyle);
  37586. /** Destructor. */
  37587. ~DrawableButton();
  37588. /** Sets up the images to draw for the various button states.
  37589. The button will keep its own internal copies of these drawables.
  37590. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  37591. will be made of the object passed-in if it is non-zero.
  37592. @param overImage the thing to draw for the button's 'over' state - if this is
  37593. zero, the button's normal image will be used when the mouse is
  37594. over it. An internal copy will be made of the object passed-in
  37595. if it is non-zero.
  37596. @param downImage the thing to draw for the button's 'down' state - if this is
  37597. zero, the 'over' image will be used instead (or the normal image
  37598. as a last resort). An internal copy will be made of the object
  37599. passed-in if it is non-zero.
  37600. @param disabledImage an image to draw when the button is disabled. If this is zero,
  37601. the normal image will be drawn with a reduced opacity instead.
  37602. An internal copy will be made of the object passed-in if it is
  37603. non-zero.
  37604. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  37605. state is 'on'. If this is 0, the normal image is used instead
  37606. @param overImageOn same as the overImage, but this is used when the button's toggle
  37607. state is 'on'. If this is 0, the normalImageOn is drawn instead
  37608. @param downImageOn same as the downImage, but this is used when the button's toggle
  37609. state is 'on'. If this is 0, the overImageOn is drawn instead
  37610. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  37611. state is 'on'. If this is 0, the normal image will be drawn instead
  37612. with a reduced opacity
  37613. */
  37614. void setImages (const Drawable* normalImage,
  37615. const Drawable* overImage = nullptr,
  37616. const Drawable* downImage = nullptr,
  37617. const Drawable* disabledImage = nullptr,
  37618. const Drawable* normalImageOn = nullptr,
  37619. const Drawable* overImageOn = nullptr,
  37620. const Drawable* downImageOn = nullptr,
  37621. const Drawable* disabledImageOn = nullptr);
  37622. /** Changes the button's style.
  37623. @see ButtonStyle
  37624. */
  37625. void setButtonStyle (ButtonStyle newStyle);
  37626. /** Changes the button's background colours.
  37627. The toggledOffColour is the colour to use when the button's toggle state
  37628. is off, and toggledOnColour when it's on.
  37629. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  37630. used to fill the background of the component.
  37631. For an ImageOnButtonBackground style, the colour is used to draw the
  37632. button's lozenge shape and exactly how the colour's used will depend
  37633. on the LookAndFeel.
  37634. */
  37635. void setBackgroundColours (const Colour& toggledOffColour,
  37636. const Colour& toggledOnColour);
  37637. /** Returns the current background colour being used.
  37638. @see setBackgroundColour
  37639. */
  37640. const Colour& getBackgroundColour() const noexcept;
  37641. /** Gives the button an optional amount of space around the edge of the drawable.
  37642. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  37643. ones on a button background. If the button is too small for the given gap, a
  37644. smaller gap will be used.
  37645. By default there's a gap of about 3 pixels.
  37646. */
  37647. void setEdgeIndent (int numPixelsIndent);
  37648. /** Returns the image that the button is currently displaying. */
  37649. Drawable* getCurrentImage() const noexcept;
  37650. Drawable* getNormalImage() const noexcept;
  37651. Drawable* getOverImage() const noexcept;
  37652. Drawable* getDownImage() const noexcept;
  37653. /** A set of colour IDs to use to change the colour of various aspects of the link.
  37654. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37655. methods.
  37656. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37657. */
  37658. enum ColourIds
  37659. {
  37660. textColourId = 0x1004010, /**< The colour to use for the URL text. */
  37661. };
  37662. protected:
  37663. /** @internal */
  37664. void paintButton (Graphics& g,
  37665. bool isMouseOverButton,
  37666. bool isButtonDown);
  37667. /** @internal */
  37668. void buttonStateChanged();
  37669. /** @internal */
  37670. void resized();
  37671. private:
  37672. ButtonStyle style;
  37673. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  37674. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  37675. Drawable* currentImage;
  37676. Colour backgroundOff, backgroundOn;
  37677. int edgeIndent;
  37678. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DrawableButton);
  37679. };
  37680. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  37681. /*** End of inlined file: juce_DrawableButton.h ***/
  37682. #endif
  37683. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37684. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  37685. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37686. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37687. /**
  37688. A button showing an underlined weblink, that will launch the link
  37689. when it's clicked.
  37690. @see Button
  37691. */
  37692. class JUCE_API HyperlinkButton : public Button
  37693. {
  37694. public:
  37695. /** Creates a HyperlinkButton.
  37696. @param linkText the text that will be displayed in the button - this is
  37697. also set as the Component's name, but the text can be
  37698. changed later with the Button::getButtonText() method
  37699. @param linkURL the URL to launch when the user clicks the button
  37700. */
  37701. HyperlinkButton (const String& linkText,
  37702. const URL& linkURL);
  37703. /** Destructor. */
  37704. ~HyperlinkButton();
  37705. /** Changes the font to use for the text.
  37706. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  37707. to match the size of the component.
  37708. */
  37709. void setFont (const Font& newFont,
  37710. bool resizeToMatchComponentHeight,
  37711. const Justification& justificationType = Justification::horizontallyCentred);
  37712. /** A set of colour IDs to use to change the colour of various aspects of the link.
  37713. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37714. methods.
  37715. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37716. */
  37717. enum ColourIds
  37718. {
  37719. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  37720. };
  37721. /** Changes the URL that the button will trigger. */
  37722. void setURL (const URL& newURL) noexcept;
  37723. /** Returns the URL that the button will trigger. */
  37724. const URL& getURL() const noexcept { return url; }
  37725. /** Resizes the button horizontally to fit snugly around the text.
  37726. This won't affect the button's height.
  37727. */
  37728. void changeWidthToFitText();
  37729. protected:
  37730. /** @internal */
  37731. void clicked();
  37732. /** @internal */
  37733. void colourChanged();
  37734. /** @internal */
  37735. void paintButton (Graphics& g,
  37736. bool isMouseOverButton,
  37737. bool isButtonDown);
  37738. private:
  37739. URL url;
  37740. Font font;
  37741. bool resizeFont;
  37742. Justification justification;
  37743. Font getFontToUse() const;
  37744. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HyperlinkButton);
  37745. };
  37746. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37747. /*** End of inlined file: juce_HyperlinkButton.h ***/
  37748. #endif
  37749. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  37750. /*** Start of inlined file: juce_ImageButton.h ***/
  37751. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  37752. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  37753. /**
  37754. As the title suggests, this is a button containing an image.
  37755. The colour and transparency of the image can be set to vary when the
  37756. button state changes.
  37757. @see Button, ShapeButton, TextButton
  37758. */
  37759. class JUCE_API ImageButton : public Button
  37760. {
  37761. public:
  37762. /** Creates an ImageButton.
  37763. Use setImage() to specify the image to use. The colours and opacities that
  37764. are specified here can be changed later using setDrawingOptions().
  37765. @param name the name to give the component
  37766. */
  37767. explicit ImageButton (const String& name);
  37768. /** Destructor. */
  37769. ~ImageButton();
  37770. /** Sets up the images to draw in various states.
  37771. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  37772. resized to the same dimensions as the normal image
  37773. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  37774. button when the button's size changes
  37775. @param preserveImageProportions if true then any rescaling of the image to fit
  37776. the button will keep the image's x and y proportions
  37777. correct - i.e. it won't distort its shape, although
  37778. this might create gaps around the edges
  37779. @param normalImage the image to use when the button is in its normal state.
  37780. button no longer needs it.
  37781. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  37782. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  37783. normal image - if this colour is transparent, no overlay
  37784. will be drawn. The overlay will be drawn over the top of the
  37785. image, so you can basically add a solid or semi-transparent
  37786. colour to the image to brighten or darken it
  37787. @param overImage the image to use when the mouse is over the button. If
  37788. you want to use the same image as was set in the normalImage
  37789. parameter, this value can be a null image.
  37790. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  37791. is over the button
  37792. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  37793. image when the mouse is over - if this colour is transparent,
  37794. no overlay will be drawn
  37795. @param downImage an image to use when the button is pressed down. If set
  37796. to a null image, the 'over' image will be drawn instead (or the
  37797. normal image if there isn't an 'over' image either).
  37798. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  37799. is pressed
  37800. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  37801. image when the button is pressed down - if this colour is
  37802. transparent, no overlay will be drawn
  37803. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  37804. whenever it's inside the button's bounding rectangle. If
  37805. set to values higher than 0, the mouse will only be
  37806. considered to be over the image when the value of the
  37807. image's alpha channel at that position is greater than
  37808. this level.
  37809. */
  37810. void setImages (bool resizeButtonNowToFitThisImage,
  37811. bool rescaleImagesWhenButtonSizeChanges,
  37812. bool preserveImageProportions,
  37813. const Image& normalImage,
  37814. float imageOpacityWhenNormal,
  37815. const Colour& overlayColourWhenNormal,
  37816. const Image& overImage,
  37817. float imageOpacityWhenOver,
  37818. const Colour& overlayColourWhenOver,
  37819. const Image& downImage,
  37820. float imageOpacityWhenDown,
  37821. const Colour& overlayColourWhenDown,
  37822. float hitTestAlphaThreshold = 0.0f);
  37823. /** Returns the currently set 'normal' image. */
  37824. Image getNormalImage() const;
  37825. /** Returns the image that's drawn when the mouse is over the button.
  37826. If a valid 'over' image has been set, this will return it; otherwise it'll
  37827. just return the normal image.
  37828. */
  37829. Image getOverImage() const;
  37830. /** Returns the image that's drawn when the button is held down.
  37831. If a valid 'down' image has been set, this will return it; otherwise it'll
  37832. return the 'over' image or normal image, depending on what's available.
  37833. */
  37834. Image getDownImage() const;
  37835. protected:
  37836. /** @internal */
  37837. bool hitTest (int x, int y);
  37838. /** @internal */
  37839. void paintButton (Graphics& g,
  37840. bool isMouseOverButton,
  37841. bool isButtonDown);
  37842. private:
  37843. bool scaleImageToFit, preserveProportions;
  37844. unsigned char alphaThreshold;
  37845. int imageX, imageY, imageW, imageH;
  37846. Image normalImage, overImage, downImage;
  37847. float normalOpacity, overOpacity, downOpacity;
  37848. Colour normalOverlay, overOverlay, downOverlay;
  37849. Image getCurrentImage() const;
  37850. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageButton);
  37851. };
  37852. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  37853. /*** End of inlined file: juce_ImageButton.h ***/
  37854. #endif
  37855. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  37856. /*** Start of inlined file: juce_ShapeButton.h ***/
  37857. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  37858. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  37859. /**
  37860. A button that contains a filled shape.
  37861. @see Button, ImageButton, TextButton, ArrowButton
  37862. */
  37863. class JUCE_API ShapeButton : public Button
  37864. {
  37865. public:
  37866. /** Creates a ShapeButton.
  37867. @param name a name to give the component - see Component::setName()
  37868. @param normalColour the colour to fill the shape with when the mouse isn't over
  37869. @param overColour the colour to use when the mouse is over the shape
  37870. @param downColour the colour to use when the button is in the pressed-down state
  37871. */
  37872. ShapeButton (const String& name,
  37873. const Colour& normalColour,
  37874. const Colour& overColour,
  37875. const Colour& downColour);
  37876. /** Destructor. */
  37877. ~ShapeButton();
  37878. /** Sets the shape to use.
  37879. @param newShape the shape to use
  37880. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  37881. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  37882. the button is resized
  37883. @param hasDropShadow if true, the button will be given a drop-shadow effect
  37884. */
  37885. void setShape (const Path& newShape,
  37886. bool resizeNowToFitThisShape,
  37887. bool maintainShapeProportions,
  37888. bool hasDropShadow);
  37889. /** Set the colours to use for drawing the shape.
  37890. @param normalColour the colour to fill the shape with when the mouse isn't over
  37891. @param overColour the colour to use when the mouse is over the shape
  37892. @param downColour the colour to use when the button is in the pressed-down state
  37893. */
  37894. void setColours (const Colour& normalColour,
  37895. const Colour& overColour,
  37896. const Colour& downColour);
  37897. /** Sets up an outline to draw around the shape.
  37898. @param outlineColour the colour to use
  37899. @param outlineStrokeWidth the thickness of line to draw
  37900. */
  37901. void setOutline (const Colour& outlineColour,
  37902. float outlineStrokeWidth);
  37903. protected:
  37904. /** @internal */
  37905. void paintButton (Graphics& g,
  37906. bool isMouseOverButton,
  37907. bool isButtonDown);
  37908. private:
  37909. Colour normalColour, overColour, downColour, outlineColour;
  37910. DropShadowEffect shadow;
  37911. Path shape;
  37912. bool maintainShapeProportions;
  37913. float outlineWidth;
  37914. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ShapeButton);
  37915. };
  37916. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  37917. /*** End of inlined file: juce_ShapeButton.h ***/
  37918. #endif
  37919. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  37920. #endif
  37921. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37922. /*** Start of inlined file: juce_ToggleButton.h ***/
  37923. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37924. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37925. /**
  37926. A button that can be toggled on/off.
  37927. All buttons can be toggle buttons, but this lets you create one of the
  37928. standard ones which has a tick-box and a text label next to it.
  37929. @see Button, DrawableButton, TextButton
  37930. */
  37931. class JUCE_API ToggleButton : public Button
  37932. {
  37933. public:
  37934. /** Creates a ToggleButton.
  37935. @param buttonText the text to put in the button (the component's name is also
  37936. initially set to this string, but these can be changed later
  37937. using the setName() and setButtonText() methods)
  37938. */
  37939. explicit ToggleButton (const String& buttonText = String::empty);
  37940. /** Destructor. */
  37941. ~ToggleButton();
  37942. /** Resizes the button to fit neatly around its current text.
  37943. The button's height won't be affected, only its width.
  37944. */
  37945. void changeWidthToFitText();
  37946. /** A set of colour IDs to use to change the colour of various aspects of the button.
  37947. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37948. methods.
  37949. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37950. */
  37951. enum ColourIds
  37952. {
  37953. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  37954. };
  37955. protected:
  37956. /** @internal */
  37957. void paintButton (Graphics& g,
  37958. bool isMouseOverButton,
  37959. bool isButtonDown);
  37960. /** @internal */
  37961. void colourChanged();
  37962. private:
  37963. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToggleButton);
  37964. };
  37965. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37966. /*** End of inlined file: juce_ToggleButton.h ***/
  37967. #endif
  37968. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37969. /*** Start of inlined file: juce_ToolbarButton.h ***/
  37970. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37971. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37972. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  37973. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  37974. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  37975. /*** Start of inlined file: juce_Toolbar.h ***/
  37976. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  37977. #define __JUCE_TOOLBAR_JUCEHEADER__
  37978. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  37979. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  37980. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  37981. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  37982. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37983. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37984. /**
  37985. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  37986. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  37987. derive your component from this class, and make sure that it is somewhere inside a
  37988. DragAndDropContainer component.
  37989. Note: If all that you need to do is to respond to files being drag-and-dropped from
  37990. the operating system onto your component, you don't need any of these classes: instead
  37991. see the FileDragAndDropTarget class.
  37992. @see DragAndDropContainer, FileDragAndDropTarget
  37993. */
  37994. class JUCE_API DragAndDropTarget
  37995. {
  37996. public:
  37997. /** Destructor. */
  37998. virtual ~DragAndDropTarget() {}
  37999. /** Contains details about the source of a drag-and-drop operation.
  38000. The contents of this
  38001. */
  38002. class JUCE_API SourceDetails
  38003. {
  38004. public:
  38005. /** Creates a SourceDetails object from its various settings. */
  38006. SourceDetails (const var& description, Component* sourceComponent, const Point<int>& localPosition) noexcept;
  38007. /** A descriptor for the drag - this is set DragAndDropContainer::startDragging(). */
  38008. var description;
  38009. /** The component from the drag operation was started. */
  38010. WeakReference<Component> sourceComponent;
  38011. /** The local position of the mouse, relative to the target component.
  38012. Note that for calls such as isInterestedInDragSource(), this may be a null position.
  38013. */
  38014. Point<int> localPosition;
  38015. };
  38016. /** Callback to check whether this target is interested in the type of object being
  38017. dragged.
  38018. @param dragSourceDetails contains information about the source of the drag operation.
  38019. @returns true if this component wants to receive the other callbacks regarging this
  38020. type of object; if it returns false, no other callbacks will be made.
  38021. */
  38022. virtual bool isInterestedInDragSource (const SourceDetails& dragSourceDetails) = 0;
  38023. /** Callback to indicate that something is being dragged over this component.
  38024. This gets called when the user moves the mouse into this component while dragging
  38025. something.
  38026. Use this callback as a trigger to make your component repaint itself to give the
  38027. user feedback about whether the item can be dropped here or not.
  38028. @param dragSourceDetails contains information about the source of the drag operation.
  38029. @see itemDragExit
  38030. */
  38031. virtual void itemDragEnter (const SourceDetails& dragSourceDetails);
  38032. /** Callback to indicate that the user is dragging something over this component.
  38033. This gets called when the user moves the mouse over this component while dragging
  38034. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  38035. this lets you know what happens in-between.
  38036. @param dragSourceDetails contains information about the source of the drag operation.
  38037. */
  38038. virtual void itemDragMove (const SourceDetails& dragSourceDetails);
  38039. /** Callback to indicate that something has been dragged off the edge of this component.
  38040. This gets called when the user moves the mouse out of this component while dragging
  38041. something.
  38042. If you've used itemDragEnter() to repaint your component and give feedback, use this
  38043. as a signal to repaint it in its normal state.
  38044. @param dragSourceDetails contains information about the source of the drag operation.
  38045. @see itemDragEnter
  38046. */
  38047. virtual void itemDragExit (const SourceDetails& dragSourceDetails);
  38048. /** Callback to indicate that the user has dropped something onto this component.
  38049. When the user drops an item this get called, and you can use the description to
  38050. work out whether your object wants to deal with it or not.
  38051. Note that after this is called, the itemDragExit method may not be called, so you should
  38052. clean up in here if there's anything you need to do when the drag finishes.
  38053. @param dragSourceDetails contains information about the source of the drag operation.
  38054. */
  38055. virtual void itemDropped (const SourceDetails& dragSourceDetails) = 0;
  38056. /** Overriding this allows the target to tell the drag container whether to
  38057. draw the drag image while the cursor is over it.
  38058. By default it returns true, but if you return false, then the normal drag
  38059. image will not be shown when the cursor is over this target.
  38060. */
  38061. virtual bool shouldDrawDragImageWhenOver();
  38062. private:
  38063. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  38064. // The parameters for these methods have changed - please update your code!
  38065. virtual void isInterestedInDragSource (const String&, Component*) {}
  38066. virtual int itemDragEnter (const String&, Component*, int, int) { return 0; }
  38067. virtual int itemDragMove (const String&, Component*, int, int) { return 0; }
  38068. virtual int itemDragExit (const String&, Component*) { return 0; }
  38069. virtual int itemDropped (const String&, Component*, int, int) { return 0; }
  38070. #endif
  38071. };
  38072. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  38073. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  38074. /**
  38075. Enables drag-and-drop behaviour for a component and all its sub-components.
  38076. For a component to be able to make or receive drag-and-drop events, one of its parent
  38077. components must derive from this class. It's probably best for the top-level
  38078. component to implement it.
  38079. Then to start a drag operation, any sub-component can just call the startDragging()
  38080. method, and this object will take over, tracking the mouse and sending appropriate
  38081. callbacks to any child components derived from DragAndDropTarget which the mouse
  38082. moves over.
  38083. Note: If all that you need to do is to respond to files being drag-and-dropped from
  38084. the operating system onto your component, you don't need any of these classes: you can do this
  38085. simply by overriding Component::filesDropped().
  38086. @see DragAndDropTarget
  38087. */
  38088. class JUCE_API DragAndDropContainer
  38089. {
  38090. public:
  38091. /** Creates a DragAndDropContainer.
  38092. The object that derives from this class must also be a Component.
  38093. */
  38094. DragAndDropContainer();
  38095. /** Destructor. */
  38096. virtual ~DragAndDropContainer();
  38097. /** Begins a drag-and-drop operation.
  38098. This starts a drag-and-drop operation - call it when the user drags the
  38099. mouse in your drag-source component, and this object will track mouse
  38100. movements until the user lets go of the mouse button, and will send
  38101. appropriate messages to DragAndDropTarget objects that the mouse moves
  38102. over.
  38103. findParentDragContainerFor() is a handy method to call to find the
  38104. drag container to use for a component.
  38105. @param sourceDescription a string or value to use as the description of the thing being dragged -
  38106. this will be passed to the objects that might be dropped-onto so they can
  38107. decide whether they want to handle it
  38108. @param sourceComponent the component that is being dragged
  38109. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  38110. a snapshot of the sourceComponent will be used instead.
  38111. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  38112. window, and can be dragged to DragAndDropTargets that are the
  38113. children of components other than this one.
  38114. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  38115. at which the image should be drawn from the mouse. If it isn't
  38116. specified, then the image will be centred around the mouse. If
  38117. an image hasn't been passed-in, this will be ignored.
  38118. */
  38119. void startDragging (const var& sourceDescription,
  38120. Component* sourceComponent,
  38121. const Image& dragImage = Image::null,
  38122. bool allowDraggingToOtherJuceWindows = false,
  38123. const Point<int>* imageOffsetFromMouse = nullptr);
  38124. /** Returns true if something is currently being dragged. */
  38125. bool isDragAndDropActive() const;
  38126. /** Returns the description of the thing that's currently being dragged.
  38127. If nothing's being dragged, this will return an empty string, otherwise it's the
  38128. string that was passed into startDragging().
  38129. @see startDragging
  38130. */
  38131. String getCurrentDragDescription() const;
  38132. /** Utility to find the DragAndDropContainer for a given Component.
  38133. This will search up this component's parent hierarchy looking for the first
  38134. parent component which is a DragAndDropContainer.
  38135. It's useful when a component wants to call startDragging but doesn't know
  38136. the DragAndDropContainer it should to use.
  38137. Obviously this may return 0 if it doesn't find a suitable component.
  38138. */
  38139. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  38140. /** This performs a synchronous drag-and-drop of a set of files to some external
  38141. application.
  38142. You can call this function in response to a mouseDrag callback, and it will
  38143. block, running its own internal message loop and tracking the mouse, while it
  38144. uses a native operating system drag-and-drop operation to move or copy some
  38145. files to another application.
  38146. @param files a list of filenames to drag
  38147. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  38148. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  38149. @returns true if the files were successfully dropped somewhere, or false if it
  38150. was interrupted
  38151. @see performExternalDragDropOfText
  38152. */
  38153. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  38154. /** This performs a synchronous drag-and-drop of a block of text to some external
  38155. application.
  38156. You can call this function in response to a mouseDrag callback, and it will
  38157. block, running its own internal message loop and tracking the mouse, while it
  38158. uses a native operating system drag-and-drop operation to move or copy some
  38159. text to another application.
  38160. @param text the text to copy
  38161. @returns true if the text was successfully dropped somewhere, or false if it
  38162. was interrupted
  38163. @see performExternalDragDropOfFiles
  38164. */
  38165. static bool performExternalDragDropOfText (const String& text);
  38166. protected:
  38167. /** Override this if you want to be able to perform an external drag a set of files
  38168. when the user drags outside of this container component.
  38169. This method will be called when a drag operation moves outside the Juce-based window,
  38170. and if you want it to then perform a file drag-and-drop, add the filenames you want
  38171. to the array passed in, and return true.
  38172. @param sourceDetails information about the source of the drag operation
  38173. @param files on return, the filenames you want to drag
  38174. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  38175. it must make a copy of them (see the performExternalDragDropOfFiles() method)
  38176. @see performExternalDragDropOfFiles
  38177. */
  38178. virtual bool shouldDropFilesWhenDraggedExternally (const DragAndDropTarget::SourceDetails& sourceDetails,
  38179. StringArray& files, bool& canMoveFiles);
  38180. private:
  38181. friend class DragImageComponent;
  38182. ScopedPointer <Component> dragImageComponent;
  38183. String currentDragDesc;
  38184. JUCE_DEPRECATED (virtual bool shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)) { return false; }
  38185. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DragAndDropContainer);
  38186. };
  38187. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38188. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  38189. class ToolbarItemComponent;
  38190. class ToolbarItemFactory;
  38191. /**
  38192. A toolbar component.
  38193. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  38194. and looks after their order and layout.
  38195. Items (icon buttons or other custom components) are added to a toolbar using a
  38196. ToolbarItemFactory - each type of item is given a unique ID number, and a
  38197. toolbar might contain more than one instance of a particular item type.
  38198. Toolbars can be interactively customised, allowing the user to drag the items
  38199. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  38200. component as a source of new items.
  38201. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  38202. */
  38203. class JUCE_API Toolbar : public Component,
  38204. public DragAndDropContainer,
  38205. public DragAndDropTarget,
  38206. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  38207. {
  38208. public:
  38209. /** Creates an empty toolbar component.
  38210. To add some icons or other components to your toolbar, you'll need to
  38211. create a ToolbarItemFactory class that can create a suitable set of
  38212. ToolbarItemComponents.
  38213. @see ToolbarItemFactory, ToolbarItemComponents
  38214. */
  38215. Toolbar();
  38216. /** Destructor.
  38217. Any items on the bar will be deleted when the toolbar is deleted.
  38218. */
  38219. ~Toolbar();
  38220. /** Changes the bar's orientation.
  38221. @see isVertical
  38222. */
  38223. void setVertical (bool shouldBeVertical);
  38224. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  38225. You can change the bar's orientation with setVertical().
  38226. */
  38227. bool isVertical() const noexcept { return vertical; }
  38228. /** Returns the depth of the bar.
  38229. If the bar is horizontal, this will return its height; if it's vertical, it
  38230. will return its width.
  38231. @see getLength
  38232. */
  38233. int getThickness() const noexcept;
  38234. /** Returns the length of the bar.
  38235. If the bar is horizontal, this will return its width; if it's vertical, it
  38236. will return its height.
  38237. @see getThickness
  38238. */
  38239. int getLength() const noexcept;
  38240. /** Deletes all items from the bar.
  38241. */
  38242. void clear();
  38243. /** Adds an item to the toolbar.
  38244. The factory's ToolbarItemFactory::createItem() will be called by this method
  38245. to create the component that will actually be added to the bar.
  38246. The new item will be inserted at the specified index (if the index is -1, it
  38247. will be added to the right-hand or bottom end of the bar).
  38248. Once added, the component will be automatically deleted by this object when it
  38249. is no longer needed.
  38250. @see ToolbarItemFactory
  38251. */
  38252. void addItem (ToolbarItemFactory& factory,
  38253. int itemId,
  38254. int insertIndex = -1);
  38255. /** Deletes one of the items from the bar.
  38256. */
  38257. void removeToolbarItem (int itemIndex);
  38258. /** Returns the number of items currently on the toolbar.
  38259. @see getItemId, getItemComponent
  38260. */
  38261. int getNumItems() const noexcept;
  38262. /** Returns the ID of the item with the given index.
  38263. If the index is less than zero or greater than the number of items,
  38264. this will return 0.
  38265. @see getNumItems
  38266. */
  38267. int getItemId (int itemIndex) const noexcept;
  38268. /** Returns the component being used for the item with the given index.
  38269. If the index is less than zero or greater than the number of items,
  38270. this will return 0.
  38271. @see getNumItems
  38272. */
  38273. ToolbarItemComponent* getItemComponent (int itemIndex) const noexcept;
  38274. /** Clears this toolbar and adds to it the default set of items that the specified
  38275. factory creates.
  38276. @see ToolbarItemFactory::getDefaultItemSet
  38277. */
  38278. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  38279. /** Options for the way items should be displayed.
  38280. @see setStyle, getStyle
  38281. */
  38282. enum ToolbarItemStyle
  38283. {
  38284. iconsOnly, /**< Means that the toolbar should just contain icons. */
  38285. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  38286. textOnly /**< Means that the toolbar only display text labels for each item. */
  38287. };
  38288. /** Returns the toolbar's current style.
  38289. @see ToolbarItemStyle, setStyle
  38290. */
  38291. ToolbarItemStyle getStyle() const noexcept { return toolbarStyle; }
  38292. /** Changes the toolbar's current style.
  38293. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  38294. */
  38295. void setStyle (const ToolbarItemStyle& newStyle);
  38296. /** Flags used by the showCustomisationDialog() method. */
  38297. enum CustomisationFlags
  38298. {
  38299. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  38300. show the "icons only" option on its choice of toolbar styles. */
  38301. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  38302. show the "icons with text" option on its choice of toolbar styles. */
  38303. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  38304. show the "text only" option on its choice of toolbar styles. */
  38305. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  38306. show a button to reset the toolbar to its default set of items. */
  38307. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  38308. };
  38309. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  38310. The dialog contains a ToolbarItemPalette and various controls for editing other
  38311. aspects of the toolbar. This method will block and run the dialog box modally,
  38312. returning when the user closes it.
  38313. The factory is used to determine the set of items that will be shown on the
  38314. palette.
  38315. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  38316. enum.
  38317. @see ToolbarItemPalette
  38318. */
  38319. void showCustomisationDialog (ToolbarItemFactory& factory,
  38320. int optionFlags = allCustomisationOptionsEnabled);
  38321. /** Turns on or off the toolbar's editing mode, in which its items can be
  38322. rearranged by the user.
  38323. (In most cases it's easier just to use showCustomisationDialog() instead of
  38324. trying to enable editing directly).
  38325. @see ToolbarItemPalette
  38326. */
  38327. void setEditingActive (bool editingEnabled);
  38328. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  38329. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38330. methods.
  38331. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38332. */
  38333. enum ColourIds
  38334. {
  38335. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  38336. more control over this, override LookAndFeel::paintToolbarBackground(). */
  38337. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  38338. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  38339. over them. */
  38340. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  38341. held down on them. */
  38342. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  38343. when the style is set to iconsWithText or textOnly. */
  38344. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  38345. the customisation dialog is active and the mouse moves over them. */
  38346. };
  38347. /** Returns a string that represents the toolbar's current set of items.
  38348. This lets you later restore the same item layout using restoreFromString().
  38349. @see restoreFromString
  38350. */
  38351. String toString() const;
  38352. /** Restores a set of items that was previously stored in a string by the toString()
  38353. method.
  38354. The factory object is used to create any item components that are needed.
  38355. @see toString
  38356. */
  38357. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  38358. const String& savedVersion);
  38359. /** @internal */
  38360. void paint (Graphics& g);
  38361. /** @internal */
  38362. void resized();
  38363. /** @internal */
  38364. void buttonClicked (Button*);
  38365. /** @internal */
  38366. void mouseDown (const MouseEvent&);
  38367. /** @internal */
  38368. bool isInterestedInDragSource (const SourceDetails&);
  38369. /** @internal */
  38370. void itemDragMove (const SourceDetails&);
  38371. /** @internal */
  38372. void itemDragExit (const SourceDetails&);
  38373. /** @internal */
  38374. void itemDropped (const SourceDetails&);
  38375. /** @internal */
  38376. void updateAllItemPositions (bool animate);
  38377. /** @internal */
  38378. static ToolbarItemComponent* createItem (ToolbarItemFactory&, int itemId);
  38379. private:
  38380. ScopedPointer<Button> missingItemsButton;
  38381. bool vertical, isEditingActive;
  38382. ToolbarItemStyle toolbarStyle;
  38383. class MissingItemsComponent;
  38384. friend class MissingItemsComponent;
  38385. OwnedArray <ToolbarItemComponent> items;
  38386. friend class ItemDragAndDropOverlayComponent;
  38387. static const char* const toolbarDragDescriptor;
  38388. void addItemInternal (ToolbarItemFactory& factory, int itemId, int insertIndex);
  38389. ToolbarItemComponent* getNextActiveComponent (int index, int delta) const;
  38390. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Toolbar);
  38391. };
  38392. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  38393. /*** End of inlined file: juce_Toolbar.h ***/
  38394. class ItemDragAndDropOverlayComponent;
  38395. /**
  38396. A component that can be used as one of the items in a Toolbar.
  38397. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  38398. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  38399. class for further info about creating them.
  38400. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  38401. components too. To do this, set the value of isBeingUsedAsAButton to false when
  38402. calling the constructor, and override contentAreaChanged(), in which you can position
  38403. any sub-components you need to add.
  38404. To add basic buttons without writing a special subclass, have a look at the
  38405. ToolbarButton class.
  38406. @see ToolbarButton, Toolbar, ToolbarItemFactory
  38407. */
  38408. class JUCE_API ToolbarItemComponent : public Button
  38409. {
  38410. public:
  38411. /** Constructor.
  38412. @param itemId the ID of the type of toolbar item which this represents
  38413. @param labelText the text to display if the toolbar's style is set to
  38414. Toolbar::iconsWithText or Toolbar::textOnly
  38415. @param isBeingUsedAsAButton set this to false if you don't want the button
  38416. to draw itself with button over/down states when the mouse
  38417. moves over it or clicks
  38418. */
  38419. ToolbarItemComponent (int itemId,
  38420. const String& labelText,
  38421. bool isBeingUsedAsAButton);
  38422. /** Destructor. */
  38423. ~ToolbarItemComponent();
  38424. /** Returns the item type ID that this component represents.
  38425. This value is in the constructor.
  38426. */
  38427. int getItemId() const noexcept { return itemId; }
  38428. /** Returns the toolbar that contains this component, or 0 if it's not currently
  38429. inside one.
  38430. */
  38431. Toolbar* getToolbar() const;
  38432. /** Returns true if this component is currently inside a toolbar which is vertical.
  38433. @see Toolbar::isVertical
  38434. */
  38435. bool isToolbarVertical() const;
  38436. /** Returns the current style setting of this item.
  38437. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  38438. @see setStyle, Toolbar::getStyle
  38439. */
  38440. Toolbar::ToolbarItemStyle getStyle() const noexcept { return toolbarStyle; }
  38441. /** Changes the current style setting of this item.
  38442. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  38443. by the toolbar that holds this item.
  38444. @see setStyle, Toolbar::setStyle
  38445. */
  38446. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  38447. /** Returns the area of the component that should be used to display the button image or
  38448. other contents of the item.
  38449. This content area may change when the item's style changes, and may leave a space around the
  38450. edge of the component where the text label can be shown.
  38451. @see contentAreaChanged
  38452. */
  38453. const Rectangle<int> getContentArea() const noexcept { return contentArea; }
  38454. /** This method must return the size criteria for this item, based on a given toolbar
  38455. size and orientation.
  38456. The preferredSize, minSize and maxSize values must all be set by your implementation
  38457. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  38458. toolbar, they refer to the item's height.
  38459. The preferredSize is the size that the component would like to be, and this must be
  38460. between the min and max sizes. For a fixed-size item, simply set all three variables to
  38461. the same value.
  38462. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  38463. Toolbar::getThickness().
  38464. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  38465. vertically.
  38466. */
  38467. virtual bool getToolbarItemSizes (int toolbarThickness,
  38468. bool isToolbarVertical,
  38469. int& preferredSize,
  38470. int& minSize,
  38471. int& maxSize) = 0;
  38472. /** Your subclass should use this method to draw its content area.
  38473. The graphics object that is passed-in will have been clipped and had its origin
  38474. moved to fit the content area as specified get getContentArea(). The width and height
  38475. parameters are the width and height of the content area.
  38476. If the component you're writing isn't a button, you can just do nothing in this method.
  38477. */
  38478. virtual void paintButtonArea (Graphics& g,
  38479. int width, int height,
  38480. bool isMouseOver, bool isMouseDown) = 0;
  38481. /** Callback to indicate that the content area of this item has changed.
  38482. This might be because the component was resized, or because the style changed and
  38483. the space needed for the text label is different.
  38484. See getContentArea() for a description of what the area is.
  38485. */
  38486. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  38487. /** Editing modes.
  38488. These are used by setEditingMode(), but will be rarely needed in user code.
  38489. */
  38490. enum ToolbarEditingMode
  38491. {
  38492. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  38493. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  38494. customisation mode, and the items can be dragged around. */
  38495. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  38496. dragged onto a toolbar to add it to that bar.*/
  38497. };
  38498. /** Changes the editing mode of this component.
  38499. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  38500. and is unlikely to be of much use in end-user-code.
  38501. */
  38502. void setEditingMode (const ToolbarEditingMode newMode);
  38503. /** Returns the current editing mode of this component.
  38504. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  38505. and is unlikely to be of much use in end-user-code.
  38506. */
  38507. ToolbarEditingMode getEditingMode() const noexcept { return mode; }
  38508. /** @internal */
  38509. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  38510. /** @internal */
  38511. void resized();
  38512. private:
  38513. friend class Toolbar;
  38514. friend class ItemDragAndDropOverlayComponent;
  38515. const int itemId;
  38516. ToolbarEditingMode mode;
  38517. Toolbar::ToolbarItemStyle toolbarStyle;
  38518. ScopedPointer <Component> overlayComp;
  38519. int dragOffsetX, dragOffsetY;
  38520. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  38521. Rectangle<int> contentArea;
  38522. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemComponent);
  38523. };
  38524. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  38525. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  38526. /**
  38527. A type of button designed to go on a toolbar.
  38528. This simple button can have two Drawable objects specified - one for normal
  38529. use and another one (optionally) for the button's "on" state if it's a
  38530. toggle button.
  38531. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  38532. */
  38533. class JUCE_API ToolbarButton : public ToolbarItemComponent
  38534. {
  38535. public:
  38536. /** Creates a ToolbarButton.
  38537. @param itemId the ID for this toolbar item type. This is passed through to the
  38538. ToolbarItemComponent constructor
  38539. @param labelText the text to display on the button (if the toolbar is using a style
  38540. that shows text labels). This is passed through to the
  38541. ToolbarItemComponent constructor
  38542. @param normalImage a drawable object that the button should use as its icon. The object
  38543. that is passed-in here will be kept by this object and will be
  38544. deleted when no longer needed or when this button is deleted.
  38545. @param toggledOnImage a drawable object that the button can use as its icon if the button
  38546. is in a toggled-on state (see the Button::getToggleState() method). If
  38547. 0 is passed-in here, then the normal image will be used instead, regardless
  38548. of the toggle state. The object that is passed-in here will be kept by
  38549. this object and will be deleted when no longer needed or when this button
  38550. is deleted.
  38551. */
  38552. ToolbarButton (int itemId,
  38553. const String& labelText,
  38554. Drawable* normalImage,
  38555. Drawable* toggledOnImage);
  38556. /** Destructor. */
  38557. ~ToolbarButton();
  38558. /** @internal */
  38559. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  38560. int& minSize, int& maxSize);
  38561. /** @internal */
  38562. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  38563. /** @internal */
  38564. void contentAreaChanged (const Rectangle<int>& newBounds);
  38565. /** @internal */
  38566. void buttonStateChanged();
  38567. /** @internal */
  38568. void resized();
  38569. /** @internal */
  38570. void enablementChanged();
  38571. private:
  38572. ScopedPointer<Drawable> normalImage, toggledOnImage;
  38573. Drawable* currentImage;
  38574. void updateDrawable();
  38575. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarButton);
  38576. };
  38577. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38578. /*** End of inlined file: juce_ToolbarButton.h ***/
  38579. #endif
  38580. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  38581. /*** Start of inlined file: juce_CodeDocument.h ***/
  38582. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  38583. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  38584. class CodeDocumentLine;
  38585. /**
  38586. A class for storing and manipulating a source code file.
  38587. When using a CodeEditorComponent, it takes one of these as its source object.
  38588. The CodeDocument stores its content as an array of lines, which makes it
  38589. quick to insert and delete.
  38590. @see CodeEditorComponent
  38591. */
  38592. class JUCE_API CodeDocument
  38593. {
  38594. public:
  38595. /** Creates a new, empty document.
  38596. */
  38597. CodeDocument();
  38598. /** Destructor. */
  38599. ~CodeDocument();
  38600. /** A position in a code document.
  38601. Using this class you can find a position in a code document and quickly get its
  38602. character position, line, and index. By calling setPositionMaintained (true), the
  38603. position is automatically updated when text is inserted or deleted in the document,
  38604. so that it maintains its original place in the text.
  38605. */
  38606. class JUCE_API Position
  38607. {
  38608. public:
  38609. /** Creates an uninitialised postion.
  38610. Don't attempt to call any methods on this until you've given it an owner document
  38611. to refer to!
  38612. */
  38613. Position() noexcept;
  38614. /** Creates a position based on a line and index in a document.
  38615. Note that this index is NOT the column number, it's the number of characters from the
  38616. start of the line. The "column" number isn't quite the same, because if the line
  38617. contains any tab characters, the relationship of the index to its visual column depends on
  38618. the number of spaces per tab being used!
  38619. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  38620. they will be adjusted to keep them within its limits.
  38621. */
  38622. Position (const CodeDocument* ownerDocument,
  38623. int line, int indexInLine) noexcept;
  38624. /** Creates a position based on a character index in a document.
  38625. This position is placed at the specified number of characters from the start of the
  38626. document. The line and column are auto-calculated.
  38627. If the position is beyond the range of the document, it'll be adjusted to keep it
  38628. inside.
  38629. */
  38630. Position (const CodeDocument* ownerDocument,
  38631. int charactersFromStartOfDocument) noexcept;
  38632. /** Creates a copy of another position.
  38633. This will copy the position, but the new object will not be set to maintain its position,
  38634. even if the source object was set to do so.
  38635. */
  38636. Position (const Position& other) noexcept;
  38637. /** Destructor. */
  38638. ~Position();
  38639. Position& operator= (const Position& other);
  38640. bool operator== (const Position& other) const noexcept;
  38641. bool operator!= (const Position& other) const noexcept;
  38642. /** Points this object at a new position within the document.
  38643. If the position is beyond the range of the document, it'll be adjusted to keep it
  38644. inside.
  38645. @see getPosition, setLineAndIndex
  38646. */
  38647. void setPosition (int charactersFromStartOfDocument);
  38648. /** Returns the position as the number of characters from the start of the document.
  38649. @see setPosition, getLineNumber, getIndexInLine
  38650. */
  38651. int getPosition() const noexcept { return characterPos; }
  38652. /** Moves the position to a new line and index within the line.
  38653. Note that the index is NOT the column at which the position appears in an editor.
  38654. If the line contains any tab characters, the relationship of the index to its
  38655. visual position depends on the number of spaces per tab being used!
  38656. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  38657. they will be adjusted to keep them within its limits.
  38658. */
  38659. void setLineAndIndex (int newLine, int newIndexInLine);
  38660. /** Returns the line number of this position.
  38661. The first line in the document is numbered zero, not one!
  38662. */
  38663. int getLineNumber() const noexcept { return line; }
  38664. /** Returns the number of characters from the start of the line.
  38665. Note that this value is NOT the column at which the position appears in an editor.
  38666. If the line contains any tab characters, the relationship of the index to its
  38667. visual position depends on the number of spaces per tab being used!
  38668. */
  38669. int getIndexInLine() const noexcept { return indexInLine; }
  38670. /** Allows the position to be automatically updated when the document changes.
  38671. If this is set to true, the positon will register with its document so that
  38672. when the document has text inserted or deleted, this position will be automatically
  38673. moved to keep it at the same position in the text.
  38674. */
  38675. void setPositionMaintained (bool isMaintained);
  38676. /** Moves the position forwards or backwards by the specified number of characters.
  38677. @see movedBy
  38678. */
  38679. void moveBy (int characterDelta);
  38680. /** Returns a position which is the same as this one, moved by the specified number of
  38681. characters.
  38682. @see moveBy
  38683. */
  38684. const Position movedBy (int characterDelta) const;
  38685. /** Returns a position which is the same as this one, moved up or down by the specified
  38686. number of lines.
  38687. @see movedBy
  38688. */
  38689. const Position movedByLines (int deltaLines) const;
  38690. /** Returns the character in the document at this position.
  38691. @see getLineText
  38692. */
  38693. const juce_wchar getCharacter() const;
  38694. /** Returns the line from the document that this position is within.
  38695. @see getCharacter, getLineNumber
  38696. */
  38697. String getLineText() const;
  38698. private:
  38699. CodeDocument* owner;
  38700. int characterPos, line, indexInLine;
  38701. bool positionMaintained;
  38702. };
  38703. /** Returns the full text of the document. */
  38704. String getAllContent() const;
  38705. /** Returns a section of the document's text. */
  38706. String getTextBetween (const Position& start, const Position& end) const;
  38707. /** Returns a line from the document. */
  38708. String getLine (int lineIndex) const noexcept;
  38709. /** Returns the number of characters in the document. */
  38710. int getNumCharacters() const noexcept;
  38711. /** Returns the number of lines in the document. */
  38712. int getNumLines() const noexcept { return lines.size(); }
  38713. /** Returns the number of characters in the longest line of the document. */
  38714. int getMaximumLineLength() noexcept;
  38715. /** Deletes a section of the text.
  38716. This operation is undoable.
  38717. */
  38718. void deleteSection (const Position& startPosition, const Position& endPosition);
  38719. /** Inserts some text into the document at a given position.
  38720. This operation is undoable.
  38721. */
  38722. void insertText (const Position& position, const String& text);
  38723. /** Clears the document and replaces it with some new text.
  38724. This operation is undoable - if you're trying to completely reset the document, you
  38725. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  38726. */
  38727. void replaceAllContent (const String& newContent);
  38728. /** Replaces the editor's contents with the contents of a stream.
  38729. This will also reset the undo history and save point marker.
  38730. */
  38731. bool loadFromStream (InputStream& stream);
  38732. /** Writes the editor's current contents to a stream. */
  38733. bool writeToStream (OutputStream& stream);
  38734. /** Returns the preferred new-line characters for the document.
  38735. This will be either "\n", "\r\n", or (rarely) "\r".
  38736. @see setNewLineCharacters
  38737. */
  38738. String getNewLineCharacters() const noexcept { return newLineChars; }
  38739. /** Sets the new-line characters that the document should use.
  38740. The string must be either "\n", "\r\n", or (rarely) "\r".
  38741. @see getNewLineCharacters
  38742. */
  38743. void setNewLineCharacters (const String& newLine) noexcept;
  38744. /** Begins a new undo transaction.
  38745. The document itself will not call this internally, so relies on whatever is using the
  38746. document to periodically call this to break up the undo sequence into sensible chunks.
  38747. @see UndoManager::beginNewTransaction
  38748. */
  38749. void newTransaction();
  38750. /** Undo the last operation.
  38751. @see UndoManager::undo
  38752. */
  38753. void undo();
  38754. /** Redo the last operation.
  38755. @see UndoManager::redo
  38756. */
  38757. void redo();
  38758. /** Clears the undo history.
  38759. @see UndoManager::clearUndoHistory
  38760. */
  38761. void clearUndoHistory();
  38762. /** Returns the document's UndoManager */
  38763. UndoManager& getUndoManager() noexcept { return undoManager; }
  38764. /** Makes a note that the document's current state matches the one that is saved.
  38765. After this has been called, hasChangedSinceSavePoint() will return false until
  38766. the document has been altered, and then it'll start returning true. If the document is
  38767. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  38768. will again return false.
  38769. @see hasChangedSinceSavePoint
  38770. */
  38771. void setSavePoint() noexcept;
  38772. /** Returns true if the state of the document differs from the state it was in when
  38773. setSavePoint() was last called.
  38774. @see setSavePoint
  38775. */
  38776. bool hasChangedSinceSavePoint() const noexcept;
  38777. /** Searches for a word-break. */
  38778. const Position findWordBreakAfter (const Position& position) const noexcept;
  38779. /** Searches for a word-break. */
  38780. const Position findWordBreakBefore (const Position& position) const noexcept;
  38781. /** An object that receives callbacks from the CodeDocument when its text changes.
  38782. @see CodeDocument::addListener, CodeDocument::removeListener
  38783. */
  38784. class JUCE_API Listener
  38785. {
  38786. public:
  38787. Listener() {}
  38788. virtual ~Listener() {}
  38789. /** Called by a CodeDocument when it is altered.
  38790. */
  38791. virtual void codeDocumentChanged (const Position& affectedTextStart,
  38792. const Position& affectedTextEnd) = 0;
  38793. };
  38794. /** Registers a listener object to receive callbacks when the document changes.
  38795. If the listener is already registered, this method has no effect.
  38796. @see removeListener
  38797. */
  38798. void addListener (Listener* listener) noexcept;
  38799. /** Deregisters a listener.
  38800. @see addListener
  38801. */
  38802. void removeListener (Listener* listener) noexcept;
  38803. /** Iterates the text in a CodeDocument.
  38804. This class lets you read characters from a CodeDocument. It's designed to be used
  38805. by a SyntaxAnalyser object.
  38806. @see CodeDocument, SyntaxAnalyser
  38807. */
  38808. class JUCE_API Iterator
  38809. {
  38810. public:
  38811. Iterator (CodeDocument* document);
  38812. Iterator (const Iterator& other);
  38813. Iterator& operator= (const Iterator& other) noexcept;
  38814. ~Iterator() noexcept;
  38815. /** Reads the next character and returns it.
  38816. @see peekNextChar
  38817. */
  38818. juce_wchar nextChar();
  38819. /** Reads the next character without advancing the current position. */
  38820. juce_wchar peekNextChar() const;
  38821. /** Advances the position by one character. */
  38822. void skip();
  38823. /** Returns the position of the next character as its position within the
  38824. whole document.
  38825. */
  38826. int getPosition() const noexcept { return position; }
  38827. /** Skips over any whitespace characters until the next character is non-whitespace. */
  38828. void skipWhitespace();
  38829. /** Skips forward until the next character will be the first character on the next line */
  38830. void skipToEndOfLine();
  38831. /** Returns the line number of the next character. */
  38832. int getLine() const noexcept { return line; }
  38833. /** Returns true if the iterator has reached the end of the document. */
  38834. bool isEOF() const noexcept;
  38835. private:
  38836. CodeDocument* document;
  38837. mutable String::CharPointerType charPointer;
  38838. int line, position;
  38839. };
  38840. private:
  38841. friend class CodeDocumentInsertAction;
  38842. friend class CodeDocumentDeleteAction;
  38843. friend class Iterator;
  38844. friend class Position;
  38845. OwnedArray <CodeDocumentLine> lines;
  38846. Array <Position*> positionsToMaintain;
  38847. UndoManager undoManager;
  38848. int currentActionIndex, indexOfSavedState;
  38849. int maximumLineLength;
  38850. ListenerList <Listener> listeners;
  38851. String newLineChars;
  38852. void sendListenerChangeMessage (int startLine, int endLine);
  38853. void insert (const String& text, int insertPos, bool undoable);
  38854. void remove (int startPos, int endPos, bool undoable);
  38855. void checkLastLineStatus();
  38856. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeDocument);
  38857. };
  38858. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  38859. /*** End of inlined file: juce_CodeDocument.h ***/
  38860. #endif
  38861. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38862. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  38863. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38864. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38865. /*** Start of inlined file: juce_TextInputTarget.h ***/
  38866. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38867. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38868. /**
  38869. An abstract base class which can be implemented by components that function as
  38870. text editors.
  38871. This class allows different types of text editor component to provide a uniform
  38872. interface, which can be used by things like OS-specific input methods, on-screen
  38873. keyboards, etc.
  38874. */
  38875. class JUCE_API TextInputTarget
  38876. {
  38877. public:
  38878. /** */
  38879. TextInputTarget() {}
  38880. /** Destructor. */
  38881. virtual ~TextInputTarget() {}
  38882. /** Returns true if this input target is currently accepting input.
  38883. For example, a text editor might return false if it's in read-only mode.
  38884. */
  38885. virtual bool isTextInputActive() const = 0;
  38886. /** Returns the extents of the selected text region, or an empty range if
  38887. nothing is selected,
  38888. */
  38889. virtual const Range<int> getHighlightedRegion() const = 0;
  38890. /** Sets the currently-selected text region. */
  38891. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  38892. /** Sets a number of temporarily underlined sections.
  38893. This is needed by MS Windows input method UI.
  38894. */
  38895. virtual void setTemporaryUnderlining (const Array <Range<int> >& underlinedRegions) = 0;
  38896. /** Returns a specified sub-section of the text. */
  38897. virtual const String getTextInRange (const Range<int>& range) const = 0;
  38898. /** Inserts some text, overwriting the selected text region, if there is one. */
  38899. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  38900. /** Returns the position of the caret, relative to the component's origin. */
  38901. virtual const Rectangle<int> getCaretRectangle() = 0;
  38902. };
  38903. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38904. /*** End of inlined file: juce_TextInputTarget.h ***/
  38905. /*** Start of inlined file: juce_CaretComponent.h ***/
  38906. #ifndef __JUCE_CARETCOMPONENT_JUCEHEADER__
  38907. #define __JUCE_CARETCOMPONENT_JUCEHEADER__
  38908. /**
  38909. */
  38910. class JUCE_API CaretComponent : public Component,
  38911. public Timer
  38912. {
  38913. public:
  38914. /** Creates the caret component.
  38915. The keyFocusOwner is an optional component which the caret will check, making
  38916. itself visible only when the keyFocusOwner has keyboard focus.
  38917. */
  38918. CaretComponent (Component* keyFocusOwner);
  38919. /** Destructor. */
  38920. ~CaretComponent();
  38921. /** Sets the caret's position to place it next to the given character.
  38922. The area is the rectangle containing the entire character that the caret is
  38923. positioned on, so by default a vertical-line caret may choose to just show itself
  38924. at the left of this area. You can override this method to customise its size.
  38925. This method will also force the caret to reset its timer and become visible (if
  38926. appropriate), so that as it moves, you can see where it is.
  38927. */
  38928. virtual void setCaretPosition (const Rectangle<int>& characterArea);
  38929. /** A set of colour IDs to use to change the colour of various aspects of the caret.
  38930. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38931. methods.
  38932. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38933. */
  38934. enum ColourIds
  38935. {
  38936. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  38937. };
  38938. /** @internal */
  38939. void paint (Graphics& g);
  38940. /** @internal */
  38941. void timerCallback();
  38942. private:
  38943. Component* owner;
  38944. bool shouldBeShown() const;
  38945. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  38946. };
  38947. #endif // __JUCE_CARETCOMPONENT_JUCEHEADER__
  38948. /*** End of inlined file: juce_CaretComponent.h ***/
  38949. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  38950. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  38951. #define __JUCE_CODETOKENISER_JUCEHEADER__
  38952. /**
  38953. A base class for tokenising code so that the syntax can be displayed in a
  38954. code editor.
  38955. @see CodeDocument, CodeEditorComponent
  38956. */
  38957. class JUCE_API CodeTokeniser
  38958. {
  38959. public:
  38960. CodeTokeniser() {}
  38961. virtual ~CodeTokeniser() {}
  38962. /** Reads the next token from the source and returns its token type.
  38963. This must leave the source pointing to the first character in the
  38964. next token.
  38965. */
  38966. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  38967. /** Returns a list of the names of the token types this analyser uses.
  38968. The index in this list must match the token type numbers that are
  38969. returned by readNextToken().
  38970. */
  38971. virtual StringArray getTokenTypes() = 0;
  38972. /** Returns a suggested syntax highlighting colour for a specified
  38973. token type.
  38974. */
  38975. virtual const Colour getDefaultColour (int tokenType) = 0;
  38976. private:
  38977. JUCE_LEAK_DETECTOR (CodeTokeniser);
  38978. };
  38979. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  38980. /*** End of inlined file: juce_CodeTokeniser.h ***/
  38981. /**
  38982. A text editor component designed specifically for source code.
  38983. This is designed to handle syntax highlighting and fast editing of very large
  38984. files.
  38985. */
  38986. class JUCE_API CodeEditorComponent : public Component,
  38987. public TextInputTarget,
  38988. public Timer,
  38989. public ScrollBar::Listener,
  38990. public CodeDocument::Listener,
  38991. public AsyncUpdater
  38992. {
  38993. public:
  38994. /** Creates an editor for a document.
  38995. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  38996. The object that you pass in is not owned or deleted by the editor - you must
  38997. make sure that it doesn't get deleted while this component is still using it.
  38998. @see CodeDocument
  38999. */
  39000. CodeEditorComponent (CodeDocument& document,
  39001. CodeTokeniser* codeTokeniser);
  39002. /** Destructor. */
  39003. ~CodeEditorComponent();
  39004. /** Returns the code document that this component is editing. */
  39005. CodeDocument& getDocument() const noexcept { return document; }
  39006. /** Loads the given content into the document.
  39007. This will completely reset the CodeDocument object, clear its undo history,
  39008. and fill it with this text.
  39009. */
  39010. void loadContent (const String& newContent);
  39011. /** Returns the standard character width. */
  39012. float getCharWidth() const noexcept { return charWidth; }
  39013. /** Returns the height of a line of text, in pixels. */
  39014. int getLineHeight() const noexcept { return lineHeight; }
  39015. /** Returns the number of whole lines visible on the screen,
  39016. This doesn't include a cut-off line that might be visible at the bottom if the
  39017. component's height isn't an exact multiple of the line-height.
  39018. */
  39019. int getNumLinesOnScreen() const noexcept { return linesOnScreen; }
  39020. /** Returns the number of whole columns visible on the screen.
  39021. This doesn't include any cut-off columns at the right-hand edge.
  39022. */
  39023. int getNumColumnsOnScreen() const noexcept { return columnsOnScreen; }
  39024. /** Returns the current caret position. */
  39025. const CodeDocument::Position getCaretPos() const { return caretPos; }
  39026. /** Returns the position of the caret, relative to the editor's origin. */
  39027. const Rectangle<int> getCaretRectangle();
  39028. /** Moves the caret.
  39029. If selecting is true, the section of the document between the current
  39030. caret position and the new one will become selected. If false, any currently
  39031. selected region will be deselected.
  39032. */
  39033. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  39034. /** Returns the on-screen position of a character in the document.
  39035. The rectangle returned is relative to this component's top-left origin.
  39036. */
  39037. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const;
  39038. /** Finds the character at a given on-screen position.
  39039. The co-ordinates are relative to this component's top-left origin.
  39040. */
  39041. const CodeDocument::Position getPositionAt (int x, int y);
  39042. bool moveCaretLeft (bool moveInWholeWordSteps, bool selecting);
  39043. bool moveCaretRight (bool moveInWholeWordSteps, bool selecting);
  39044. bool moveCaretUp (bool selecting);
  39045. bool moveCaretDown (bool selecting);
  39046. bool scrollDown();
  39047. bool scrollUp();
  39048. bool pageUp (bool selecting);
  39049. bool pageDown (bool selecting);
  39050. bool moveCaretToTop (bool selecting);
  39051. bool moveCaretToStartOfLine (bool selecting);
  39052. bool moveCaretToEnd (bool selecting);
  39053. bool moveCaretToEndOfLine (bool selecting);
  39054. bool deleteBackwards (bool moveInWholeWordSteps);
  39055. bool deleteForwards (bool moveInWholeWordSteps);
  39056. bool copyToClipboard();
  39057. bool cutToClipboard();
  39058. bool pasteFromClipboard();
  39059. bool undo();
  39060. bool redo();
  39061. bool selectAll();
  39062. void deselectAll();
  39063. void scrollToLine (int newFirstLineOnScreen);
  39064. void scrollBy (int deltaLines);
  39065. void scrollToColumn (int newFirstColumnOnScreen);
  39066. void scrollToKeepCaretOnScreen();
  39067. void insertTextAtCaret (const String& textToInsert);
  39068. void insertTabAtCaret();
  39069. const Range<int> getHighlightedRegion() const;
  39070. void setHighlightedRegion (const Range<int>& newRange);
  39071. const String getTextInRange (const Range<int>& range) const;
  39072. /** Changes the current tab settings.
  39073. This lets you change the tab size and whether pressing the tab key inserts a
  39074. tab character, or its equivalent number of spaces.
  39075. */
  39076. void setTabSize (int numSpacesPerTab, bool insertSpacesInsteadOfTabCharacters);
  39077. /** Returns the current number of spaces per tab.
  39078. @see setTabSize
  39079. */
  39080. int getTabSize() const noexcept { return spacesPerTab; }
  39081. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  39082. @see setTabSize
  39083. */
  39084. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  39085. /** Changes the font.
  39086. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  39087. */
  39088. void setFont (const Font& newFont);
  39089. /** Returns the font that the editor is using. */
  39090. const Font& getFont() const noexcept { return font; }
  39091. /** Resets the syntax highlighting colours to the default ones provided by the
  39092. code tokeniser.
  39093. @see CodeTokeniser::getDefaultColour
  39094. */
  39095. void resetToDefaultColours();
  39096. /** Changes one of the syntax highlighting colours.
  39097. The token type values are dependent on the tokeniser being used - use
  39098. CodeTokeniser::getTokenTypes() to get a list of the token types.
  39099. @see getColourForTokenType
  39100. */
  39101. void setColourForTokenType (int tokenType, const Colour& colour);
  39102. /** Returns one of the syntax highlighting colours.
  39103. The token type values are dependent on the tokeniser being used - use
  39104. CodeTokeniser::getTokenTypes() to get a list of the token types.
  39105. @see setColourForTokenType
  39106. */
  39107. const Colour getColourForTokenType (int tokenType) const;
  39108. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  39109. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39110. methods.
  39111. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39112. */
  39113. enum ColourIds
  39114. {
  39115. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  39116. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  39117. selected text. */
  39118. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  39119. enabled. */
  39120. };
  39121. /** Changes the size of the scrollbars. */
  39122. void setScrollbarThickness (int thickness);
  39123. /** Returns the thickness of the scrollbars. */
  39124. int getScrollbarThickness() const noexcept { return scrollbarThickness; }
  39125. /** @internal */
  39126. void resized();
  39127. /** @internal */
  39128. void paint (Graphics& g);
  39129. /** @internal */
  39130. bool keyPressed (const KeyPress& key);
  39131. /** @internal */
  39132. void mouseDown (const MouseEvent& e);
  39133. /** @internal */
  39134. void mouseDrag (const MouseEvent& e);
  39135. /** @internal */
  39136. void mouseUp (const MouseEvent& e);
  39137. /** @internal */
  39138. void mouseDoubleClick (const MouseEvent& e);
  39139. /** @internal */
  39140. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39141. /** @internal */
  39142. void focusGained (FocusChangeType cause);
  39143. /** @internal */
  39144. void focusLost (FocusChangeType cause);
  39145. /** @internal */
  39146. void timerCallback();
  39147. /** @internal */
  39148. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  39149. /** @internal */
  39150. void handleAsyncUpdate();
  39151. /** @internal */
  39152. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  39153. const CodeDocument::Position& affectedTextEnd);
  39154. /** @internal */
  39155. bool isTextInputActive() const;
  39156. /** @internal */
  39157. void setTemporaryUnderlining (const Array <Range<int> >&);
  39158. private:
  39159. CodeDocument& document;
  39160. Font font;
  39161. int firstLineOnScreen, gutter, spacesPerTab;
  39162. float charWidth;
  39163. int lineHeight, linesOnScreen, columnsOnScreen;
  39164. int scrollbarThickness, columnToTryToMaintain;
  39165. bool useSpacesForTabs;
  39166. double xOffset;
  39167. CodeDocument::Position caretPos;
  39168. CodeDocument::Position selectionStart, selectionEnd;
  39169. ScopedPointer<CaretComponent> caret;
  39170. ScrollBar verticalScrollBar, horizontalScrollBar;
  39171. enum DragType
  39172. {
  39173. notDragging,
  39174. draggingSelectionStart,
  39175. draggingSelectionEnd
  39176. };
  39177. DragType dragType;
  39178. CodeTokeniser* codeTokeniser;
  39179. Array <Colour> coloursForTokenCategories;
  39180. class CodeEditorLine;
  39181. OwnedArray <CodeEditorLine> lines;
  39182. void rebuildLineTokens();
  39183. OwnedArray <CodeDocument::Iterator> cachedIterators;
  39184. void clearCachedIterators (int firstLineToBeInvalid);
  39185. void updateCachedIterators (int maxLineNum);
  39186. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  39187. void moveLineDelta (int delta, bool selecting);
  39188. void updateCaretPosition();
  39189. void updateScrollBars();
  39190. void scrollToLineInternal (int line);
  39191. void scrollToColumnInternal (double column);
  39192. void newTransaction();
  39193. void cut();
  39194. int indexToColumn (int line, int index) const noexcept;
  39195. int columnToIndex (int line, int column) const noexcept;
  39196. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeEditorComponent);
  39197. };
  39198. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39199. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  39200. #endif
  39201. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  39202. #endif
  39203. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39204. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  39205. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39206. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39207. /**
  39208. A simple lexical analyser for syntax colouring of C++ code.
  39209. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  39210. */
  39211. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  39212. {
  39213. public:
  39214. CPlusPlusCodeTokeniser();
  39215. ~CPlusPlusCodeTokeniser();
  39216. enum TokenType
  39217. {
  39218. tokenType_error = 0,
  39219. tokenType_comment,
  39220. tokenType_builtInKeyword,
  39221. tokenType_identifier,
  39222. tokenType_integerLiteral,
  39223. tokenType_floatLiteral,
  39224. tokenType_stringLiteral,
  39225. tokenType_operator,
  39226. tokenType_bracket,
  39227. tokenType_punctuation,
  39228. tokenType_preprocessor
  39229. };
  39230. int readNextToken (CodeDocument::Iterator& source);
  39231. StringArray getTokenTypes();
  39232. const Colour getDefaultColour (int tokenType);
  39233. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  39234. static bool isReservedKeyword (const String& token) noexcept;
  39235. private:
  39236. JUCE_LEAK_DETECTOR (CPlusPlusCodeTokeniser);
  39237. };
  39238. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39239. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  39240. #endif
  39241. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  39242. /*** Start of inlined file: juce_ComboBox.h ***/
  39243. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  39244. #define __JUCE_COMBOBOX_JUCEHEADER__
  39245. /*** Start of inlined file: juce_Label.h ***/
  39246. #ifndef __JUCE_LABEL_JUCEHEADER__
  39247. #define __JUCE_LABEL_JUCEHEADER__
  39248. /*** Start of inlined file: juce_TextEditor.h ***/
  39249. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  39250. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  39251. /**
  39252. A component containing text that can be edited.
  39253. A TextEditor can either be in single- or multi-line mode, and supports mixed
  39254. fonts and colours.
  39255. @see TextEditor::Listener, Label
  39256. */
  39257. class JUCE_API TextEditor : public Component,
  39258. public TextInputTarget,
  39259. public SettableTooltipClient
  39260. {
  39261. public:
  39262. /** Creates a new, empty text editor.
  39263. @param componentName the name to pass to the component for it to use as its name
  39264. @param passwordCharacter if this is not zero, this character will be used as a replacement
  39265. for all characters that are drawn on screen - e.g. to create
  39266. a password-style textbox containing circular blobs instead of text,
  39267. you could set this value to 0x25cf, which is the unicode character
  39268. for a black splodge (not all fonts include this, though), or 0x2022,
  39269. which is a bullet (probably the best choice for linux).
  39270. */
  39271. explicit TextEditor (const String& componentName = String::empty,
  39272. juce_wchar passwordCharacter = 0);
  39273. /** Destructor. */
  39274. virtual ~TextEditor();
  39275. /** Puts the editor into either multi- or single-line mode.
  39276. By default, the editor will be in single-line mode, so use this if you need a multi-line
  39277. editor.
  39278. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  39279. on if you want a multi-line editor with line-breaks.
  39280. @see isMultiLine, setReturnKeyStartsNewLine
  39281. */
  39282. void setMultiLine (bool shouldBeMultiLine,
  39283. bool shouldWordWrap = true);
  39284. /** Returns true if the editor is in multi-line mode.
  39285. */
  39286. bool isMultiLine() const;
  39287. /** Changes the behaviour of the return key.
  39288. If set to true, the return key will insert a new-line into the text; if false
  39289. it will trigger a call to the TextEditor::Listener::textEditorReturnKeyPressed()
  39290. method. By default this is set to false, and when true it will only insert
  39291. new-lines when in multi-line mode (see setMultiLine()).
  39292. */
  39293. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  39294. /** Returns the value set by setReturnKeyStartsNewLine().
  39295. See setReturnKeyStartsNewLine() for more info.
  39296. */
  39297. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  39298. /** Indicates whether the tab key should be accepted and used to input a tab character,
  39299. or whether it gets ignored.
  39300. By default the tab key is ignored, so that it can be used to switch keyboard focus
  39301. between components.
  39302. */
  39303. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  39304. /** Returns true if the tab key is being used for input.
  39305. @see setTabKeyUsedAsCharacter
  39306. */
  39307. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  39308. /** Changes the editor to read-only mode.
  39309. By default, the text editor is not read-only. If you're making it read-only, you
  39310. might also want to call setCaretVisible (false) to get rid of the caret.
  39311. The text can still be highlighted and copied when in read-only mode.
  39312. @see isReadOnly, setCaretVisible
  39313. */
  39314. void setReadOnly (bool shouldBeReadOnly);
  39315. /** Returns true if the editor is in read-only mode.
  39316. */
  39317. bool isReadOnly() const;
  39318. /** Makes the caret visible or invisible.
  39319. By default the caret is visible.
  39320. @see setCaretColour, setCaretPosition
  39321. */
  39322. void setCaretVisible (bool shouldBeVisible);
  39323. /** Returns true if the caret is enabled.
  39324. @see setCaretVisible
  39325. */
  39326. bool isCaretVisible() const { return caret != nullptr; }
  39327. /** Enables/disables a vertical scrollbar.
  39328. (This only applies when in multi-line mode). When the text gets too long to fit
  39329. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  39330. this is enabled, the scrollbar will be hidden unless it's needed.
  39331. By default the scrollbar is enabled.
  39332. */
  39333. void setScrollbarsShown (bool shouldBeEnabled);
  39334. /** Returns true if scrollbars are enabled.
  39335. @see setScrollbarsShown
  39336. */
  39337. bool areScrollbarsShown() const { return scrollbarVisible; }
  39338. /** Changes the password character used to disguise the text.
  39339. @param passwordCharacter if this is not zero, this character will be used as a replacement
  39340. for all characters that are drawn on screen - e.g. to create
  39341. a password-style textbox containing circular blobs instead of text,
  39342. you could set this value to 0x25cf, which is the unicode character
  39343. for a black splodge (not all fonts include this, though), or 0x2022,
  39344. which is a bullet (probably the best choice for linux).
  39345. */
  39346. void setPasswordCharacter (juce_wchar passwordCharacter);
  39347. /** Returns the current password character.
  39348. @see setPasswordCharacter
  39349. */
  39350. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  39351. /** Allows a right-click menu to appear for the editor.
  39352. (This defaults to being enabled).
  39353. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  39354. of options such as cut/copy/paste, undo/redo, etc.
  39355. */
  39356. void setPopupMenuEnabled (bool menuEnabled);
  39357. /** Returns true if the right-click menu is enabled.
  39358. @see setPopupMenuEnabled
  39359. */
  39360. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  39361. /** Returns true if a popup-menu is currently being displayed.
  39362. */
  39363. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  39364. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  39365. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39366. methods.
  39367. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39368. */
  39369. enum ColourIds
  39370. {
  39371. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  39372. transparent if necessary. */
  39373. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  39374. that because the editor can contain multiple colours, calling this
  39375. method won't change the colour of existing text - to do that, call
  39376. applyFontToAllText() after calling this method.*/
  39377. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  39378. the text - this can be transparent if you don't want to show any
  39379. highlighting.*/
  39380. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  39381. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  39382. the edge of the component. */
  39383. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  39384. the edge of the component when it has focus. */
  39385. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  39386. around the edge of the editor. */
  39387. };
  39388. /** Sets the font to use for newly added text.
  39389. This will change the font that will be used next time any text is added or entered
  39390. into the editor. It won't change the font of any existing text - to do that, use
  39391. applyFontToAllText() instead.
  39392. @see applyFontToAllText
  39393. */
  39394. void setFont (const Font& newFont);
  39395. /** Applies a font to all the text in the editor.
  39396. This will also set the current font to use for any new text that's added.
  39397. @see setFont
  39398. */
  39399. void applyFontToAllText (const Font& newFont);
  39400. /** Returns the font that's currently being used for new text.
  39401. @see setFont
  39402. */
  39403. const Font& getFont() const;
  39404. /** If set to true, focusing on the editor will highlight all its text.
  39405. (Set to false by default).
  39406. This is useful for boxes where you expect the user to re-enter all the
  39407. text when they focus on the component, rather than editing what's already there.
  39408. */
  39409. void setSelectAllWhenFocused (bool b);
  39410. /** Sets limits on the characters that can be entered.
  39411. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  39412. limit is set
  39413. @param allowedCharacters if this is non-empty, then only characters that occur in
  39414. this string are allowed to be entered into the editor.
  39415. */
  39416. void setInputRestrictions (int maxTextLength,
  39417. const String& allowedCharacters = String::empty);
  39418. /** When the text editor is empty, it can be set to display a message.
  39419. This is handy for things like telling the user what to type in the box - the
  39420. string is only displayed, it's not taken to actually be the contents of
  39421. the editor.
  39422. */
  39423. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  39424. /** Changes the size of the scrollbars that are used.
  39425. Handy if you need smaller scrollbars for a small text box.
  39426. */
  39427. void setScrollBarThickness (int newThicknessPixels);
  39428. /** Shows or hides the buttons on any scrollbars that are used.
  39429. @see ScrollBar::setButtonVisibility
  39430. */
  39431. void setScrollBarButtonVisibility (bool buttonsVisible);
  39432. /**
  39433. Receives callbacks from a TextEditor component when it changes.
  39434. @see TextEditor::addListener
  39435. */
  39436. class JUCE_API Listener
  39437. {
  39438. public:
  39439. /** Destructor. */
  39440. virtual ~Listener() {}
  39441. /** Called when the user changes the text in some way. */
  39442. virtual void textEditorTextChanged (TextEditor& editor);
  39443. /** Called when the user presses the return key. */
  39444. virtual void textEditorReturnKeyPressed (TextEditor& editor);
  39445. /** Called when the user presses the escape key. */
  39446. virtual void textEditorEscapeKeyPressed (TextEditor& editor);
  39447. /** Called when the text editor loses focus. */
  39448. virtual void textEditorFocusLost (TextEditor& editor);
  39449. };
  39450. /** Registers a listener to be told when things happen to the text.
  39451. @see removeListener
  39452. */
  39453. void addListener (Listener* newListener);
  39454. /** Deregisters a listener.
  39455. @see addListener
  39456. */
  39457. void removeListener (Listener* listenerToRemove);
  39458. /** Returns the entire contents of the editor. */
  39459. String getText() const;
  39460. /** Returns a section of the contents of the editor. */
  39461. const String getTextInRange (const Range<int>& textRange) const;
  39462. /** Returns true if there are no characters in the editor.
  39463. This is more efficient than calling getText().isEmpty().
  39464. */
  39465. bool isEmpty() const;
  39466. /** Sets the entire content of the editor.
  39467. This will clear the editor and insert the given text (using the current text colour
  39468. and font). You can set the current text colour using
  39469. @code setColour (TextEditor::textColourId, ...);
  39470. @endcode
  39471. @param newText the text to add
  39472. @param sendTextChangeMessage if true, this will cause a change message to
  39473. be sent to all the listeners.
  39474. @see insertText
  39475. */
  39476. void setText (const String& newText,
  39477. bool sendTextChangeMessage = true);
  39478. /** Returns a Value object that can be used to get or set the text.
  39479. Bear in mind that this operate quite slowly if your text box contains large
  39480. amounts of text, as it needs to dynamically build the string that's involved. It's
  39481. best used for small text boxes.
  39482. */
  39483. Value& getTextValue();
  39484. /** Inserts some text at the current caret position.
  39485. If a section of the text is highlighted, it will be replaced by
  39486. this string, otherwise it will be inserted.
  39487. To delete a section of text, you can use setHighlightedRegion() to
  39488. highlight it, and call insertTextAtCursor (String::empty).
  39489. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  39490. */
  39491. void insertTextAtCaret (const String& textToInsert);
  39492. /** Deletes all the text from the editor. */
  39493. void clear();
  39494. /** Deletes the currently selected region.
  39495. This doesn't copy the deleted section to the clipboard - if you need to do that, call copy() first.
  39496. @see copy, paste, SystemClipboard
  39497. */
  39498. void cut();
  39499. /** Copies the currently selected region to the clipboard.
  39500. @see cut, paste, SystemClipboard
  39501. */
  39502. void copy();
  39503. /** Pastes the contents of the clipboard into the editor at the caret position.
  39504. @see cut, copy, SystemClipboard
  39505. */
  39506. void paste();
  39507. /** Moves the caret to be in front of a given character.
  39508. @see getCaretPosition
  39509. */
  39510. void setCaretPosition (int newIndex);
  39511. /** Returns the current index of the caret.
  39512. @see setCaretPosition
  39513. */
  39514. int getCaretPosition() const;
  39515. /** Attempts to scroll the text editor so that the caret ends up at
  39516. a specified position.
  39517. This won't affect the caret's position within the text, it tries to scroll
  39518. the entire editor vertically and horizontally so that the caret is sitting
  39519. at the given position (relative to the top-left of this component).
  39520. Depending on the amount of text available, it might not be possible to
  39521. scroll far enough for the caret to reach this exact position, but it
  39522. will go as far as it can in that direction.
  39523. */
  39524. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  39525. /** Get the graphical position of the caret.
  39526. The rectangle returned is relative to the component's top-left corner.
  39527. @see scrollEditorToPositionCaret
  39528. */
  39529. const Rectangle<int> getCaretRectangle();
  39530. /** Selects a section of the text. */
  39531. void setHighlightedRegion (const Range<int>& newSelection);
  39532. /** Returns the range of characters that are selected.
  39533. If nothing is selected, this will return an empty range.
  39534. @see setHighlightedRegion
  39535. */
  39536. const Range<int> getHighlightedRegion() const { return selection; }
  39537. /** Returns the section of text that is currently selected. */
  39538. String getHighlightedText() const;
  39539. /** Finds the index of the character at a given position.
  39540. The co-ordinates are relative to the component's top-left.
  39541. */
  39542. int getTextIndexAt (int x, int y);
  39543. /** Counts the number of characters in the text.
  39544. This is quicker than getting the text as a string if you just need to know
  39545. the length.
  39546. */
  39547. int getTotalNumChars() const;
  39548. /** Returns the total width of the text, as it is currently laid-out.
  39549. This may be larger than the size of the TextEditor, and can change when
  39550. the TextEditor is resized or the text changes.
  39551. */
  39552. int getTextWidth() const;
  39553. /** Returns the maximum height of the text, as it is currently laid-out.
  39554. This may be larger than the size of the TextEditor, and can change when
  39555. the TextEditor is resized or the text changes.
  39556. */
  39557. int getTextHeight() const;
  39558. /** Changes the size of the gap at the top and left-edge of the editor.
  39559. By default there's a gap of 4 pixels.
  39560. */
  39561. void setIndents (int newLeftIndent, int newTopIndent);
  39562. /** Changes the size of border left around the edge of the component.
  39563. @see getBorder
  39564. */
  39565. void setBorder (const BorderSize<int>& border);
  39566. /** Returns the size of border around the edge of the component.
  39567. @see setBorder
  39568. */
  39569. const BorderSize<int> getBorder() const;
  39570. /** Used to disable the auto-scrolling which keeps the caret visible.
  39571. If true (the default), the editor will scroll when the caret moves offscreen. If
  39572. set to false, it won't.
  39573. */
  39574. void setScrollToShowCursor (bool shouldScrollToShowCaret);
  39575. /** @internal */
  39576. void paint (Graphics& g);
  39577. /** @internal */
  39578. void paintOverChildren (Graphics& g);
  39579. /** @internal */
  39580. void mouseDown (const MouseEvent& e);
  39581. /** @internal */
  39582. void mouseUp (const MouseEvent& e);
  39583. /** @internal */
  39584. void mouseDrag (const MouseEvent& e);
  39585. /** @internal */
  39586. void mouseDoubleClick (const MouseEvent& e);
  39587. /** @internal */
  39588. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39589. /** @internal */
  39590. bool keyPressed (const KeyPress& key);
  39591. /** @internal */
  39592. bool keyStateChanged (bool isKeyDown);
  39593. /** @internal */
  39594. void focusGained (FocusChangeType cause);
  39595. /** @internal */
  39596. void focusLost (FocusChangeType cause);
  39597. /** @internal */
  39598. void resized();
  39599. /** @internal */
  39600. void enablementChanged();
  39601. /** @internal */
  39602. void colourChanged();
  39603. /** @internal */
  39604. void lookAndFeelChanged();
  39605. /** @internal */
  39606. bool isTextInputActive() const;
  39607. /** @internal */
  39608. void setTemporaryUnderlining (const Array <Range<int> >&);
  39609. bool moveCaretLeft (bool moveInWholeWordSteps, bool selecting);
  39610. bool moveCaretRight (bool moveInWholeWordSteps, bool selecting);
  39611. bool moveCaretUp (bool selecting);
  39612. bool moveCaretDown (bool selecting);
  39613. bool pageUp (bool selecting);
  39614. bool pageDown (bool selecting);
  39615. bool scrollDown();
  39616. bool scrollUp();
  39617. bool moveCaretToTop (bool selecting);
  39618. bool moveCaretToStartOfLine (bool selecting);
  39619. bool moveCaretToEnd (bool selecting);
  39620. bool moveCaretToEndOfLine (bool selecting);
  39621. bool deleteBackwards (bool moveInWholeWordSteps);
  39622. bool deleteForwards (bool moveInWholeWordSteps);
  39623. bool copyToClipboard();
  39624. bool cutToClipboard();
  39625. bool pasteFromClipboard();
  39626. bool selectAll();
  39627. bool undo();
  39628. bool redo();
  39629. /** This adds the items to the popup menu.
  39630. By default it adds the cut/copy/paste items, but you can override this if
  39631. you need to replace these with your own items.
  39632. If you want to add your own items to the existing ones, you can override this,
  39633. call the base class's addPopupMenuItems() method, then append your own items.
  39634. When the menu has been shown, performPopupMenuAction() will be called to
  39635. perform the item that the user has chosen.
  39636. The default menu items will be added using item IDs in the range
  39637. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  39638. menu IDs.
  39639. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  39640. a pointer to the info about it, or may be null if the menu is being triggered
  39641. by some other means.
  39642. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  39643. */
  39644. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  39645. const MouseEvent* mouseClickEvent);
  39646. /** This is called to perform one of the items that was shown on the popup menu.
  39647. If you've overridden addPopupMenuItems(), you should also override this
  39648. to perform the actions that you've added.
  39649. If you've overridden addPopupMenuItems() but have still left the default items
  39650. on the menu, remember to call the superclass's performPopupMenuAction()
  39651. so that it can perform the default actions if that's what the user clicked on.
  39652. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  39653. */
  39654. virtual void performPopupMenuAction (int menuItemID);
  39655. protected:
  39656. /** Scrolls the minimum distance needed to get the caret into view. */
  39657. void scrollToMakeSureCursorIsVisible();
  39658. /** @internal */
  39659. void moveCaret (int newCaretPos);
  39660. /** @internal */
  39661. void moveCaretTo (int newPosition, bool isSelecting);
  39662. /** Used internally to dispatch a text-change message. */
  39663. void textChanged();
  39664. /** Begins a new transaction in the UndoManager. */
  39665. void newTransaction();
  39666. /** Used internally to trigger an undo or redo. */
  39667. void doUndoRedo (bool isRedo);
  39668. /** Can be overridden to intercept return key presses directly */
  39669. virtual void returnPressed();
  39670. /** Can be overridden to intercept escape key presses directly */
  39671. virtual void escapePressed();
  39672. /** @internal */
  39673. void handleCommandMessage (int commandId);
  39674. private:
  39675. class Iterator;
  39676. class UniformTextSection;
  39677. class TextHolderComponent;
  39678. class InsertAction;
  39679. class RemoveAction;
  39680. friend class InsertAction;
  39681. friend class RemoveAction;
  39682. ScopedPointer <Viewport> viewport;
  39683. TextHolderComponent* textHolder;
  39684. BorderSize<int> borderSize;
  39685. bool readOnly : 1;
  39686. bool multiline : 1;
  39687. bool wordWrap : 1;
  39688. bool returnKeyStartsNewLine : 1;
  39689. bool popupMenuEnabled : 1;
  39690. bool selectAllTextWhenFocused : 1;
  39691. bool scrollbarVisible : 1;
  39692. bool wasFocused : 1;
  39693. bool keepCaretOnScreen : 1;
  39694. bool tabKeyUsed : 1;
  39695. bool menuActive : 1;
  39696. bool valueTextNeedsUpdating : 1;
  39697. UndoManager undoManager;
  39698. ScopedPointer<CaretComponent> caret;
  39699. int maxTextLength;
  39700. Range<int> selection;
  39701. int leftIndent, topIndent;
  39702. unsigned int lastTransactionTime;
  39703. Font currentFont;
  39704. mutable int totalNumChars;
  39705. int caretPosition;
  39706. Array <UniformTextSection*> sections;
  39707. String textToShowWhenEmpty;
  39708. Colour colourForTextWhenEmpty;
  39709. juce_wchar passwordCharacter;
  39710. Value textValue;
  39711. enum
  39712. {
  39713. notDragging,
  39714. draggingSelectionStart,
  39715. draggingSelectionEnd
  39716. } dragType;
  39717. String allowedCharacters;
  39718. ListenerList <Listener> listeners;
  39719. Array <Range<int> > underlinedSections;
  39720. void coalesceSimilarSections();
  39721. void splitSection (int sectionIndex, int charToSplitAt);
  39722. void clearInternal (UndoManager* um);
  39723. void insert (const String& text, int insertIndex, const Font& font,
  39724. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  39725. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  39726. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  39727. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  39728. void updateCaretPosition();
  39729. void updateValueFromText();
  39730. void textWasChangedByValue();
  39731. int indexAtPosition (float x, float y);
  39732. int findWordBreakAfter (int position) const;
  39733. int findWordBreakBefore (int position) const;
  39734. bool moveCaretWithTransation (int newPos, bool selecting);
  39735. friend class TextHolderComponent;
  39736. friend class TextEditorViewport;
  39737. void drawContent (Graphics& g);
  39738. void updateTextHolderSize();
  39739. float getWordWrapWidth() const;
  39740. void timerCallbackInt();
  39741. void repaintText (const Range<int>& range);
  39742. void scrollByLines (int deltaLines);
  39743. bool undoOrRedo (bool shouldUndo);
  39744. UndoManager* getUndoManager() noexcept;
  39745. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditor);
  39746. };
  39747. /** This typedef is just for compatibility with old code - newer code should use the TextEditor::Listener class directly. */
  39748. typedef TextEditor::Listener TextEditorListener;
  39749. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  39750. /*** End of inlined file: juce_TextEditor.h ***/
  39751. #if JUCE_VC6
  39752. #define Listener ButtonListener
  39753. #endif
  39754. /**
  39755. A component that displays a text string, and can optionally become a text
  39756. editor when clicked.
  39757. */
  39758. class JUCE_API Label : public Component,
  39759. public SettableTooltipClient,
  39760. protected TextEditorListener,
  39761. private ComponentListener,
  39762. private ValueListener
  39763. {
  39764. public:
  39765. /** Creates a Label.
  39766. @param componentName the name to give the component
  39767. @param labelText the text to show in the label
  39768. */
  39769. Label (const String& componentName = String::empty,
  39770. const String& labelText = String::empty);
  39771. /** Destructor. */
  39772. ~Label();
  39773. /** Changes the label text.
  39774. If broadcastChangeMessage is true and the new text is different to the current
  39775. text, then the class will broadcast a change message to any Label::Listener objects
  39776. that are registered.
  39777. */
  39778. void setText (const String& newText, bool broadcastChangeMessage);
  39779. /** Returns the label's current text.
  39780. @param returnActiveEditorContents if this is true and the label is currently
  39781. being edited, then this method will return the
  39782. text as it's being shown in the editor. If false,
  39783. then the value returned here won't be updated until
  39784. the user has finished typing and pressed the return
  39785. key.
  39786. */
  39787. String getText (bool returnActiveEditorContents = false) const;
  39788. /** Returns the text content as a Value object.
  39789. You can call Value::referTo() on this object to make the label read and control
  39790. a Value object that you supply.
  39791. */
  39792. Value& getTextValue() { return textValue; }
  39793. /** Changes the font to use to draw the text.
  39794. @see getFont
  39795. */
  39796. void setFont (const Font& newFont);
  39797. /** Returns the font currently being used.
  39798. @see setFont
  39799. */
  39800. const Font& getFont() const noexcept;
  39801. /** A set of colour IDs to use to change the colour of various aspects of the label.
  39802. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39803. methods.
  39804. Note that you can also use the constants from TextEditor::ColourIds to change the
  39805. colour of the text editor that is opened when a label is editable.
  39806. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39807. */
  39808. enum ColourIds
  39809. {
  39810. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  39811. textColourId = 0x1000281, /**< The colour for the text. */
  39812. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  39813. Leave this transparent to not have an outline. */
  39814. };
  39815. /** Sets the style of justification to be used for positioning the text.
  39816. (The default is Justification::centredLeft)
  39817. */
  39818. void setJustificationType (const Justification& justification);
  39819. /** Returns the type of justification, as set in setJustificationType(). */
  39820. const Justification getJustificationType() const noexcept { return justification; }
  39821. /** Changes the gap that is left between the edge of the component and the text.
  39822. By default there's a small gap left at the sides of the component to allow for
  39823. the drawing of the border, but you can change this if necessary.
  39824. */
  39825. void setBorderSize (int horizontalBorder, int verticalBorder);
  39826. /** Returns the size of the horizontal gap being left around the text.
  39827. */
  39828. int getHorizontalBorderSize() const noexcept { return horizontalBorderSize; }
  39829. /** Returns the size of the vertical gap being left around the text.
  39830. */
  39831. int getVerticalBorderSize() const noexcept { return verticalBorderSize; }
  39832. /** Makes this label "stick to" another component.
  39833. This will cause the label to follow another component around, staying
  39834. either to its left or above it.
  39835. @param owner the component to follow
  39836. @param onLeft if true, the label will stay on the left of its component; if
  39837. false, it will stay above it.
  39838. */
  39839. void attachToComponent (Component* owner, bool onLeft);
  39840. /** If this label has been attached to another component using attachToComponent, this
  39841. returns the other component.
  39842. Returns 0 if the label is not attached.
  39843. */
  39844. Component* getAttachedComponent() const;
  39845. /** If the label is attached to the left of another component, this returns true.
  39846. Returns false if the label is above the other component. This is only relevent if
  39847. attachToComponent() has been called.
  39848. */
  39849. bool isAttachedOnLeft() const noexcept { return leftOfOwnerComp; }
  39850. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  39851. using ellipsis.
  39852. @see Graphics::drawFittedText
  39853. */
  39854. void setMinimumHorizontalScale (float newScale);
  39855. float getMinimumHorizontalScale() const noexcept { return minimumHorizontalScale; }
  39856. /**
  39857. A class for receiving events from a Label.
  39858. You can register a Label::Listener with a Label using the Label::addListener()
  39859. method, and it will be called when the text of the label changes, either because
  39860. of a call to Label::setText() or by the user editing the text (if the label is
  39861. editable).
  39862. @see Label::addListener, Label::removeListener
  39863. */
  39864. class JUCE_API Listener
  39865. {
  39866. public:
  39867. /** Destructor. */
  39868. virtual ~Listener() {}
  39869. /** Called when a Label's text has changed.
  39870. */
  39871. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  39872. };
  39873. /** Registers a listener that will be called when the label's text changes. */
  39874. void addListener (Listener* listener);
  39875. /** Deregisters a previously-registered listener. */
  39876. void removeListener (Listener* listener);
  39877. /** Makes the label turn into a TextEditor when clicked.
  39878. By default this is turned off.
  39879. If turned on, then single- or double-clicking will turn the label into
  39880. an editor. If the user then changes the text, then the ChangeBroadcaster
  39881. base class will be used to send change messages to any listeners that
  39882. have registered.
  39883. If the user changes the text, the textWasEdited() method will be called
  39884. afterwards, and subclasses can override this if they need to do anything
  39885. special.
  39886. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  39887. @param editOnDoubleClick if true, a double-click is needed to start editing
  39888. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  39889. edited will discard any changes; if false, then this will
  39890. commit the changes.
  39891. @see showEditor, setEditorColours, TextEditor
  39892. */
  39893. void setEditable (bool editOnSingleClick,
  39894. bool editOnDoubleClick = false,
  39895. bool lossOfFocusDiscardsChanges = false);
  39896. /** Returns true if this option was set using setEditable(). */
  39897. bool isEditableOnSingleClick() const noexcept { return editSingleClick; }
  39898. /** Returns true if this option was set using setEditable(). */
  39899. bool isEditableOnDoubleClick() const noexcept { return editDoubleClick; }
  39900. /** Returns true if this option has been set in a call to setEditable(). */
  39901. bool doesLossOfFocusDiscardChanges() const noexcept { return lossOfFocusDiscardsChanges; }
  39902. /** Returns true if the user can edit this label's text. */
  39903. bool isEditable() const noexcept { return editSingleClick || editDoubleClick; }
  39904. /** Makes the editor appear as if the label had been clicked by the user.
  39905. @see textWasEdited, setEditable
  39906. */
  39907. void showEditor();
  39908. /** Hides the editor if it was being shown.
  39909. @param discardCurrentEditorContents if true, the label's text will be
  39910. reset to whatever it was before the editor
  39911. was shown; if false, the current contents of the
  39912. editor will be used to set the label's text
  39913. before it is hidden.
  39914. */
  39915. void hideEditor (bool discardCurrentEditorContents);
  39916. /** Returns true if the editor is currently focused and active. */
  39917. bool isBeingEdited() const noexcept;
  39918. protected:
  39919. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  39920. Subclasses can override this if they need to customise this component in some way.
  39921. */
  39922. virtual TextEditor* createEditorComponent();
  39923. /** Called after the user changes the text. */
  39924. virtual void textWasEdited();
  39925. /** Called when the text has been altered. */
  39926. virtual void textWasChanged();
  39927. /** Called when the text editor has just appeared, due to a user click or other focus change. */
  39928. virtual void editorShown (TextEditor* editorComponent);
  39929. /** Called when the text editor is going to be deleted, after editing has finished. */
  39930. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  39931. /** @internal */
  39932. void paint (Graphics& g);
  39933. /** @internal */
  39934. void resized();
  39935. /** @internal */
  39936. void mouseUp (const MouseEvent& e);
  39937. /** @internal */
  39938. void mouseDoubleClick (const MouseEvent& e);
  39939. /** @internal */
  39940. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  39941. /** @internal */
  39942. void componentParentHierarchyChanged (Component& component);
  39943. /** @internal */
  39944. void componentVisibilityChanged (Component& component);
  39945. /** @internal */
  39946. void inputAttemptWhenModal();
  39947. /** @internal */
  39948. void focusGained (FocusChangeType);
  39949. /** @internal */
  39950. void enablementChanged();
  39951. /** @internal */
  39952. KeyboardFocusTraverser* createFocusTraverser();
  39953. /** @internal */
  39954. void textEditorTextChanged (TextEditor& editor);
  39955. /** @internal */
  39956. void textEditorReturnKeyPressed (TextEditor& editor);
  39957. /** @internal */
  39958. void textEditorEscapeKeyPressed (TextEditor& editor);
  39959. /** @internal */
  39960. void textEditorFocusLost (TextEditor& editor);
  39961. /** @internal */
  39962. void colourChanged();
  39963. /** @internal */
  39964. void valueChanged (Value&);
  39965. private:
  39966. Value textValue;
  39967. String lastTextValue;
  39968. Font font;
  39969. Justification justification;
  39970. ScopedPointer<TextEditor> editor;
  39971. ListenerList<Listener> listeners;
  39972. WeakReference<Component> ownerComponent;
  39973. int horizontalBorderSize, verticalBorderSize;
  39974. float minimumHorizontalScale;
  39975. bool editSingleClick : 1;
  39976. bool editDoubleClick : 1;
  39977. bool lossOfFocusDiscardsChanges : 1;
  39978. bool leftOfOwnerComp : 1;
  39979. bool updateFromTextEditorContents (TextEditor&);
  39980. void callChangeListeners();
  39981. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Label);
  39982. };
  39983. /** This typedef is just for compatibility with old code - newer code should use the Label::Listener class directly. */
  39984. typedef Label::Listener LabelListener;
  39985. #if JUCE_VC6
  39986. #undef Listener
  39987. #endif
  39988. #endif // __JUCE_LABEL_JUCEHEADER__
  39989. /*** End of inlined file: juce_Label.h ***/
  39990. #if JUCE_VC6
  39991. #define Listener SliderListener
  39992. #endif
  39993. /**
  39994. A component that lets the user choose from a drop-down list of choices.
  39995. The combo-box has a list of text strings, each with an associated id number,
  39996. that will be shown in the drop-down list when the user clicks on the component.
  39997. The currently selected choice is displayed in the combo-box, and this can
  39998. either be read-only text, or editable.
  39999. To find out when the user selects a different item or edits the text, you
  40000. can register a ComboBox::Listener to receive callbacks.
  40001. @see ComboBox::Listener
  40002. */
  40003. class JUCE_API ComboBox : public Component,
  40004. public SettableTooltipClient,
  40005. public LabelListener, // (can't use Label::Listener due to idiotic VC2005 bug)
  40006. public ValueListener,
  40007. private AsyncUpdater
  40008. {
  40009. public:
  40010. /** Creates a combo-box.
  40011. On construction, the text field will be empty, so you should call the
  40012. setSelectedId() or setText() method to choose the initial value before
  40013. displaying it.
  40014. @param componentName the name to set for the component (see Component::setName())
  40015. */
  40016. explicit ComboBox (const String& componentName = String::empty);
  40017. /** Destructor. */
  40018. ~ComboBox();
  40019. /** Sets whether the test in the combo-box is editable.
  40020. The default state for a new ComboBox is non-editable, and can only be changed
  40021. by choosing from the drop-down list.
  40022. */
  40023. void setEditableText (bool isEditable);
  40024. /** Returns true if the text is directly editable.
  40025. @see setEditableText
  40026. */
  40027. bool isTextEditable() const noexcept;
  40028. /** Sets the style of justification to be used for positioning the text.
  40029. The default is Justification::centredLeft. The text is displayed using a
  40030. Label component inside the ComboBox.
  40031. */
  40032. void setJustificationType (const Justification& justification);
  40033. /** Returns the current justification for the text box.
  40034. @see setJustificationType
  40035. */
  40036. const Justification getJustificationType() const noexcept;
  40037. /** Adds an item to be shown in the drop-down list.
  40038. @param newItemText the text of the item to show in the list
  40039. @param newItemId an associated ID number that can be set or retrieved - see
  40040. getSelectedId() and setSelectedId(). Note that this value can not
  40041. be 0!
  40042. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  40043. */
  40044. void addItem (const String& newItemText, int newItemId);
  40045. /** Adds a separator line to the drop-down list.
  40046. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  40047. */
  40048. void addSeparator();
  40049. /** Adds a heading to the drop-down list, so that you can group the items into
  40050. different sections.
  40051. The headings are indented slightly differently to set them apart from the
  40052. items on the list, and obviously can't be selected. You might want to add
  40053. separators between your sections too.
  40054. @see addItem, addSeparator
  40055. */
  40056. void addSectionHeading (const String& headingName);
  40057. /** This allows items in the drop-down list to be selectively disabled.
  40058. When you add an item, it's enabled by default, but you can call this
  40059. method to change its status.
  40060. If you disable an item which is already selected, this won't change the
  40061. current selection - it just stops the user choosing that item from the list.
  40062. */
  40063. void setItemEnabled (int itemId, bool shouldBeEnabled);
  40064. /** Returns true if the given item is enabled. */
  40065. bool isItemEnabled (int itemId) const noexcept;
  40066. /** Changes the text for an existing item.
  40067. */
  40068. void changeItemText (int itemId, const String& newText);
  40069. /** Removes all the items from the drop-down list.
  40070. If this call causes the content to be cleared, then a change-message
  40071. will be broadcast unless dontSendChangeMessage is true.
  40072. @see addItem, removeItem, getNumItems
  40073. */
  40074. void clear (bool dontSendChangeMessage = false);
  40075. /** Returns the number of items that have been added to the list.
  40076. Note that this doesn't include headers or separators.
  40077. */
  40078. int getNumItems() const noexcept;
  40079. /** Returns the text for one of the items in the list.
  40080. Note that this doesn't include headers or separators.
  40081. @param index the item's index from 0 to (getNumItems() - 1)
  40082. */
  40083. String getItemText (int index) const;
  40084. /** Returns the ID for one of the items in the list.
  40085. Note that this doesn't include headers or separators.
  40086. @param index the item's index from 0 to (getNumItems() - 1)
  40087. */
  40088. int getItemId (int index) const noexcept;
  40089. /** Returns the index in the list of a particular item ID.
  40090. If no such ID is found, this will return -1.
  40091. */
  40092. int indexOfItemId (int itemId) const noexcept;
  40093. /** Returns the ID of the item that's currently shown in the box.
  40094. If no item is selected, or if the text is editable and the user
  40095. has entered something which isn't one of the items in the list, then
  40096. this will return 0.
  40097. @see setSelectedId, getSelectedItemIndex, getText
  40098. */
  40099. int getSelectedId() const noexcept;
  40100. /** Returns a Value object that can be used to get or set the selected item's ID.
  40101. You can call Value::referTo() on this object to make the combo box control
  40102. another Value object.
  40103. */
  40104. Value& getSelectedIdAsValue() { return currentId; }
  40105. /** Sets one of the items to be the current selection.
  40106. This will set the ComboBox's text to that of the item that matches
  40107. this ID.
  40108. @param newItemId the new item to select
  40109. @param dontSendChangeMessage if set to true, this method won't trigger a
  40110. change notification
  40111. @see getSelectedId, setSelectedItemIndex, setText
  40112. */
  40113. void setSelectedId (int newItemId, bool dontSendChangeMessage = false);
  40114. /** Returns the index of the item that's currently shown in the box.
  40115. If no item is selected, or if the text is editable and the user
  40116. has entered something which isn't one of the items in the list, then
  40117. this will return -1.
  40118. @see setSelectedItemIndex, getSelectedId, getText
  40119. */
  40120. int getSelectedItemIndex() const;
  40121. /** Sets one of the items to be the current selection.
  40122. This will set the ComboBox's text to that of the item at the given
  40123. index in the list.
  40124. @param newItemIndex the new item to select
  40125. @param dontSendChangeMessage if set to true, this method won't trigger a
  40126. change notification
  40127. @see getSelectedItemIndex, setSelectedId, setText
  40128. */
  40129. void setSelectedItemIndex (int newItemIndex, bool dontSendChangeMessage = false);
  40130. /** Returns the text that is currently shown in the combo-box's text field.
  40131. If the ComboBox has editable text, then this text may have been edited
  40132. by the user; otherwise it will be one of the items from the list, or
  40133. possibly an empty string if nothing was selected.
  40134. @see setText, getSelectedId, getSelectedItemIndex
  40135. */
  40136. String getText() const;
  40137. /** Sets the contents of the combo-box's text field.
  40138. The text passed-in will be set as the current text regardless of whether
  40139. it is one of the items in the list. If the current text isn't one of the
  40140. items, then getSelectedId() will return -1, otherwise it wil return
  40141. the approriate ID.
  40142. @param newText the text to select
  40143. @param dontSendChangeMessage if set to true, this method won't trigger a
  40144. change notification
  40145. @see getText
  40146. */
  40147. void setText (const String& newText, bool dontSendChangeMessage = false);
  40148. /** Programmatically opens the text editor to allow the user to edit the current item.
  40149. This is the same effect as when the box is clicked-on.
  40150. @see Label::showEditor();
  40151. */
  40152. void showEditor();
  40153. /** Pops up the combo box's list. */
  40154. void showPopup();
  40155. /**
  40156. A class for receiving events from a ComboBox.
  40157. You can register a ComboBox::Listener with a ComboBox using the ComboBox::addListener()
  40158. method, and it will be called when the selected item in the box changes.
  40159. @see ComboBox::addListener, ComboBox::removeListener
  40160. */
  40161. class JUCE_API Listener
  40162. {
  40163. public:
  40164. /** Destructor. */
  40165. virtual ~Listener() {}
  40166. /** Called when a ComboBox has its selected item changed. */
  40167. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  40168. };
  40169. /** Registers a listener that will be called when the box's content changes. */
  40170. void addListener (Listener* listener);
  40171. /** Deregisters a previously-registered listener. */
  40172. void removeListener (Listener* listener);
  40173. /** Sets a message to display when there is no item currently selected.
  40174. @see getTextWhenNothingSelected
  40175. */
  40176. void setTextWhenNothingSelected (const String& newMessage);
  40177. /** Returns the text that is shown when no item is selected.
  40178. @see setTextWhenNothingSelected
  40179. */
  40180. String getTextWhenNothingSelected() const;
  40181. /** Sets the message to show when there are no items in the list, and the user clicks
  40182. on the drop-down box.
  40183. By default it just says "no choices", but this lets you change it to something more
  40184. meaningful.
  40185. */
  40186. void setTextWhenNoChoicesAvailable (const String& newMessage);
  40187. /** Returns the text shown when no items have been added to the list.
  40188. @see setTextWhenNoChoicesAvailable
  40189. */
  40190. String getTextWhenNoChoicesAvailable() const;
  40191. /** Gives the ComboBox a tooltip. */
  40192. void setTooltip (const String& newTooltip);
  40193. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  40194. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40195. methods.
  40196. To change the colours of the menu that pops up
  40197. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40198. */
  40199. enum ColourIds
  40200. {
  40201. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  40202. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  40203. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  40204. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  40205. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  40206. };
  40207. /** @internal */
  40208. void labelTextChanged (Label*);
  40209. /** @internal */
  40210. void enablementChanged();
  40211. /** @internal */
  40212. void colourChanged();
  40213. /** @internal */
  40214. void focusGained (Component::FocusChangeType cause);
  40215. /** @internal */
  40216. void focusLost (Component::FocusChangeType cause);
  40217. /** @internal */
  40218. void handleAsyncUpdate();
  40219. /** @internal */
  40220. const String getTooltip() { return label->getTooltip(); }
  40221. /** @internal */
  40222. void mouseDown (const MouseEvent&);
  40223. /** @internal */
  40224. void mouseDrag (const MouseEvent&);
  40225. /** @internal */
  40226. void mouseUp (const MouseEvent&);
  40227. /** @internal */
  40228. void lookAndFeelChanged();
  40229. /** @internal */
  40230. void paint (Graphics&);
  40231. /** @internal */
  40232. void resized();
  40233. /** @internal */
  40234. bool keyStateChanged (bool isKeyDown);
  40235. /** @internal */
  40236. bool keyPressed (const KeyPress&);
  40237. /** @internal */
  40238. void valueChanged (Value&);
  40239. private:
  40240. struct ItemInfo
  40241. {
  40242. ItemInfo (const String& name, int itemId, bool isEnabled, bool isHeading);
  40243. bool isSeparator() const noexcept;
  40244. bool isRealItem() const noexcept;
  40245. String name;
  40246. int itemId;
  40247. bool isEnabled : 1, isHeading : 1;
  40248. };
  40249. OwnedArray <ItemInfo> items;
  40250. Value currentId;
  40251. int lastCurrentId;
  40252. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  40253. ListenerList <Listener> listeners;
  40254. ScopedPointer<Label> label;
  40255. String textWhenNothingSelected, noChoicesMessage;
  40256. ItemInfo* getItemForId (int itemId) const noexcept;
  40257. ItemInfo* getItemForIndex (int index) const noexcept;
  40258. bool selectIfEnabled (int index);
  40259. static void popupMenuFinishedCallback (int, ComboBox*);
  40260. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBox);
  40261. };
  40262. /** This typedef is just for compatibility with old code - newer code should use the ComboBox::Listener class directly. */
  40263. typedef ComboBox::Listener ComboBoxListener;
  40264. #if JUCE_VC6
  40265. #undef Listener
  40266. #endif
  40267. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  40268. /*** End of inlined file: juce_ComboBox.h ***/
  40269. #endif
  40270. #ifndef __JUCE_IMAGECOMPONENT_JUCEHEADER__
  40271. /*** Start of inlined file: juce_ImageComponent.h ***/
  40272. #ifndef __JUCE_IMAGECOMPONENT_JUCEHEADER__
  40273. #define __JUCE_IMAGECOMPONENT_JUCEHEADER__
  40274. /**
  40275. A component that simply displays an image.
  40276. Use setImage to give it an image, and it'll display it - simple as that!
  40277. */
  40278. class JUCE_API ImageComponent : public Component,
  40279. public SettableTooltipClient
  40280. {
  40281. public:
  40282. /** Creates an ImageComponent. */
  40283. ImageComponent (const String& componentName = String::empty);
  40284. /** Destructor. */
  40285. ~ImageComponent();
  40286. /** Sets the image that should be displayed. */
  40287. void setImage (const Image& newImage);
  40288. /** Sets the image that should be displayed, and its placement within the component. */
  40289. void setImage (const Image& newImage,
  40290. const RectanglePlacement& placementToUse);
  40291. /** Returns the current image. */
  40292. const Image& getImage() const;
  40293. /** Sets the method of positioning that will be used to fit the image within the component's bounds.
  40294. By default the positioning is centred, and will fit the image inside the component's bounds
  40295. whilst keeping its aspect ratio correct, but you can change it to whatever layout you need.
  40296. */
  40297. void setImagePlacement (const RectanglePlacement& newPlacement);
  40298. /** Returns the current image placement. */
  40299. const RectanglePlacement getImagePlacement() const;
  40300. /** @internal */
  40301. void paint (Graphics& g);
  40302. private:
  40303. Image image;
  40304. RectanglePlacement placement;
  40305. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageComponent);
  40306. };
  40307. #endif // __JUCE_IMAGECOMPONENT_JUCEHEADER__
  40308. /*** End of inlined file: juce_ImageComponent.h ***/
  40309. #endif
  40310. #ifndef __JUCE_LABEL_JUCEHEADER__
  40311. #endif
  40312. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  40313. #endif
  40314. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  40315. /*** Start of inlined file: juce_ProgressBar.h ***/
  40316. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  40317. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  40318. /**
  40319. A progress bar component.
  40320. To use this, just create one and make it visible. It'll run its own timer
  40321. to keep an eye on a variable that you give it, and will automatically
  40322. redraw itself when the variable changes.
  40323. For an easy way of running a background task with a dialog box showing its
  40324. progress, see the ThreadWithProgressWindow class.
  40325. @see ThreadWithProgressWindow
  40326. */
  40327. class JUCE_API ProgressBar : public Component,
  40328. public SettableTooltipClient,
  40329. private Timer
  40330. {
  40331. public:
  40332. /** Creates a ProgressBar.
  40333. @param progress pass in a reference to a double that you're going to
  40334. update with your task's progress. The ProgressBar will
  40335. monitor the value of this variable and will redraw itself
  40336. when the value changes. The range is from 0 to 1.0. Obviously
  40337. you'd better be careful not to delete this variable while the
  40338. ProgressBar still exists!
  40339. */
  40340. explicit ProgressBar (double& progress);
  40341. /** Destructor. */
  40342. ~ProgressBar();
  40343. /** Turns the percentage display on or off.
  40344. By default this is on, and the progress bar will display a text string showing
  40345. its current percentage.
  40346. */
  40347. void setPercentageDisplay (bool shouldDisplayPercentage);
  40348. /** Gives the progress bar a string to display inside it.
  40349. If you call this, it will turn off the percentage display.
  40350. @see setPercentageDisplay
  40351. */
  40352. void setTextToDisplay (const String& text);
  40353. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  40354. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40355. methods.
  40356. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40357. */
  40358. enum ColourIds
  40359. {
  40360. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  40361. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  40362. classes will probably use variations on this colour. */
  40363. };
  40364. protected:
  40365. /** @internal */
  40366. void paint (Graphics& g);
  40367. /** @internal */
  40368. void lookAndFeelChanged();
  40369. /** @internal */
  40370. void visibilityChanged();
  40371. /** @internal */
  40372. void colourChanged();
  40373. private:
  40374. double& progress;
  40375. double currentValue;
  40376. bool displayPercentage;
  40377. String displayedMessage, currentMessage;
  40378. uint32 lastCallbackTime;
  40379. void timerCallback();
  40380. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgressBar);
  40381. };
  40382. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  40383. /*** End of inlined file: juce_ProgressBar.h ***/
  40384. #endif
  40385. #ifndef __JUCE_SLIDER_JUCEHEADER__
  40386. /*** Start of inlined file: juce_Slider.h ***/
  40387. #ifndef __JUCE_SLIDER_JUCEHEADER__
  40388. #define __JUCE_SLIDER_JUCEHEADER__
  40389. #if JUCE_VC6
  40390. #define Listener LabelListener
  40391. #endif
  40392. /**
  40393. A slider control for changing a value.
  40394. The slider can be horizontal, vertical, or rotary, and can optionally have
  40395. a text-box inside it to show an editable display of the current value.
  40396. To use it, create a Slider object and use the setSliderStyle() method
  40397. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  40398. To define the values that it can be set to, see the setRange() and setValue() methods.
  40399. There are also lots of custom tweaks you can do by subclassing and overriding
  40400. some of the virtual methods, such as changing the scaling, changing the format of
  40401. the text display, custom ways of limiting the values, etc.
  40402. You can register Slider::Listener objects with a slider, and they'll be called when
  40403. the value changes.
  40404. @see Slider::Listener
  40405. */
  40406. class JUCE_API Slider : public Component,
  40407. public SettableTooltipClient,
  40408. public AsyncUpdater,
  40409. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  40410. public LabelListener,
  40411. public ValueListener
  40412. {
  40413. public:
  40414. /** Creates a slider.
  40415. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  40416. setRange(), etc.
  40417. */
  40418. explicit Slider (const String& componentName = String::empty);
  40419. /** Destructor. */
  40420. ~Slider();
  40421. /** The types of slider available.
  40422. @see setSliderStyle, setRotaryParameters
  40423. */
  40424. enum SliderStyle
  40425. {
  40426. LinearHorizontal, /**< A traditional horizontal slider. */
  40427. LinearVertical, /**< A traditional vertical slider. */
  40428. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  40429. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  40430. @see setRotaryParameters */
  40431. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  40432. @see setRotaryParameters */
  40433. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  40434. @see setRotaryParameters */
  40435. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  40436. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  40437. @see setMinValue, setMaxValue */
  40438. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  40439. @see setMinValue, setMaxValue */
  40440. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  40441. value, with the current value being somewhere between them.
  40442. @see setMinValue, setMaxValue */
  40443. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  40444. value, with the current value being somewhere between them.
  40445. @see setMinValue, setMaxValue */
  40446. };
  40447. /** Changes the type of slider interface being used.
  40448. @param newStyle the type of interface
  40449. @see setRotaryParameters, setVelocityBasedMode,
  40450. */
  40451. void setSliderStyle (SliderStyle newStyle);
  40452. /** Returns the slider's current style.
  40453. @see setSliderStyle
  40454. */
  40455. SliderStyle getSliderStyle() const noexcept { return style; }
  40456. /** Changes the properties of a rotary slider.
  40457. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  40458. the slider's minimum value is represented
  40459. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  40460. the slider's maximum value is represented. This must be
  40461. greater than startAngleRadians
  40462. @param stopAtEnd if true, then when the slider is dragged around past the
  40463. minimum or maximum, it'll stop there; if false, it'll wrap
  40464. back to the opposite value
  40465. */
  40466. void setRotaryParameters (float startAngleRadians,
  40467. float endAngleRadians,
  40468. bool stopAtEnd);
  40469. /** Sets the distance the mouse has to move to drag the slider across
  40470. the full extent of its range.
  40471. This only applies when in modes like RotaryHorizontalDrag, where it's using
  40472. relative mouse movements to adjust the slider.
  40473. */
  40474. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  40475. /** Returns the current sensitivity value set by setMouseDragSensitivity(). */
  40476. int getMouseDragSensitivity() const noexcept { return pixelsForFullDragExtent; }
  40477. /** Changes the way the the mouse is used when dragging the slider.
  40478. If true, this will turn on velocity-sensitive dragging, so that
  40479. the faster the mouse moves, the bigger the movement to the slider. This
  40480. helps when making accurate adjustments if the slider's range is quite large.
  40481. If false, the slider will just try to snap to wherever the mouse is.
  40482. */
  40483. void setVelocityBasedMode (bool isVelocityBased);
  40484. /** Returns true if velocity-based mode is active.
  40485. @see setVelocityBasedMode
  40486. */
  40487. bool getVelocityBasedMode() const noexcept { return isVelocityBased; }
  40488. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  40489. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  40490. or if you're holding down ctrl.
  40491. @param sensitivity higher values than 1.0 increase the range of acceleration used
  40492. @param threshold the minimum number of pixels that the mouse needs to move for it
  40493. to be treated as a movement
  40494. @param offset values greater than 0.0 increase the minimum speed that will be used when
  40495. the threshold is reached
  40496. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  40497. key to toggle velocity-sensitive mode
  40498. */
  40499. void setVelocityModeParameters (double sensitivity = 1.0,
  40500. int threshold = 1,
  40501. double offset = 0.0,
  40502. bool userCanPressKeyToSwapMode = true);
  40503. /** Returns the velocity sensitivity setting.
  40504. @see setVelocityModeParameters
  40505. */
  40506. double getVelocitySensitivity() const noexcept { return velocityModeSensitivity; }
  40507. /** Returns the velocity threshold setting.
  40508. @see setVelocityModeParameters
  40509. */
  40510. int getVelocityThreshold() const noexcept { return velocityModeThreshold; }
  40511. /** Returns the velocity offset setting.
  40512. @see setVelocityModeParameters
  40513. */
  40514. double getVelocityOffset() const noexcept { return velocityModeOffset; }
  40515. /** Returns the velocity user key setting.
  40516. @see setVelocityModeParameters
  40517. */
  40518. bool getVelocityModeIsSwappable() const noexcept { return userKeyOverridesVelocity; }
  40519. /** Sets up a skew factor to alter the way values are distributed.
  40520. You may want to use a range of values on the slider where more accuracy
  40521. is required towards one end of the range, so this will logarithmically
  40522. spread the values across the length of the slider.
  40523. If the factor is < 1.0, the lower end of the range will fill more of the
  40524. slider's length; if the factor is > 1.0, the upper end of the range
  40525. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  40526. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  40527. method instead.
  40528. @see getSkewFactor, setSkewFactorFromMidPoint
  40529. */
  40530. void setSkewFactor (double factor);
  40531. /** Sets up a skew factor to alter the way values are distributed.
  40532. This allows you to specify the slider value that should appear in the
  40533. centre of the slider's visible range.
  40534. @see setSkewFactor, getSkewFactor
  40535. */
  40536. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  40537. /** Returns the current skew factor.
  40538. See setSkewFactor for more info.
  40539. @see setSkewFactor, setSkewFactorFromMidPoint
  40540. */
  40541. double getSkewFactor() const noexcept { return skewFactor; }
  40542. /** Used by setIncDecButtonsMode().
  40543. */
  40544. enum IncDecButtonMode
  40545. {
  40546. incDecButtonsNotDraggable,
  40547. incDecButtonsDraggable_AutoDirection,
  40548. incDecButtonsDraggable_Horizontal,
  40549. incDecButtonsDraggable_Vertical
  40550. };
  40551. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  40552. can be dragged on the buttons to drag the values.
  40553. By default this is turned off. When enabled, clicking on the buttons still works
  40554. them as normal, but by holding down the mouse on a button and dragging it a little
  40555. distance, it flips into a mode where the value can be dragged. The drag direction can
  40556. either be set explicitly to be vertical or horizontal, or can be set to
  40557. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  40558. are side-by-side or above each other.
  40559. */
  40560. void setIncDecButtonsMode (IncDecButtonMode mode);
  40561. /** The position of the slider's text-entry box.
  40562. @see setTextBoxStyle
  40563. */
  40564. enum TextEntryBoxPosition
  40565. {
  40566. NoTextBox, /**< Doesn't display a text box. */
  40567. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  40568. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  40569. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  40570. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  40571. };
  40572. /** Changes the location and properties of the text-entry box.
  40573. @param newPosition where it should go (or NoTextBox to not have one at all)
  40574. @param isReadOnly if true, it's a read-only display
  40575. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  40576. room for the slider as well!
  40577. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  40578. room for the slider as well!
  40579. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  40580. */
  40581. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  40582. bool isReadOnly,
  40583. int textEntryBoxWidth,
  40584. int textEntryBoxHeight);
  40585. /** Returns the status of the text-box.
  40586. @see setTextBoxStyle
  40587. */
  40588. const TextEntryBoxPosition getTextBoxPosition() const noexcept { return textBoxPos; }
  40589. /** Returns the width used for the text-box.
  40590. @see setTextBoxStyle
  40591. */
  40592. int getTextBoxWidth() const noexcept { return textBoxWidth; }
  40593. /** Returns the height used for the text-box.
  40594. @see setTextBoxStyle
  40595. */
  40596. int getTextBoxHeight() const noexcept { return textBoxHeight; }
  40597. /** Makes the text-box editable.
  40598. By default this is true, and the user can enter values into the textbox,
  40599. but it can be turned off if that's not suitable.
  40600. @see setTextBoxStyle, getValueFromText, getTextFromValue
  40601. */
  40602. void setTextBoxIsEditable (bool shouldBeEditable);
  40603. /** Returns true if the text-box is read-only.
  40604. @see setTextBoxStyle
  40605. */
  40606. bool isTextBoxEditable() const { return editableText; }
  40607. /** If the text-box is editable, this will give it the focus so that the user can
  40608. type directly into it.
  40609. This is basically the effect as the user clicking on it.
  40610. */
  40611. void showTextBox();
  40612. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  40613. focus away from it.
  40614. @param discardCurrentEditorContents if true, the slider's value will be left
  40615. unchanged; if false, the current contents of the
  40616. text editor will be used to set the slider position
  40617. before it is hidden.
  40618. */
  40619. void hideTextBox (bool discardCurrentEditorContents);
  40620. /** Changes the slider's current value.
  40621. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40622. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40623. want to handle it.
  40624. @param newValue the new value to set - this will be restricted by the
  40625. minimum and maximum range, and will be snapped to the
  40626. nearest interval if one has been set
  40627. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40628. any Slider::Listeners or the valueChanged() method
  40629. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40630. synchronously; if false, it will be asynchronous
  40631. */
  40632. void setValue (double newValue,
  40633. bool sendUpdateMessage = true,
  40634. bool sendMessageSynchronously = false);
  40635. /** Returns the slider's current value. */
  40636. double getValue() const;
  40637. /** Returns the Value object that represents the slider's current position.
  40638. You can use this Value object to connect the slider's position to external values or setters,
  40639. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  40640. your own Value object.
  40641. @see Value, getMaxValue, getMinValueObject
  40642. */
  40643. Value& getValueObject() { return currentValue; }
  40644. /** Sets the limits that the slider's value can take.
  40645. @param newMinimum the lowest value allowed
  40646. @param newMaximum the highest value allowed
  40647. @param newInterval the steps in which the value is allowed to increase - if this
  40648. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  40649. */
  40650. void setRange (double newMinimum,
  40651. double newMaximum,
  40652. double newInterval = 0);
  40653. /** Returns the current maximum value.
  40654. @see setRange
  40655. */
  40656. double getMaximum() const { return maximum; }
  40657. /** Returns the current minimum value.
  40658. @see setRange
  40659. */
  40660. double getMinimum() const { return minimum; }
  40661. /** Returns the current step-size for values.
  40662. @see setRange
  40663. */
  40664. double getInterval() const { return interval; }
  40665. /** For a slider with two or three thumbs, this returns the lower of its values.
  40666. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  40667. A slider with three values also uses the normal getValue() and setValue() methods to
  40668. control the middle value.
  40669. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  40670. */
  40671. double getMinValue() const;
  40672. /** For a slider with two or three thumbs, this returns the lower of its values.
  40673. You can use this Value object to connect the slider's position to external values or setters,
  40674. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  40675. your own Value object.
  40676. @see Value, getMinValue, getMaxValueObject
  40677. */
  40678. Value& getMinValueObject() noexcept { return valueMin; }
  40679. /** For a slider with two or three thumbs, this sets the lower of its values.
  40680. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40681. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40682. want to handle it.
  40683. @param newValue the new value to set - this will be restricted by the
  40684. minimum and maximum range, and will be snapped to the nearest
  40685. interval if one has been set.
  40686. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40687. any Slider::Listeners or the valueChanged() method
  40688. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40689. synchronously; if false, it will be asynchronous
  40690. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  40691. max value (in a two-value slider) or the mid value (in a three-value
  40692. slider). If false, then if this value goes beyond those values,
  40693. it will push them along with it.
  40694. @see getMinValue, setMaxValue, setValue
  40695. */
  40696. void setMinValue (double newValue,
  40697. bool sendUpdateMessage = true,
  40698. bool sendMessageSynchronously = false,
  40699. bool allowNudgingOfOtherValues = false);
  40700. /** For a slider with two or three thumbs, this returns the higher of its values.
  40701. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  40702. A slider with three values also uses the normal getValue() and setValue() methods to
  40703. control the middle value.
  40704. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  40705. */
  40706. double getMaxValue() const;
  40707. /** For a slider with two or three thumbs, this returns the higher of its values.
  40708. You can use this Value object to connect the slider's position to external values or setters,
  40709. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  40710. your own Value object.
  40711. @see Value, getMaxValue, getMinValueObject
  40712. */
  40713. Value& getMaxValueObject() noexcept { return valueMax; }
  40714. /** For a slider with two or three thumbs, this sets the lower of its values.
  40715. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40716. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40717. want to handle it.
  40718. @param newValue the new value to set - this will be restricted by the
  40719. minimum and maximum range, and will be snapped to the nearest
  40720. interval if one has been set.
  40721. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40722. any Slider::Listeners or the valueChanged() method
  40723. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40724. synchronously; if false, it will be asynchronous
  40725. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  40726. min value (in a two-value slider) or the mid value (in a three-value
  40727. slider). If false, then if this value goes beyond those values,
  40728. it will push them along with it.
  40729. @see getMaxValue, setMinValue, setValue
  40730. */
  40731. void setMaxValue (double newValue,
  40732. bool sendUpdateMessage = true,
  40733. bool sendMessageSynchronously = false,
  40734. bool allowNudgingOfOtherValues = false);
  40735. /** For a slider with two or three thumbs, this sets the minimum and maximum thumb positions.
  40736. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  40737. that are registered, and will synchronously call the valueChanged() method in case subclasses
  40738. want to handle it.
  40739. @param newMinValue the new minimum value to set - this will be snapped to the
  40740. nearest interval if one has been set.
  40741. @param newMaxValue the new minimum value to set - this will be snapped to the
  40742. nearest interval if one has been set.
  40743. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  40744. any Slider::Listeners or the valueChanged() method
  40745. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  40746. synchronously; if false, it will be asynchronous
  40747. @see setMaxValue, setMinValue, setValue
  40748. */
  40749. void setMinAndMaxValues (double newMinValue, double newMaxValue,
  40750. bool sendUpdateMessage = true,
  40751. bool sendMessageSynchronously = false);
  40752. /** A class for receiving callbacks from a Slider.
  40753. To be told when a slider's value changes, you can register a Slider::Listener
  40754. object using Slider::addListener().
  40755. @see Slider::addListener, Slider::removeListener
  40756. */
  40757. class JUCE_API Listener
  40758. {
  40759. public:
  40760. /** Destructor. */
  40761. virtual ~Listener() {}
  40762. /** Called when the slider's value is changed.
  40763. This may be caused by dragging it, or by typing in its text entry box,
  40764. or by a call to Slider::setValue().
  40765. You can find out the new value using Slider::getValue().
  40766. @see Slider::valueChanged
  40767. */
  40768. virtual void sliderValueChanged (Slider* slider) = 0;
  40769. /** Called when the slider is about to be dragged.
  40770. This is called when a drag begins, then it's followed by multiple calls
  40771. to sliderValueChanged(), and then sliderDragEnded() is called after the
  40772. user lets go.
  40773. @see sliderDragEnded, Slider::startedDragging
  40774. */
  40775. virtual void sliderDragStarted (Slider* slider);
  40776. /** Called after a drag operation has finished.
  40777. @see sliderDragStarted, Slider::stoppedDragging
  40778. */
  40779. virtual void sliderDragEnded (Slider* slider);
  40780. };
  40781. /** Adds a listener to be called when this slider's value changes. */
  40782. void addListener (Listener* listener);
  40783. /** Removes a previously-registered listener. */
  40784. void removeListener (Listener* listener);
  40785. /** This lets you choose whether double-clicking moves the slider to a given position.
  40786. By default this is turned off, but it's handy if you want a double-click to act
  40787. as a quick way of resetting a slider. Just pass in the value you want it to
  40788. go to when double-clicked.
  40789. @see getDoubleClickReturnValue
  40790. */
  40791. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  40792. double valueToSetOnDoubleClick);
  40793. /** Returns the values last set by setDoubleClickReturnValue() method.
  40794. Sets isEnabled to true if double-click is enabled, and returns the value
  40795. that was set.
  40796. @see setDoubleClickReturnValue
  40797. */
  40798. double getDoubleClickReturnValue (bool& isEnabled) const;
  40799. /** Tells the slider whether to keep sending change messages while the user
  40800. is dragging the slider.
  40801. If set to true, a change message will only be sent when the user has
  40802. dragged the slider and let go. If set to false (the default), then messages
  40803. will be continuously sent as they drag it while the mouse button is still
  40804. held down.
  40805. */
  40806. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  40807. /** This lets you change whether the slider thumb jumps to the mouse position
  40808. when you click.
  40809. By default, this is true. If it's false, then the slider moves with relative
  40810. motion when you drag it.
  40811. This only applies to linear bars, and won't affect two- or three- value
  40812. sliders.
  40813. */
  40814. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  40815. /** If enabled, this gives the slider a pop-up bubble which appears while the
  40816. slider is being dragged.
  40817. This can be handy if your slider doesn't have a text-box, so that users can
  40818. see the value just when they're changing it.
  40819. If you pass a component as the parentComponentToUse parameter, the pop-up
  40820. bubble will be added as a child of that component when it's needed. If you
  40821. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  40822. transparent window, so if you're using an OS that can't do transparent windows
  40823. you'll have to add it to a parent component instead).
  40824. */
  40825. void setPopupDisplayEnabled (bool isEnabled,
  40826. Component* parentComponentToUse);
  40827. /** If this is set to true, then right-clicking on the slider will pop-up
  40828. a menu to let the user change the way it works.
  40829. By default this is turned off, but when turned on, the menu will include
  40830. things like velocity sensitivity, and for rotary sliders, whether they
  40831. use a linear or rotary mouse-drag to move them.
  40832. */
  40833. void setPopupMenuEnabled (bool menuEnabled);
  40834. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  40835. By default it's enabled.
  40836. */
  40837. void setScrollWheelEnabled (bool enabled);
  40838. /** Returns a number to indicate which thumb is currently being dragged by the
  40839. mouse.
  40840. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  40841. the maximum-value thumb, or -1 if none is currently down.
  40842. */
  40843. int getThumbBeingDragged() const noexcept { return sliderBeingDragged; }
  40844. /** Callback to indicate that the user is about to start dragging the slider.
  40845. @see Slider::Listener::sliderDragStarted
  40846. */
  40847. virtual void startedDragging();
  40848. /** Callback to indicate that the user has just stopped dragging the slider.
  40849. @see Slider::Listener::sliderDragEnded
  40850. */
  40851. virtual void stoppedDragging();
  40852. /** Callback to indicate that the user has just moved the slider.
  40853. @see Slider::Listener::sliderValueChanged
  40854. */
  40855. virtual void valueChanged();
  40856. /** Subclasses can override this to convert a text string to a value.
  40857. When the user enters something into the text-entry box, this method is
  40858. called to convert it to a value.
  40859. The default routine just tries to convert it to a double.
  40860. @see getTextFromValue
  40861. */
  40862. virtual double getValueFromText (const String& text);
  40863. /** Turns the slider's current value into a text string.
  40864. Subclasses can override this to customise the formatting of the text-entry box.
  40865. The default implementation just turns the value into a string, using
  40866. a number of decimal places based on the range interval. If a suffix string
  40867. has been set using setTextValueSuffix(), this will be appended to the text.
  40868. @see getValueFromText
  40869. */
  40870. virtual const String getTextFromValue (double value);
  40871. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  40872. a string.
  40873. This is used by the default implementation of getTextFromValue(), and is just
  40874. appended to the numeric value. For more advanced formatting, you can override
  40875. getTextFromValue() and do something else.
  40876. */
  40877. void setTextValueSuffix (const String& suffix);
  40878. /** Returns the suffix that was set by setTextValueSuffix(). */
  40879. String getTextValueSuffix() const;
  40880. /** Allows a user-defined mapping of distance along the slider to its value.
  40881. The default implementation for this performs the skewing operation that
  40882. can be set up in the setSkewFactor() method. Override it if you need
  40883. some kind of custom mapping instead, but make sure you also implement the
  40884. inverse function in valueToProportionOfLength().
  40885. @param proportion a value 0 to 1.0, indicating a distance along the slider
  40886. @returns the slider value that is represented by this position
  40887. @see valueToProportionOfLength
  40888. */
  40889. virtual double proportionOfLengthToValue (double proportion);
  40890. /** Allows a user-defined mapping of value to the position of the slider along its length.
  40891. The default implementation for this performs the skewing operation that
  40892. can be set up in the setSkewFactor() method. Override it if you need
  40893. some kind of custom mapping instead, but make sure you also implement the
  40894. inverse function in proportionOfLengthToValue().
  40895. @param value a valid slider value, between the range of values specified in
  40896. setRange()
  40897. @returns a value 0 to 1.0 indicating the distance along the slider that
  40898. represents this value
  40899. @see proportionOfLengthToValue
  40900. */
  40901. virtual double valueToProportionOfLength (double value);
  40902. /** Returns the X or Y coordinate of a value along the slider's length.
  40903. If the slider is horizontal, this will be the X coordinate of the given
  40904. value, relative to the left of the slider. If it's vertical, then this will
  40905. be the Y coordinate, relative to the top of the slider.
  40906. If the slider is rotary, this will throw an assertion and return 0. If the
  40907. value is out-of-range, it will be constrained to the length of the slider.
  40908. */
  40909. float getPositionOfValue (double value);
  40910. /** This can be overridden to allow the slider to snap to user-definable values.
  40911. If overridden, it will be called when the user tries to move the slider to
  40912. a given position, and allows a subclass to sanity-check this value, possibly
  40913. returning a different value to use instead.
  40914. @param attemptedValue the value the user is trying to enter
  40915. @param userIsDragging true if the user is dragging with the mouse; false if
  40916. they are entering the value using the text box
  40917. @returns the value to use instead
  40918. */
  40919. virtual double snapValue (double attemptedValue, bool userIsDragging);
  40920. /** This can be called to force the text box to update its contents.
  40921. (Not normally needed, as this is done automatically).
  40922. */
  40923. void updateText();
  40924. /** True if the slider moves horizontally. */
  40925. bool isHorizontal() const;
  40926. /** True if the slider moves vertically. */
  40927. bool isVertical() const;
  40928. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  40929. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40930. methods.
  40931. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40932. */
  40933. enum ColourIds
  40934. {
  40935. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  40936. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  40937. and feel class how this is used. */
  40938. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  40939. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  40940. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  40941. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  40942. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  40943. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  40944. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  40945. };
  40946. protected:
  40947. /** @internal */
  40948. void labelTextChanged (Label*);
  40949. /** @internal */
  40950. void paint (Graphics& g);
  40951. /** @internal */
  40952. void resized();
  40953. /** @internal */
  40954. void mouseDown (const MouseEvent& e);
  40955. /** @internal */
  40956. void mouseUp (const MouseEvent& e);
  40957. /** @internal */
  40958. void mouseDrag (const MouseEvent& e);
  40959. /** @internal */
  40960. void mouseDoubleClick (const MouseEvent& e);
  40961. /** @internal */
  40962. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  40963. /** @internal */
  40964. void modifierKeysChanged (const ModifierKeys& modifiers);
  40965. /** @internal */
  40966. void buttonClicked (Button* button);
  40967. /** @internal */
  40968. void lookAndFeelChanged();
  40969. /** @internal */
  40970. void enablementChanged();
  40971. /** @internal */
  40972. void focusOfChildComponentChanged (FocusChangeType cause);
  40973. /** @internal */
  40974. void handleAsyncUpdate();
  40975. /** @internal */
  40976. void colourChanged();
  40977. /** @internal */
  40978. void valueChanged (Value& value);
  40979. /** Returns the best number of decimal places to use when displaying numbers.
  40980. This is calculated from the slider's interval setting.
  40981. */
  40982. int getNumDecimalPlacesToDisplay() const noexcept { return numDecimalPlaces; }
  40983. private:
  40984. ListenerList <Listener> listeners;
  40985. Value currentValue, valueMin, valueMax;
  40986. double lastCurrentValue, lastValueMin, lastValueMax;
  40987. double minimum, maximum, interval, doubleClickReturnValue;
  40988. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  40989. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  40990. int velocityModeThreshold;
  40991. float rotaryStart, rotaryEnd;
  40992. int numDecimalPlaces;
  40993. Point<int> mousePosWhenLastDragged;
  40994. int mouseDragStartX, mouseDragStartY;
  40995. int sliderRegionStart, sliderRegionSize;
  40996. int sliderBeingDragged;
  40997. int pixelsForFullDragExtent;
  40998. Rectangle<int> sliderRect;
  40999. String textSuffix;
  41000. SliderStyle style;
  41001. TextEntryBoxPosition textBoxPos;
  41002. int textBoxWidth, textBoxHeight;
  41003. IncDecButtonMode incDecButtonMode;
  41004. bool editableText : 1, doubleClickToValue : 1;
  41005. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  41006. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  41007. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  41008. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  41009. ScopedPointer<Label> valueBox;
  41010. ScopedPointer<Button> incButton, decButton;
  41011. class PopupDisplayComponent;
  41012. friend class PopupDisplayComponent;
  41013. friend class ScopedPointer <PopupDisplayComponent>;
  41014. ScopedPointer <PopupDisplayComponent> popupDisplay;
  41015. Component* parentForPopupDisplay;
  41016. float getLinearSliderPos (double value);
  41017. void restoreMouseIfHidden();
  41018. void sendDragStart();
  41019. void sendDragEnd();
  41020. double constrainedValue (double value) const;
  41021. void triggerChangeMessage (bool synchronous);
  41022. bool incDecDragDirectionIsHorizontal() const;
  41023. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Slider);
  41024. };
  41025. /** This typedef is just for compatibility with old code - newer code should use the Slider::Listener class directly. */
  41026. typedef Slider::Listener SliderListener;
  41027. #if JUCE_VC6
  41028. #undef Listener
  41029. #endif
  41030. #endif // __JUCE_SLIDER_JUCEHEADER__
  41031. /*** End of inlined file: juce_Slider.h ***/
  41032. #endif
  41033. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  41034. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  41035. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  41036. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  41037. /**
  41038. A component that displays a strip of column headings for a table, and allows these
  41039. to be resized, dragged around, etc.
  41040. This is just the component that goes at the top of a table. You can use it
  41041. directly for custom components, or to create a simple table, use the
  41042. TableListBox class.
  41043. To use one of these, create it and use addColumn() to add all the columns that you need.
  41044. Each column must be given a unique ID number that's used to refer to it.
  41045. @see TableListBox, TableHeaderComponent::Listener
  41046. */
  41047. class JUCE_API TableHeaderComponent : public Component,
  41048. private AsyncUpdater
  41049. {
  41050. public:
  41051. /** Creates an empty table header.
  41052. */
  41053. TableHeaderComponent();
  41054. /** Destructor. */
  41055. ~TableHeaderComponent();
  41056. /** A combination of these flags are passed into the addColumn() method to specify
  41057. the properties of a column.
  41058. */
  41059. enum ColumnPropertyFlags
  41060. {
  41061. 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. */
  41062. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  41063. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  41064. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  41065. 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. */
  41066. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  41067. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  41068. /** This set of default flags is used as the default parameter value in addColumn(). */
  41069. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  41070. /** A quick way of combining flags for a column that's not resizable. */
  41071. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  41072. /** A quick way of combining flags for a column that's not resizable or sortable. */
  41073. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  41074. /** A quick way of combining flags for a column that's not sortable. */
  41075. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  41076. };
  41077. /** Adds a column to the table.
  41078. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  41079. registered listeners.
  41080. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  41081. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  41082. a unique ID. This is used to identify the column later on, after the user may have
  41083. changed the order that they appear in
  41084. @param width the initial width of the column, in pixels
  41085. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  41086. if the 'resizable' flag is specified for this column
  41087. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  41088. if the 'resizable' flag is specified for this column
  41089. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  41090. properties of this column
  41091. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  41092. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  41093. all columns, not just the index amongst those that are currently visible
  41094. */
  41095. void addColumn (const String& columnName,
  41096. int columnId,
  41097. int width,
  41098. int minimumWidth = 30,
  41099. int maximumWidth = -1,
  41100. int propertyFlags = defaultFlags,
  41101. int insertIndex = -1);
  41102. /** Removes a column with the given ID.
  41103. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  41104. registered listeners.
  41105. */
  41106. void removeColumn (int columnIdToRemove);
  41107. /** Deletes all columns from the table.
  41108. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  41109. registered listeners.
  41110. */
  41111. void removeAllColumns();
  41112. /** Returns the number of columns in the table.
  41113. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  41114. return the total number of columns, including hidden ones.
  41115. @see isColumnVisible
  41116. */
  41117. int getNumColumns (bool onlyCountVisibleColumns) const;
  41118. /** Returns the name for a column.
  41119. @see setColumnName
  41120. */
  41121. String getColumnName (int columnId) const;
  41122. /** Changes the name of a column. */
  41123. void setColumnName (int columnId, const String& newName);
  41124. /** Moves a column to a different index in the table.
  41125. @param columnId the column to move
  41126. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  41127. */
  41128. void moveColumn (int columnId, int newVisibleIndex);
  41129. /** Returns the width of one of the columns.
  41130. */
  41131. int getColumnWidth (int columnId) const;
  41132. /** Changes the width of a column.
  41133. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  41134. */
  41135. void setColumnWidth (int columnId, int newWidth);
  41136. /** Shows or hides a column.
  41137. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  41138. @see isColumnVisible
  41139. */
  41140. void setColumnVisible (int columnId, bool shouldBeVisible);
  41141. /** Returns true if this column is currently visible.
  41142. @see setColumnVisible
  41143. */
  41144. bool isColumnVisible (int columnId) const;
  41145. /** Changes the column which is the sort column.
  41146. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  41147. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  41148. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  41149. @see getSortColumnId, isSortedForwards, reSortTable
  41150. */
  41151. void setSortColumnId (int columnId, bool sortForwards);
  41152. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  41153. @see setSortColumnId, isSortedForwards
  41154. */
  41155. int getSortColumnId() const;
  41156. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  41157. @see setSortColumnId
  41158. */
  41159. bool isSortedForwards() const;
  41160. /** Triggers a re-sort of the table according to the current sort-column.
  41161. If you modifiy the table's contents, you can call this to signal that the table needs
  41162. to be re-sorted.
  41163. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  41164. tableSortOrderChanged() method of any listeners).
  41165. */
  41166. void reSortTable();
  41167. /** Returns the total width of all the visible columns in the table.
  41168. */
  41169. int getTotalWidth() const;
  41170. /** Returns the index of a given column.
  41171. If there's no such column ID, this will return -1.
  41172. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  41173. otherwise it'll return the index amongst all the columns, including any hidden ones.
  41174. */
  41175. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  41176. /** Returns the ID of the column at a given index.
  41177. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  41178. otherwise it'll count it amongst all the columns, including any hidden ones.
  41179. If the index is out-of-range, it'll return 0.
  41180. */
  41181. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  41182. /** Returns the rectangle containing of one of the columns.
  41183. The index is an index from 0 to the number of columns that are currently visible (hidden
  41184. ones are not counted). It returns a rectangle showing the position of the column relative
  41185. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  41186. */
  41187. const Rectangle<int> getColumnPosition (int index) const;
  41188. /** Finds the column ID at a given x-position in the component.
  41189. If there is a column at this point this returns its ID, or if not, it will return 0.
  41190. */
  41191. int getColumnIdAtX (int xToFind) const;
  41192. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  41193. entire width of the component.
  41194. By default this is disabled. Turning it on also means that when resizing a column, those
  41195. on the right will be squashed to fit.
  41196. */
  41197. void setStretchToFitActive (bool shouldStretchToFit);
  41198. /** Returns true if stretch-to-fit has been enabled.
  41199. @see setStretchToFitActive
  41200. */
  41201. bool isStretchToFitActive() const;
  41202. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  41203. specified width, keeping their relative proportions the same.
  41204. If the minimum widths of the columns are too wide to fit into this space, it may
  41205. actually end up wider.
  41206. */
  41207. void resizeAllColumnsToFit (int targetTotalWidth);
  41208. /** Enables or disables the pop-up menu.
  41209. The default menu allows the user to show or hide columns. You can add custom
  41210. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  41211. By default the menu is enabled.
  41212. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  41213. */
  41214. void setPopupMenuActive (bool hasMenu);
  41215. /** Returns true if the pop-up menu is enabled.
  41216. @see setPopupMenuActive
  41217. */
  41218. bool isPopupMenuActive() const;
  41219. /** Returns a string that encapsulates the table's current layout.
  41220. This can be restored later using restoreFromString(). It saves the order of
  41221. the columns, the currently-sorted column, and the widths.
  41222. @see restoreFromString
  41223. */
  41224. String toString() const;
  41225. /** Restores the state of the table, based on a string previously created with
  41226. toString().
  41227. @see toString
  41228. */
  41229. void restoreFromString (const String& storedVersion);
  41230. /**
  41231. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  41232. You can register one of these objects for table events using TableHeaderComponent::addListener()
  41233. and TableHeaderComponent::removeListener().
  41234. @see TableHeaderComponent
  41235. */
  41236. class JUCE_API Listener
  41237. {
  41238. public:
  41239. Listener() {}
  41240. /** Destructor. */
  41241. virtual ~Listener() {}
  41242. /** This is called when some of the table's columns are added, removed, hidden,
  41243. or rearranged.
  41244. */
  41245. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  41246. /** This is called when one or more of the table's columns are resized.
  41247. */
  41248. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  41249. /** This is called when the column by which the table should be sorted is changed.
  41250. */
  41251. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  41252. /** This is called when the user begins or ends dragging one of the columns around.
  41253. When the user starts dragging a column, this is called with the ID of that
  41254. column. When they finish dragging, it is called again with 0 as the ID.
  41255. */
  41256. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  41257. int columnIdNowBeingDragged);
  41258. };
  41259. /** Adds a listener to be informed about things that happen to the header. */
  41260. void addListener (Listener* newListener);
  41261. /** Removes a previously-registered listener. */
  41262. void removeListener (Listener* listenerToRemove);
  41263. /** This can be overridden to handle a mouse-click on one of the column headers.
  41264. The default implementation will use this click to call getSortColumnId() and
  41265. change the sort order.
  41266. */
  41267. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  41268. /** This can be overridden to add custom items to the pop-up menu.
  41269. If you override this, you should call the superclass's method to add its
  41270. column show/hide items, if you want them on the menu as well.
  41271. Then to handle the result, override reactToMenuItem().
  41272. @see reactToMenuItem
  41273. */
  41274. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  41275. /** Override this to handle any custom items that you have added to the
  41276. pop-up menu with an addMenuItems() override.
  41277. If the menuReturnId isn't one of your own custom menu items, you'll need to
  41278. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  41279. handle the items that it had added.
  41280. @see addMenuItems
  41281. */
  41282. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  41283. /** @internal */
  41284. void paint (Graphics& g);
  41285. /** @internal */
  41286. void resized();
  41287. /** @internal */
  41288. void mouseMove (const MouseEvent&);
  41289. /** @internal */
  41290. void mouseEnter (const MouseEvent&);
  41291. /** @internal */
  41292. void mouseExit (const MouseEvent&);
  41293. /** @internal */
  41294. void mouseDown (const MouseEvent&);
  41295. /** @internal */
  41296. void mouseDrag (const MouseEvent&);
  41297. /** @internal */
  41298. void mouseUp (const MouseEvent&);
  41299. /** @internal */
  41300. const MouseCursor getMouseCursor();
  41301. /** Can be overridden for more control over the pop-up menu behaviour. */
  41302. virtual void showColumnChooserMenu (int columnIdClicked);
  41303. private:
  41304. struct ColumnInfo
  41305. {
  41306. String name;
  41307. int id, propertyFlags, width, minimumWidth, maximumWidth;
  41308. double lastDeliberateWidth;
  41309. bool isVisible() const;
  41310. };
  41311. OwnedArray <ColumnInfo> columns;
  41312. Array <Listener*> listeners;
  41313. ScopedPointer <Component> dragOverlayComp;
  41314. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  41315. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  41316. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  41317. ColumnInfo* getInfoForId (int columnId) const;
  41318. int visibleIndexToTotalIndex (int visibleIndex) const;
  41319. void sendColumnsChanged();
  41320. void handleAsyncUpdate();
  41321. void beginDrag (const MouseEvent&);
  41322. void endDrag (int finalIndex);
  41323. int getResizeDraggerAt (int mouseX) const;
  41324. void updateColumnUnderMouse (int x, int y);
  41325. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  41326. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableHeaderComponent);
  41327. };
  41328. /** This typedef is just for compatibility with old code - newer code should use the TableHeaderComponent::Listener class directly. */
  41329. typedef TableHeaderComponent::Listener TableHeaderListener;
  41330. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  41331. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  41332. #endif
  41333. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  41334. /*** Start of inlined file: juce_TableListBox.h ***/
  41335. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  41336. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  41337. /**
  41338. One of these is used by a TableListBox as the data model for the table's contents.
  41339. The virtual methods that you override in this class take care of drawing the
  41340. table cells, and reacting to events.
  41341. @see TableListBox
  41342. */
  41343. class JUCE_API TableListBoxModel
  41344. {
  41345. public:
  41346. TableListBoxModel() {}
  41347. /** Destructor. */
  41348. virtual ~TableListBoxModel() {}
  41349. /** This must return the number of rows currently in the table.
  41350. If the number of rows changes, you must call TableListBox::updateContent() to
  41351. cause it to refresh the list.
  41352. */
  41353. virtual int getNumRows() = 0;
  41354. /** This must draw the background behind one of the rows in the table.
  41355. The graphics context has its origin at the row's top-left, and your method
  41356. should fill the area specified by the width and height parameters.
  41357. */
  41358. virtual void paintRowBackground (Graphics& g,
  41359. int rowNumber,
  41360. int width, int height,
  41361. bool rowIsSelected) = 0;
  41362. /** This must draw one of the cells.
  41363. The graphics context's origin will already be set to the top-left of the cell,
  41364. whose size is specified by (width, height).
  41365. */
  41366. virtual void paintCell (Graphics& g,
  41367. int rowNumber,
  41368. int columnId,
  41369. int width, int height,
  41370. bool rowIsSelected) = 0;
  41371. /** This is used to create or update a custom component to go in a cell.
  41372. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  41373. and handle mouse clicks with cellClicked().
  41374. This method will be called whenever a custom component might need to be updated - e.g.
  41375. when the table is changed, or TableListBox::updateContent() is called.
  41376. If you don't need a custom component for the specified cell, then return 0.
  41377. If you do want a custom component, and the existingComponentToUpdate is null, then
  41378. this method must create a new component suitable for the cell, and return it.
  41379. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  41380. by this method. In this case, the method must either update it to make sure it's correctly representing
  41381. the given cell (which may be different from the one that the component was created for), or it can
  41382. delete this component and return a new one.
  41383. */
  41384. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  41385. Component* existingComponentToUpdate);
  41386. /** This callback is made when the user clicks on one of the cells in the table.
  41387. The mouse event's coordinates will be relative to the entire table row.
  41388. @see cellDoubleClicked, backgroundClicked
  41389. */
  41390. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  41391. /** This callback is made when the user clicks on one of the cells in the table.
  41392. The mouse event's coordinates will be relative to the entire table row.
  41393. @see cellClicked, backgroundClicked
  41394. */
  41395. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  41396. /** This can be overridden to react to the user double-clicking on a part of the list where
  41397. there are no rows.
  41398. @see cellClicked
  41399. */
  41400. virtual void backgroundClicked();
  41401. /** This callback is made when the table's sort order is changed.
  41402. This could be because the user has clicked a column header, or because the
  41403. TableHeaderComponent::setSortColumnId() method was called.
  41404. If you implement this, your method should re-sort the table using the given
  41405. column as the key.
  41406. */
  41407. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  41408. /** Returns the best width for one of the columns.
  41409. If you implement this method, you should measure the width of all the items
  41410. in this column, and return the best size.
  41411. Returning 0 means that the column shouldn't be changed.
  41412. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  41413. */
  41414. virtual int getColumnAutoSizeWidth (int columnId);
  41415. /** Returns a tooltip for a particular cell in the table.
  41416. */
  41417. virtual const String getCellTooltip (int rowNumber, int columnId);
  41418. /** Override this to be informed when rows are selected or deselected.
  41419. @see ListBox::selectedRowsChanged()
  41420. */
  41421. virtual void selectedRowsChanged (int lastRowSelected);
  41422. /** Override this to be informed when the delete key is pressed.
  41423. @see ListBox::deleteKeyPressed()
  41424. */
  41425. virtual void deleteKeyPressed (int lastRowSelected);
  41426. /** Override this to be informed when the return key is pressed.
  41427. @see ListBox::returnKeyPressed()
  41428. */
  41429. virtual void returnKeyPressed (int lastRowSelected);
  41430. /** Override this to be informed when the list is scrolled.
  41431. This might be caused by the user moving the scrollbar, or by programmatic changes
  41432. to the list position.
  41433. */
  41434. virtual void listWasScrolled();
  41435. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  41436. If this returns a non-null variant then when the user drags a row, the table will try to
  41437. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  41438. drag-and-drop operation, using this string as the source description, and the listbox
  41439. itself as the source component.
  41440. @see getDragSourceCustomData, DragAndDropContainer::startDragging
  41441. */
  41442. virtual const var getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  41443. };
  41444. /**
  41445. A table of cells, using a TableHeaderComponent as its header.
  41446. This component makes it easy to create a table by providing a TableListBoxModel as
  41447. the data source.
  41448. @see TableListBoxModel, TableHeaderComponent
  41449. */
  41450. class JUCE_API TableListBox : public ListBox,
  41451. private ListBoxModel,
  41452. private TableHeaderComponent::Listener
  41453. {
  41454. public:
  41455. /** Creates a TableListBox.
  41456. The model pointer passed-in can be null, in which case you can set it later
  41457. with setModel().
  41458. */
  41459. TableListBox (const String& componentName = String::empty,
  41460. TableListBoxModel* model = 0);
  41461. /** Destructor. */
  41462. ~TableListBox();
  41463. /** Changes the TableListBoxModel that is being used for this table.
  41464. */
  41465. void setModel (TableListBoxModel* newModel);
  41466. /** Returns the model currently in use. */
  41467. TableListBoxModel* getModel() const { return model; }
  41468. /** Returns the header component being used in this table. */
  41469. TableHeaderComponent& getHeader() const { return *header; }
  41470. /** Sets the header component to use for the table.
  41471. The table will take ownership of the component that you pass in, and will delete it
  41472. when it's no longer needed.
  41473. */
  41474. void setHeader (TableHeaderComponent* newHeader);
  41475. /** Changes the height of the table header component.
  41476. @see getHeaderHeight
  41477. */
  41478. void setHeaderHeight (int newHeight);
  41479. /** Returns the height of the table header.
  41480. @see setHeaderHeight
  41481. */
  41482. int getHeaderHeight() const;
  41483. /** Resizes a column to fit its contents.
  41484. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  41485. and applies that to the column.
  41486. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  41487. */
  41488. void autoSizeColumn (int columnId);
  41489. /** Calls autoSizeColumn() for all columns in the table. */
  41490. void autoSizeAllColumns();
  41491. /** Enables or disables the auto size options on the popup menu.
  41492. By default, these are enabled.
  41493. */
  41494. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  41495. /** True if the auto-size options should be shown on the menu.
  41496. @see setAutoSizeMenuOptionsShown
  41497. */
  41498. bool isAutoSizeMenuOptionShown() const;
  41499. /** Returns the position of one of the cells in the table.
  41500. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  41501. the table component's top-left. The row number isn't checked to see if it's
  41502. in-range, but the column ID must exist or this will return an empty rectangle.
  41503. If relativeToComponentTopLeft is false, the co-ords are relative to the
  41504. top-left of the table's top-left cell.
  41505. */
  41506. const Rectangle<int> getCellPosition (int columnId, int rowNumber,
  41507. bool relativeToComponentTopLeft) const;
  41508. /** Returns the component that currently represents a given cell.
  41509. If the component for this cell is off-screen or if the position is out-of-range,
  41510. this may return 0.
  41511. @see getCellPosition
  41512. */
  41513. Component* getCellComponent (int columnId, int rowNumber) const;
  41514. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  41515. @see ListBox::scrollToEnsureRowIsOnscreen
  41516. */
  41517. void scrollToEnsureColumnIsOnscreen (int columnId);
  41518. /** @internal */
  41519. int getNumRows();
  41520. /** @internal */
  41521. void paintListBoxItem (int, Graphics&, int, int, bool);
  41522. /** @internal */
  41523. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  41524. /** @internal */
  41525. void selectedRowsChanged (int lastRowSelected);
  41526. /** @internal */
  41527. void deleteKeyPressed (int currentSelectedRow);
  41528. /** @internal */
  41529. void returnKeyPressed (int currentSelectedRow);
  41530. /** @internal */
  41531. void backgroundClicked();
  41532. /** @internal */
  41533. void listWasScrolled();
  41534. /** @internal */
  41535. void tableColumnsChanged (TableHeaderComponent*);
  41536. /** @internal */
  41537. void tableColumnsResized (TableHeaderComponent*);
  41538. /** @internal */
  41539. void tableSortOrderChanged (TableHeaderComponent*);
  41540. /** @internal */
  41541. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  41542. /** @internal */
  41543. void resized();
  41544. private:
  41545. TableHeaderComponent* header;
  41546. TableListBoxModel* model;
  41547. int columnIdNowBeingDragged;
  41548. bool autoSizeOptionsShown;
  41549. void updateColumnComponents() const;
  41550. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBox);
  41551. };
  41552. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  41553. /*** End of inlined file: juce_TableListBox.h ***/
  41554. #endif
  41555. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  41556. #endif
  41557. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  41558. #endif
  41559. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  41560. #endif
  41561. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41562. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  41563. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41564. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41565. /**
  41566. A factory object which can create ToolbarItemComponent objects.
  41567. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  41568. that it can create.
  41569. Each type of item is identified by a unique ID, and multiple instances of an
  41570. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  41571. bars).
  41572. @see Toolbar, ToolbarItemComponent, ToolbarButton
  41573. */
  41574. class JUCE_API ToolbarItemFactory
  41575. {
  41576. public:
  41577. ToolbarItemFactory();
  41578. /** Destructor. */
  41579. virtual ~ToolbarItemFactory();
  41580. /** A set of reserved item ID values, used for the built-in item types.
  41581. */
  41582. enum SpecialItemIds
  41583. {
  41584. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  41585. can be placed between sets of items to break them into groups. */
  41586. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  41587. items.*/
  41588. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  41589. either side of it, filling any available space. */
  41590. };
  41591. /** Must return a list of the IDs for all the item types that this factory can create.
  41592. The ids should be added to the array that is passed-in.
  41593. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  41594. and the predefined IDs in the SpecialItemIds enum.
  41595. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  41596. to this list if you want your toolbar to be able to contain those items.
  41597. The list returned here is used by the ToolbarItemPalette class to obtain its list
  41598. of available items, and their order on the palette will reflect the order in which
  41599. they appear on this list.
  41600. @see ToolbarItemPalette
  41601. */
  41602. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  41603. /** Must return the set of items that should be added to a toolbar as its default set.
  41604. This method is used by Toolbar::addDefaultItems() to determine which items to
  41605. create.
  41606. The items that your method adds to the array that is passed-in will be added to the
  41607. toolbar in the same order. Items can appear in the list more than once.
  41608. */
  41609. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  41610. /** Must create an instance of one of the items that the factory lists in its
  41611. getAllToolbarItemIds() method.
  41612. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  41613. method, except for the built-in item types from the SpecialItemIds enum, which
  41614. are created internally by the toolbar code.
  41615. Try not to keep a pointer to the object that is returned, as it will be deleted
  41616. automatically by the toolbar, and remember that multiple instances of the same
  41617. item type are likely to exist at the same time.
  41618. */
  41619. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  41620. };
  41621. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  41622. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  41623. #endif
  41624. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41625. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  41626. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41627. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41628. /**
  41629. A component containing a list of toolbar items, which the user can drag onto
  41630. a toolbar to add them.
  41631. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  41632. which automatically shows one of these in a dialog box with lots of extra controls.
  41633. @see Toolbar
  41634. */
  41635. class JUCE_API ToolbarItemPalette : public Component,
  41636. public DragAndDropContainer
  41637. {
  41638. public:
  41639. /** Creates a palette of items for a given factory, with the aim of adding them
  41640. to the specified toolbar.
  41641. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  41642. set of items that are shown in this palette.
  41643. The toolbar and factory must not be deleted while this object exists.
  41644. */
  41645. ToolbarItemPalette (ToolbarItemFactory& factory,
  41646. Toolbar* toolbar);
  41647. /** Destructor. */
  41648. ~ToolbarItemPalette();
  41649. /** @internal */
  41650. void resized();
  41651. private:
  41652. ToolbarItemFactory& factory;
  41653. Toolbar* toolbar;
  41654. Viewport viewport;
  41655. OwnedArray <ToolbarItemComponent> items;
  41656. friend class Toolbar;
  41657. void replaceComponent (ToolbarItemComponent* comp);
  41658. void addComponent (int itemId, int index);
  41659. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemPalette);
  41660. };
  41661. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  41662. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  41663. #endif
  41664. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  41665. /*** Start of inlined file: juce_TreeView.h ***/
  41666. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  41667. #define __JUCE_TREEVIEW_JUCEHEADER__
  41668. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  41669. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41670. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41671. /**
  41672. Components derived from this class can have files dropped onto them by an external application.
  41673. @see DragAndDropContainer
  41674. */
  41675. class JUCE_API FileDragAndDropTarget
  41676. {
  41677. public:
  41678. /** Destructor. */
  41679. virtual ~FileDragAndDropTarget() {}
  41680. /** Callback to check whether this target is interested in the set of files being offered.
  41681. Note that this will be called repeatedly when the user is dragging the mouse around over your
  41682. component, so don't do anything time-consuming in here, like opening the files to have a look
  41683. inside them!
  41684. @param files the set of (absolute) pathnames of the files that the user is dragging
  41685. @returns true if this component wants to receive the other callbacks regarging this
  41686. type of object; if it returns false, no other callbacks will be made.
  41687. */
  41688. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  41689. /** Callback to indicate that some files are being dragged over this component.
  41690. This gets called when the user moves the mouse into this component while dragging.
  41691. Use this callback as a trigger to make your component repaint itself to give the
  41692. user feedback about whether the files can be dropped here or not.
  41693. @param files the set of (absolute) pathnames of the files that the user is dragging
  41694. @param x the mouse x position, relative to this component
  41695. @param y the mouse y position, relative to this component
  41696. */
  41697. virtual void fileDragEnter (const StringArray& files, int x, int y);
  41698. /** Callback to indicate that the user is dragging some files over this component.
  41699. This gets called when the user moves the mouse over this component while dragging.
  41700. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  41701. this lets you know what happens in-between.
  41702. @param files the set of (absolute) pathnames of the files that the user is dragging
  41703. @param x the mouse x position, relative to this component
  41704. @param y the mouse y position, relative to this component
  41705. */
  41706. virtual void fileDragMove (const StringArray& files, int x, int y);
  41707. /** Callback to indicate that the mouse has moved away from this component.
  41708. This gets called when the user moves the mouse out of this component while dragging
  41709. the files.
  41710. If you've used fileDragEnter() to repaint your component and give feedback, use this
  41711. as a signal to repaint it in its normal state.
  41712. @param files the set of (absolute) pathnames of the files that the user is dragging
  41713. */
  41714. virtual void fileDragExit (const StringArray& files);
  41715. /** Callback to indicate that the user has dropped the files onto this component.
  41716. When the user drops the files, this get called, and you can use the files in whatever
  41717. way is appropriate.
  41718. Note that after this is called, the fileDragExit method may not be called, so you should
  41719. clean up in here if there's anything you need to do when the drag finishes.
  41720. @param files the set of (absolute) pathnames of the files that the user is dragging
  41721. @param x the mouse x position, relative to this component
  41722. @param y the mouse y position, relative to this component
  41723. */
  41724. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  41725. };
  41726. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  41727. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  41728. class TreeView;
  41729. /**
  41730. An item in a treeview.
  41731. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  41732. own sub-items.
  41733. To implement an item that contains sub-items, override the itemOpennessChanged()
  41734. method so that when it is opened, it adds the new sub-items to itself using the
  41735. addSubItem method. Depending on the nature of the item it might choose to only
  41736. do this the first time it's opened, or it might want to refresh itself each time.
  41737. It also has the option of deleting its sub-items when it is closed, or leaving them
  41738. in place.
  41739. */
  41740. class JUCE_API TreeViewItem
  41741. {
  41742. public:
  41743. /** Constructor. */
  41744. TreeViewItem();
  41745. /** Destructor. */
  41746. virtual ~TreeViewItem();
  41747. /** Returns the number of sub-items that have been added to this item.
  41748. Note that this doesn't mean much if the node isn't open.
  41749. @see getSubItem, mightContainSubItems, addSubItem
  41750. */
  41751. int getNumSubItems() const noexcept;
  41752. /** Returns one of the item's sub-items.
  41753. Remember that the object returned might get deleted at any time when its parent
  41754. item is closed or refreshed, depending on the nature of the items you're using.
  41755. @see getNumSubItems
  41756. */
  41757. TreeViewItem* getSubItem (int index) const noexcept;
  41758. /** Removes any sub-items. */
  41759. void clearSubItems();
  41760. /** Adds a sub-item.
  41761. @param newItem the object to add to the item's sub-item list. Once added, these can be
  41762. found using getSubItem(). When the items are later removed with
  41763. removeSubItem() (or when this item is deleted), they will be deleted.
  41764. @param insertPosition the index which the new item should have when it's added. If this
  41765. value is less than 0, the item will be added to the end of the list.
  41766. */
  41767. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  41768. /** Removes one of the sub-items.
  41769. @param index the item to remove
  41770. @param deleteItem if true, the item that is removed will also be deleted.
  41771. */
  41772. void removeSubItem (int index, bool deleteItem = true);
  41773. /** Returns the TreeView to which this item belongs. */
  41774. TreeView* getOwnerView() const noexcept { return ownerView; }
  41775. /** Returns the item within which this item is contained. */
  41776. TreeViewItem* getParentItem() const noexcept { return parentItem; }
  41777. /** True if this item is currently open in the treeview. */
  41778. bool isOpen() const noexcept;
  41779. /** Opens or closes the item.
  41780. When opened or closed, the item's itemOpennessChanged() method will be called,
  41781. and a subclass should use this callback to create and add any sub-items that
  41782. it needs to.
  41783. @see itemOpennessChanged, mightContainSubItems
  41784. */
  41785. void setOpen (bool shouldBeOpen);
  41786. /** True if this item is currently selected.
  41787. Use this when painting the node, to decide whether to draw it as selected or not.
  41788. */
  41789. bool isSelected() const noexcept;
  41790. /** Selects or deselects the item.
  41791. This will cause a callback to itemSelectionChanged()
  41792. */
  41793. void setSelected (bool shouldBeSelected,
  41794. bool deselectOtherItemsFirst);
  41795. /** Returns the rectangle that this item occupies.
  41796. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  41797. top-left of the TreeView comp, so this will depend on the scroll-position of
  41798. the tree. If false, it is relative to the top-left of the topmost item in the
  41799. tree (so this would be unaffected by scrolling the view).
  41800. */
  41801. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const noexcept;
  41802. /** Sends a signal to the treeview to make it refresh itself.
  41803. Call this if your items have changed and you want the tree to update to reflect
  41804. this.
  41805. */
  41806. void treeHasChanged() const noexcept;
  41807. /** Sends a repaint message to redraw just this item.
  41808. Note that you should only call this if you want to repaint a superficial change. If
  41809. you're altering the tree's nodes, you should instead call treeHasChanged().
  41810. */
  41811. void repaintItem() const;
  41812. /** Returns the row number of this item in the tree.
  41813. The row number of an item will change according to which items are open.
  41814. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  41815. */
  41816. int getRowNumberInTree() const noexcept;
  41817. /** Returns true if all the item's parent nodes are open.
  41818. This is useful to check whether the item might actually be visible or not.
  41819. */
  41820. bool areAllParentsOpen() const noexcept;
  41821. /** Changes whether lines are drawn to connect any sub-items to this item.
  41822. By default, line-drawing is turned on.
  41823. */
  41824. void setLinesDrawnForSubItems (bool shouldDrawLines) noexcept;
  41825. /** Tells the tree whether this item can potentially be opened.
  41826. If your item could contain sub-items, this should return true; if it returns
  41827. false then the tree will not try to open the item. This determines whether or
  41828. not the item will be drawn with a 'plus' button next to it.
  41829. */
  41830. virtual bool mightContainSubItems() = 0;
  41831. /** Returns a string to uniquely identify this item.
  41832. If you're planning on using the TreeView::getOpennessState() method, then
  41833. these strings will be used to identify which nodes are open. The string
  41834. should be unique amongst the item's sibling items, but it's ok for there
  41835. to be duplicates at other levels of the tree.
  41836. If you're not going to store the state, then it's ok not to bother implementing
  41837. this method.
  41838. */
  41839. virtual const String getUniqueName() const;
  41840. /** Called when an item is opened or closed.
  41841. When setOpen() is called and the item has specified that it might
  41842. have sub-items with the mightContainSubItems() method, this method
  41843. is called to let the item create or manage its sub-items.
  41844. So when this is called with isNowOpen set to true (i.e. when the item is being
  41845. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  41846. refresh its sub-item list.
  41847. When this is called with isNowOpen set to false, the subclass might want
  41848. to use clearSubItems() to save on space, or it might choose to leave them,
  41849. depending on the nature of the tree.
  41850. You could also use this callback as a trigger to start a background process
  41851. which asynchronously creates sub-items and adds them, if that's more
  41852. appropriate for the task in hand.
  41853. @see mightContainSubItems
  41854. */
  41855. virtual void itemOpennessChanged (bool isNowOpen);
  41856. /** Must return the width required by this item.
  41857. If your item needs to have a particular width in pixels, return that value; if
  41858. you'd rather have it just fill whatever space is available in the treeview,
  41859. return -1.
  41860. If all your items return -1, no horizontal scrollbar will be shown, but if any
  41861. items have fixed widths and extend beyond the width of the treeview, a
  41862. scrollbar will appear.
  41863. Each item can be a different width, but if they change width, you should call
  41864. treeHasChanged() to update the tree.
  41865. */
  41866. virtual int getItemWidth() const { return -1; }
  41867. /** Must return the height required by this item.
  41868. This is the height in pixels that the item will take up. Items in the tree
  41869. can be different heights, but if they change height, you should call
  41870. treeHasChanged() to update the tree.
  41871. */
  41872. virtual int getItemHeight() const { return 20; }
  41873. /** You can override this method to return false if you don't want to allow the
  41874. user to select this item.
  41875. */
  41876. virtual bool canBeSelected() const { return true; }
  41877. /** Creates a component that will be used to represent this item.
  41878. You don't have to implement this method - if it returns 0 then no component
  41879. will be used for the item, and you can just draw it using the paintItem()
  41880. callback. But if you do return a component, it will be positioned in the
  41881. treeview so that it can be used to represent this item.
  41882. The component returned will be managed by the treeview, so always return
  41883. a new component, and don't keep a reference to it, as the treeview will
  41884. delete it later when it goes off the screen or is no longer needed. Also
  41885. bear in mind that if the component keeps a reference to the item that
  41886. created it, that item could be deleted before the component. Its position
  41887. and size will be completely managed by the tree, so don't attempt to move it
  41888. around.
  41889. Something you may want to do with your component is to give it a pointer to
  41890. the TreeView that created it. This is perfectly safe, and there's no danger
  41891. of it becoming a dangling pointer because the TreeView will always delete
  41892. the component before it is itself deleted.
  41893. As long as you stick to these rules you can return whatever kind of
  41894. component you like. It's most useful if you're doing things like drag-and-drop
  41895. of items, or want to use a Label component to edit item names, etc.
  41896. */
  41897. virtual Component* createItemComponent() { return nullptr; }
  41898. /** Draws the item's contents.
  41899. You can choose to either implement this method and draw each item, or you
  41900. can use createItemComponent() to create a component that will represent the
  41901. item.
  41902. If all you need in your tree is to be able to draw the items and detect when
  41903. the user selects or double-clicks one of them, it's probably enough to
  41904. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  41905. complicated interactions, you may need to use createItemComponent() instead.
  41906. @param g the graphics context to draw into
  41907. @param width the width of the area available for drawing
  41908. @param height the height of the area available for drawing
  41909. */
  41910. virtual void paintItem (Graphics& g, int width, int height);
  41911. /** Draws the item's open/close button.
  41912. If you don't implement this method, the default behaviour is to
  41913. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  41914. it for custom effects.
  41915. */
  41916. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  41917. /** Called when the user clicks on this item.
  41918. If you're using createItemComponent() to create a custom component for the
  41919. item, the mouse-clicks might not make it through to the treeview, but this
  41920. is how you find out about clicks when just drawing each item individually.
  41921. The associated mouse-event details are passed in, so you can find out about
  41922. which button, where it was, etc.
  41923. @see itemDoubleClicked
  41924. */
  41925. virtual void itemClicked (const MouseEvent& e);
  41926. /** Called when the user double-clicks on this item.
  41927. If you're using createItemComponent() to create a custom component for the
  41928. item, the mouse-clicks might not make it through to the treeview, but this
  41929. is how you find out about clicks when just drawing each item individually.
  41930. The associated mouse-event details are passed in, so you can find out about
  41931. which button, where it was, etc.
  41932. If not overridden, the base class method here will open or close the item as
  41933. if the 'plus' button had been clicked.
  41934. @see itemClicked
  41935. */
  41936. virtual void itemDoubleClicked (const MouseEvent& e);
  41937. /** Called when the item is selected or deselected.
  41938. Use this if you want to do something special when the item's selectedness
  41939. changes. By default it'll get repainted when this happens.
  41940. */
  41941. virtual void itemSelectionChanged (bool isNowSelected);
  41942. /** The item can return a tool tip string here if it wants to.
  41943. @see TooltipClient
  41944. */
  41945. virtual const String getTooltip();
  41946. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  41947. If this returns a non-null variant then when the user drags an item, the treeview will
  41948. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  41949. a drag-and-drop operation, using this string as the source description, with the treeview
  41950. itself as the source component.
  41951. If you need more complex drag-and-drop behaviour, you can use custom components for
  41952. the items, and use those to trigger the drag.
  41953. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  41954. isInterestedInFileDrag(), etc.
  41955. @see DragAndDropContainer::startDragging
  41956. */
  41957. virtual const var getDragSourceDescription();
  41958. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  41959. method and return true.
  41960. If you return true and allow some files to be dropped, you'll also need to implement the
  41961. filesDropped() method to do something with them.
  41962. Note that this will be called often, so make your implementation very quick! There's
  41963. certainly no time to try opening the files and having a think about what's inside them!
  41964. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  41965. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  41966. */
  41967. virtual bool isInterestedInFileDrag (const StringArray& files);
  41968. /** When files are dropped into this item, this callback is invoked.
  41969. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  41970. The insertIndex value indicates where in the list of sub-items the files were dropped.
  41971. If files are dropped onto an area of the tree where there are no visible items, this
  41972. method is called on the root item of the tree, with an insert index of 0.
  41973. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  41974. */
  41975. virtual void filesDropped (const StringArray& files, int insertIndex);
  41976. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  41977. If you implement this method, you'll also need to implement itemDropped() in order to handle
  41978. the items when they are dropped.
  41979. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  41980. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  41981. */
  41982. virtual bool isInterestedInDragSource (const DragAndDropTarget::SourceDetails& dragSourceDetails);
  41983. /** When a things are dropped into this item, this callback is invoked.
  41984. For this to work, you need to have also implemented isInterestedInDragSource().
  41985. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  41986. If files are dropped onto an area of the tree where there are no visible items, this
  41987. method is called on the root item of the tree, with an insert index of 0.
  41988. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  41989. */
  41990. virtual void itemDropped (const DragAndDropTarget::SourceDetails& dragSourceDetails, int insertIndex);
  41991. /** Sets a flag to indicate that the item wants to be allowed
  41992. to draw all the way across to the left edge of the treeview.
  41993. By default this is false, which means that when the paintItem()
  41994. method is called, its graphics context is clipped to only allow
  41995. drawing within the item's rectangle. If this flag is set to true,
  41996. then the graphics context isn't clipped on its left side, so it
  41997. can draw all the way across to the left margin. Note that the
  41998. context will still have its origin in the same place though, so
  41999. the coordinates of anything to its left will be negative. It's
  42000. mostly useful if you want to draw a wider bar behind the
  42001. highlighted item.
  42002. */
  42003. void setDrawsInLeftMargin (bool canDrawInLeftMargin) noexcept;
  42004. /** Saves the current state of open/closed nodes so it can be restored later.
  42005. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  42006. and records it as XML. To identify node objects it uses the
  42007. TreeViewItem::getUniqueName() method to create named paths. This
  42008. means that the same state of open/closed nodes can be restored to a
  42009. completely different instance of the tree, as long as it contains nodes
  42010. whose unique names are the same.
  42011. You'd normally want to use TreeView::getOpennessState() rather than call it
  42012. for a specific item, but this can be handy if you need to briefly save the state
  42013. for a section of the tree.
  42014. The caller is responsible for deleting the object that is returned.
  42015. @see TreeView::getOpennessState, restoreOpennessState
  42016. */
  42017. XmlElement* getOpennessState() const noexcept;
  42018. /** Restores the openness of this item and all its sub-items from a saved state.
  42019. See TreeView::restoreOpennessState for more details.
  42020. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  42021. for a specific item, but this can be handy if you need to briefly save the state
  42022. for a section of the tree.
  42023. @see TreeView::restoreOpennessState, getOpennessState
  42024. */
  42025. void restoreOpennessState (const XmlElement& xml) noexcept;
  42026. /** Returns the index of this item in its parent's sub-items. */
  42027. int getIndexInParent() const noexcept;
  42028. /** Returns true if this item is the last of its parent's sub-itens. */
  42029. bool isLastOfSiblings() const noexcept;
  42030. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  42031. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  42032. The string takes the form of a path, constructed from the getUniqueName() of this
  42033. item and all its parents, so these must all be correctly implemented for it to work.
  42034. @see TreeView::findItemFromIdentifierString, getUniqueName
  42035. */
  42036. String getItemIdentifierString() const;
  42037. /**
  42038. This handy class takes a copy of a TreeViewItem's openness when you create it,
  42039. and restores that openness state when its destructor is called.
  42040. This can very handy when you're refreshing sub-items - e.g.
  42041. @code
  42042. void MyTreeViewItem::updateChildItems()
  42043. {
  42044. OpennessRestorer openness (*this); // saves the openness state here..
  42045. clearSubItems();
  42046. // add a bunch of sub-items here which may or may not be the same as the ones that
  42047. // were previously there
  42048. addSubItem (...
  42049. // ..and at this point, the old openness is restored, so any items that haven't
  42050. // changed will have their old openness retained.
  42051. }
  42052. @endcode
  42053. */
  42054. class OpennessRestorer
  42055. {
  42056. public:
  42057. OpennessRestorer (TreeViewItem& treeViewItem);
  42058. ~OpennessRestorer();
  42059. private:
  42060. TreeViewItem& treeViewItem;
  42061. ScopedPointer <XmlElement> oldOpenness;
  42062. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpennessRestorer);
  42063. };
  42064. private:
  42065. TreeView* ownerView;
  42066. TreeViewItem* parentItem;
  42067. OwnedArray <TreeViewItem> subItems;
  42068. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  42069. int uid;
  42070. bool selected : 1;
  42071. bool redrawNeeded : 1;
  42072. bool drawLinesInside : 1;
  42073. bool drawsInLeftMargin : 1;
  42074. unsigned int openness : 2;
  42075. friend class TreeView;
  42076. friend class TreeViewContentComponent;
  42077. void updatePositions (int newY);
  42078. int getIndentX() const noexcept;
  42079. void setOwnerView (TreeView*) noexcept;
  42080. void paintRecursively (Graphics&, int width);
  42081. TreeViewItem* getTopLevelItem() noexcept;
  42082. TreeViewItem* findItemRecursively (int y) noexcept;
  42083. TreeViewItem* getDeepestOpenParentItem() noexcept;
  42084. int getNumRows() const noexcept;
  42085. TreeViewItem* getItemOnRow (int index) noexcept;
  42086. void deselectAllRecursively();
  42087. int countSelectedItemsRecursively (int depth) const noexcept;
  42088. TreeViewItem* getSelectedItemWithIndex (int index) noexcept;
  42089. TreeViewItem* getNextVisibleItem (bool recurse) const noexcept;
  42090. TreeViewItem* findItemFromIdentifierString (const String&);
  42091. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  42092. // The parameters for these methods have changed - please update your code!
  42093. virtual void isInterestedInDragSource (const String&, Component*) {}
  42094. virtual int itemDropped (const String&, Component*, int) { return 0; }
  42095. #endif
  42096. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewItem);
  42097. };
  42098. /**
  42099. A tree-view component.
  42100. Use one of these to hold and display a structure of TreeViewItem objects.
  42101. */
  42102. class JUCE_API TreeView : public Component,
  42103. public SettableTooltipClient,
  42104. public FileDragAndDropTarget,
  42105. public DragAndDropTarget,
  42106. private AsyncUpdater
  42107. {
  42108. public:
  42109. /** Creates an empty treeview.
  42110. Once you've got a treeview component, you'll need to give it something to
  42111. display, using the setRootItem() method.
  42112. */
  42113. TreeView (const String& componentName = String::empty);
  42114. /** Destructor. */
  42115. ~TreeView();
  42116. /** Sets the item that is displayed in the treeview.
  42117. A tree has a single root item which contains as many sub-items as it needs. If
  42118. you want the tree to contain a number of root items, you should still use a single
  42119. root item above these, but hide it using setRootItemVisible().
  42120. You can pass in 0 to this method to clear the tree and remove its current root item.
  42121. The object passed in will not be deleted by the treeview, it's up to the caller
  42122. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  42123. this item until you've removed it from the tree, either by calling setRootItem (nullptr),
  42124. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  42125. to delete it.
  42126. */
  42127. void setRootItem (TreeViewItem* newRootItem);
  42128. /** Returns the tree's root item.
  42129. This will be the last object passed to setRootItem(), or 0 if none has been set.
  42130. */
  42131. TreeViewItem* getRootItem() const noexcept { return rootItem; }
  42132. /** This will remove and delete the current root item.
  42133. It's a convenient way of deleting the item and calling setRootItem (nullptr).
  42134. */
  42135. void deleteRootItem();
  42136. /** Changes whether the tree's root item is shown or not.
  42137. If the root item is hidden, only its sub-items will be shown in the treeview - this
  42138. lets you make the tree look as if it's got many root items. If it's hidden, this call
  42139. will also make sure the root item is open (otherwise the treeview would look empty).
  42140. */
  42141. void setRootItemVisible (bool shouldBeVisible);
  42142. /** Returns true if the root item is visible.
  42143. @see setRootItemVisible
  42144. */
  42145. bool isRootItemVisible() const noexcept { return rootItemVisible; }
  42146. /** Sets whether items are open or closed by default.
  42147. Normally, items are closed until the user opens them, but you can use this
  42148. to make them default to being open until explicitly closed.
  42149. @see areItemsOpenByDefault
  42150. */
  42151. void setDefaultOpenness (bool isOpenByDefault);
  42152. /** Returns true if the tree's items default to being open.
  42153. @see setDefaultOpenness
  42154. */
  42155. bool areItemsOpenByDefault() const noexcept { return defaultOpenness; }
  42156. /** This sets a flag to indicate that the tree can be used for multi-selection.
  42157. You can always select multiple items internally by calling the
  42158. TreeViewItem::setSelected() method, but this flag indicates whether the user
  42159. is allowed to multi-select by clicking on the tree.
  42160. By default it is disabled.
  42161. @see isMultiSelectEnabled
  42162. */
  42163. void setMultiSelectEnabled (bool canMultiSelect);
  42164. /** Returns whether multi-select has been enabled for the tree.
  42165. @see setMultiSelectEnabled
  42166. */
  42167. bool isMultiSelectEnabled() const noexcept { return multiSelectEnabled; }
  42168. /** Sets a flag to indicate whether to hide the open/close buttons.
  42169. @see areOpenCloseButtonsVisible
  42170. */
  42171. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  42172. /** Returns whether open/close buttons are shown.
  42173. @see setOpenCloseButtonsVisible
  42174. */
  42175. bool areOpenCloseButtonsVisible() const noexcept { return openCloseButtonsVisible; }
  42176. /** Deselects any items that are currently selected. */
  42177. void clearSelectedItems();
  42178. /** Returns the number of items that are currently selected.
  42179. If maximumDepthToSearchTo is >= 0, it lets you specify a maximum depth to which the
  42180. tree will be recursed.
  42181. @see getSelectedItem, clearSelectedItems
  42182. */
  42183. int getNumSelectedItems (int maximumDepthToSearchTo = -1) const noexcept;
  42184. /** Returns one of the selected items in the tree.
  42185. @param index the index, 0 to (getNumSelectedItems() - 1)
  42186. */
  42187. TreeViewItem* getSelectedItem (int index) const noexcept;
  42188. /** Returns the number of rows the tree is using.
  42189. This will depend on which items are open.
  42190. @see TreeViewItem::getRowNumberInTree()
  42191. */
  42192. int getNumRowsInTree() const;
  42193. /** Returns the item on a particular row of the tree.
  42194. If the index is out of range, this will return 0.
  42195. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  42196. */
  42197. TreeViewItem* getItemOnRow (int index) const;
  42198. /** Returns the item that contains a given y position.
  42199. The y is relative to the top of the TreeView component.
  42200. */
  42201. TreeViewItem* getItemAt (int yPosition) const noexcept;
  42202. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  42203. void scrollToKeepItemVisible (TreeViewItem* item);
  42204. /** Returns the treeview's Viewport object. */
  42205. Viewport* getViewport() const noexcept;
  42206. /** Returns the number of pixels by which each nested level of the tree is indented.
  42207. @see setIndentSize
  42208. */
  42209. int getIndentSize() const noexcept { return indentSize; }
  42210. /** Changes the distance by which each nested level of the tree is indented.
  42211. @see getIndentSize
  42212. */
  42213. void setIndentSize (int newIndentSize);
  42214. /** Searches the tree for an item with the specified identifier.
  42215. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  42216. If no such item exists, this will return false. If the item is found, all of its items
  42217. will be automatically opened.
  42218. */
  42219. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  42220. /** Saves the current state of open/closed nodes so it can be restored later.
  42221. This takes a snapshot of which nodes have been explicitly opened or closed,
  42222. and records it as XML. To identify node objects it uses the
  42223. TreeViewItem::getUniqueName() method to create named paths. This
  42224. means that the same state of open/closed nodes can be restored to a
  42225. completely different instance of the tree, as long as it contains nodes
  42226. whose unique names are the same.
  42227. The caller is responsible for deleting the object that is returned.
  42228. @param alsoIncludeScrollPosition if this is true, the state will also
  42229. include information about where the
  42230. tree has been scrolled to vertically,
  42231. so this can also be restored
  42232. @see restoreOpennessState
  42233. */
  42234. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  42235. /** Restores a previously saved arrangement of open/closed nodes.
  42236. This will try to restore a snapshot of the tree's state that was created by
  42237. the getOpennessState() method. If any of the nodes named in the original
  42238. XML aren't present in this tree, they will be ignored.
  42239. If restoreStoredSelection is true, it will also try to re-select any items that
  42240. were selected in the stored state.
  42241. @see getOpennessState
  42242. */
  42243. void restoreOpennessState (const XmlElement& newState,
  42244. bool restoreStoredSelection);
  42245. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  42246. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42247. methods.
  42248. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42249. */
  42250. enum ColourIds
  42251. {
  42252. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  42253. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  42254. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  42255. };
  42256. /** @internal */
  42257. void paint (Graphics& g);
  42258. /** @internal */
  42259. void resized();
  42260. /** @internal */
  42261. bool keyPressed (const KeyPress& key);
  42262. /** @internal */
  42263. void colourChanged();
  42264. /** @internal */
  42265. void enablementChanged();
  42266. /** @internal */
  42267. bool isInterestedInFileDrag (const StringArray& files);
  42268. /** @internal */
  42269. void fileDragEnter (const StringArray& files, int x, int y);
  42270. /** @internal */
  42271. void fileDragMove (const StringArray& files, int x, int y);
  42272. /** @internal */
  42273. void fileDragExit (const StringArray& files);
  42274. /** @internal */
  42275. void filesDropped (const StringArray& files, int x, int y);
  42276. /** @internal */
  42277. bool isInterestedInDragSource (const SourceDetails&);
  42278. /** @internal */
  42279. void itemDragEnter (const SourceDetails&);
  42280. /** @internal */
  42281. void itemDragMove (const SourceDetails&);
  42282. /** @internal */
  42283. void itemDragExit (const SourceDetails&);
  42284. /** @internal */
  42285. void itemDropped (const SourceDetails&);
  42286. private:
  42287. friend class TreeViewItem;
  42288. friend class TreeViewContentComponent;
  42289. class TreeViewport;
  42290. class InsertPointHighlight;
  42291. class TargetGroupHighlight;
  42292. friend class ScopedPointer<TreeViewport>;
  42293. friend class ScopedPointer<InsertPointHighlight>;
  42294. friend class ScopedPointer<TargetGroupHighlight>;
  42295. ScopedPointer<TreeViewport> viewport;
  42296. CriticalSection nodeAlterationLock;
  42297. TreeViewItem* rootItem;
  42298. ScopedPointer<InsertPointHighlight> dragInsertPointHighlight;
  42299. ScopedPointer<TargetGroupHighlight> dragTargetGroupHighlight;
  42300. int indentSize;
  42301. bool defaultOpenness : 1;
  42302. bool needsRecalculating : 1;
  42303. bool rootItemVisible : 1;
  42304. bool multiSelectEnabled : 1;
  42305. bool openCloseButtonsVisible : 1;
  42306. void itemsChanged() noexcept;
  42307. void handleAsyncUpdate();
  42308. void moveSelectedRow (int delta);
  42309. void updateButtonUnderMouse (const MouseEvent& e);
  42310. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) noexcept;
  42311. void hideDragHighlight() noexcept;
  42312. void handleDrag (const StringArray& files, const SourceDetails&);
  42313. void handleDrop (const StringArray& files, const SourceDetails&);
  42314. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  42315. const StringArray& files, const SourceDetails&) const noexcept;
  42316. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeView);
  42317. };
  42318. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  42319. /*** End of inlined file: juce_TreeView.h ***/
  42320. #endif
  42321. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  42322. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  42323. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  42324. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  42325. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  42326. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  42327. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  42328. /*** Start of inlined file: juce_FileFilter.h ***/
  42329. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  42330. #define __JUCE_FILEFILTER_JUCEHEADER__
  42331. /**
  42332. Interface for deciding which files are suitable for something.
  42333. For example, this is used by DirectoryContentsList to select which files
  42334. go into the list.
  42335. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  42336. */
  42337. class JUCE_API FileFilter
  42338. {
  42339. public:
  42340. /** Creates a filter with the given description.
  42341. The description can be returned later with the getDescription() method.
  42342. */
  42343. FileFilter (const String& filterDescription);
  42344. /** Destructor. */
  42345. virtual ~FileFilter();
  42346. /** Returns the description that the filter was created with. */
  42347. const String& getDescription() const noexcept;
  42348. /** Should return true if this file is suitable for inclusion in whatever context
  42349. the object is being used.
  42350. */
  42351. virtual bool isFileSuitable (const File& file) const = 0;
  42352. /** Should return true if this directory is suitable for inclusion in whatever context
  42353. the object is being used.
  42354. */
  42355. virtual bool isDirectorySuitable (const File& file) const = 0;
  42356. protected:
  42357. String description;
  42358. };
  42359. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  42360. /*** End of inlined file: juce_FileFilter.h ***/
  42361. /**
  42362. A class to asynchronously scan for details about the files in a directory.
  42363. This keeps a list of files and some information about them, using a background
  42364. thread to scan for more files. As files are found, it broadcasts change messages
  42365. to tell any listeners.
  42366. @see FileListComponent, FileBrowserComponent
  42367. */
  42368. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  42369. public TimeSliceClient
  42370. {
  42371. public:
  42372. /** Creates a directory list.
  42373. To set the directory it should point to, use setDirectory(), which will
  42374. also start it scanning for files on the background thread.
  42375. When the background thread finds and adds new files to this list, the
  42376. ChangeBroadcaster class will send a change message, so you can register
  42377. listeners and update them when the list changes.
  42378. @param fileFilter an optional filter to select which files are
  42379. included in the list. If this is 0, then all files
  42380. and directories are included. Make sure that the
  42381. filter doesn't get deleted during the lifetime of this
  42382. object
  42383. @param threadToUse a thread object that this list can use
  42384. to scan for files as a background task. Make sure
  42385. that the thread you give it has been started, or you
  42386. won't get any files!
  42387. */
  42388. DirectoryContentsList (const FileFilter* fileFilter,
  42389. TimeSliceThread& threadToUse);
  42390. /** Destructor. */
  42391. ~DirectoryContentsList();
  42392. /** Sets the directory to look in for files.
  42393. If the directory that's passed in is different to the current one, this will
  42394. also start the background thread scanning it for files.
  42395. */
  42396. void setDirectory (const File& directory,
  42397. bool includeDirectories,
  42398. bool includeFiles);
  42399. /** Returns the directory that's currently being used. */
  42400. const File& getDirectory() const;
  42401. /** Clears the list, and stops the thread scanning for files. */
  42402. void clear();
  42403. /** Clears the list and restarts scanning the directory for files. */
  42404. void refresh();
  42405. /** True if the background thread hasn't yet finished scanning for files. */
  42406. bool isStillLoading() const;
  42407. /** Tells the list whether or not to ignore hidden files.
  42408. By default these are ignored.
  42409. */
  42410. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  42411. /** Returns true if hidden files are ignored.
  42412. @see setIgnoresHiddenFiles
  42413. */
  42414. bool ignoresHiddenFiles() const;
  42415. /** Contains cached information about one of the files in a DirectoryContentsList.
  42416. */
  42417. struct FileInfo
  42418. {
  42419. /** The filename.
  42420. This isn't a full pathname, it's just the last part of the path, same as you'd
  42421. get from File::getFileName().
  42422. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  42423. */
  42424. String filename;
  42425. /** File size in bytes. */
  42426. int64 fileSize;
  42427. /** File modification time.
  42428. As supplied by File::getLastModificationTime().
  42429. */
  42430. Time modificationTime;
  42431. /** File creation time.
  42432. As supplied by File::getCreationTime().
  42433. */
  42434. Time creationTime;
  42435. /** True if the file is a directory. */
  42436. bool isDirectory;
  42437. /** True if the file is read-only. */
  42438. bool isReadOnly;
  42439. };
  42440. /** Returns the number of files currently available in the list.
  42441. The info about one of these files can be retrieved with getFileInfo() or
  42442. getFile().
  42443. Obviously as the background thread runs and scans the directory for files, this
  42444. number will change.
  42445. @see getFileInfo, getFile
  42446. */
  42447. int getNumFiles() const;
  42448. /** Returns the cached information about one of the files in the list.
  42449. If the index is in-range, this will return true and will copy the file's details
  42450. to the structure that is passed-in.
  42451. If it returns false, then the index wasn't in range, and the structure won't
  42452. be affected.
  42453. @see getNumFiles, getFile
  42454. */
  42455. bool getFileInfo (int index, FileInfo& resultInfo) const;
  42456. /** Returns one of the files in the list.
  42457. @param index should be less than getNumFiles(). If this is out-of-range, the
  42458. return value will be File::nonexistent
  42459. @see getNumFiles, getFileInfo
  42460. */
  42461. File getFile (int index) const;
  42462. /** Returns the file filter being used.
  42463. The filter is specified in the constructor.
  42464. */
  42465. const FileFilter* getFilter() const { return fileFilter; }
  42466. /** @internal */
  42467. int useTimeSlice();
  42468. /** @internal */
  42469. TimeSliceThread& getTimeSliceThread() { return thread; }
  42470. /** @internal */
  42471. static int compareElements (const DirectoryContentsList::FileInfo* first,
  42472. const DirectoryContentsList::FileInfo* second);
  42473. private:
  42474. File root;
  42475. const FileFilter* fileFilter;
  42476. TimeSliceThread& thread;
  42477. int fileTypeFlags;
  42478. CriticalSection fileListLock;
  42479. OwnedArray <FileInfo> files;
  42480. ScopedPointer <DirectoryIterator> fileFindHandle;
  42481. bool volatile shouldStop;
  42482. void changed();
  42483. bool checkNextFile (bool& hasChanged);
  42484. bool addFile (const File& file, bool isDir,
  42485. const int64 fileSize, const Time& modTime,
  42486. const Time& creationTime, bool isReadOnly);
  42487. void setTypeFlags (int newFlags);
  42488. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsList);
  42489. };
  42490. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  42491. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  42492. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  42493. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  42494. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  42495. /**
  42496. A listener for user selection events in a file browser.
  42497. This is used by a FileBrowserComponent or FileListComponent.
  42498. */
  42499. class JUCE_API FileBrowserListener
  42500. {
  42501. public:
  42502. /** Destructor. */
  42503. virtual ~FileBrowserListener();
  42504. /** Callback when the user selects a different file in the browser. */
  42505. virtual void selectionChanged() = 0;
  42506. /** Callback when the user clicks on a file in the browser. */
  42507. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  42508. /** Callback when the user double-clicks on a file in the browser. */
  42509. virtual void fileDoubleClicked (const File& file) = 0;
  42510. };
  42511. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  42512. /*** End of inlined file: juce_FileBrowserListener.h ***/
  42513. /**
  42514. A base class for components that display a list of the files in a directory.
  42515. @see DirectoryContentsList
  42516. */
  42517. class JUCE_API DirectoryContentsDisplayComponent
  42518. {
  42519. public:
  42520. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  42521. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  42522. /** Destructor. */
  42523. virtual ~DirectoryContentsDisplayComponent();
  42524. /** Returns the number of files the user has got selected.
  42525. @see getSelectedFile
  42526. */
  42527. virtual int getNumSelectedFiles() const = 0;
  42528. /** Returns one of the files that the user has currently selected.
  42529. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  42530. @see getNumSelectedFiles
  42531. */
  42532. virtual const File getSelectedFile (int index) const = 0;
  42533. /** Deselects any selected files. */
  42534. virtual void deselectAllFiles() = 0;
  42535. /** Scrolls this view to the top. */
  42536. virtual void scrollToTop() = 0;
  42537. /** Adds a listener to be told when files are selected or clicked.
  42538. @see removeListener
  42539. */
  42540. void addListener (FileBrowserListener* listener);
  42541. /** Removes a listener.
  42542. @see addListener
  42543. */
  42544. void removeListener (FileBrowserListener* listener);
  42545. /** A set of colour IDs to use to change the colour of various aspects of the list.
  42546. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42547. methods.
  42548. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42549. */
  42550. enum ColourIds
  42551. {
  42552. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  42553. textColourId = 0x1000541, /**< The colour for the text. */
  42554. };
  42555. /** @internal */
  42556. void sendSelectionChangeMessage();
  42557. /** @internal */
  42558. void sendDoubleClickMessage (const File& file);
  42559. /** @internal */
  42560. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  42561. protected:
  42562. DirectoryContentsList& fileList;
  42563. ListenerList <FileBrowserListener> listeners;
  42564. private:
  42565. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsDisplayComponent);
  42566. };
  42567. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  42568. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  42569. #endif
  42570. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  42571. #endif
  42572. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42573. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  42574. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42575. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42576. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  42577. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  42578. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  42579. /**
  42580. Base class for components that live inside a file chooser dialog box and
  42581. show previews of the files that get selected.
  42582. One of these allows special extra information to be displayed for files
  42583. in a dialog box as the user selects them. Each time the current file or
  42584. directory is changed, the selectedFileChanged() method will be called
  42585. to allow it to update itself appropriately.
  42586. @see FileChooser, ImagePreviewComponent
  42587. */
  42588. class JUCE_API FilePreviewComponent : public Component
  42589. {
  42590. public:
  42591. /** Creates a FilePreviewComponent. */
  42592. FilePreviewComponent();
  42593. /** Destructor. */
  42594. ~FilePreviewComponent();
  42595. /** Called to indicate that the user's currently selected file has changed.
  42596. @param newSelectedFile the newly selected file or directory, which may be
  42597. File::nonexistent if none is selected.
  42598. */
  42599. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  42600. private:
  42601. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilePreviewComponent);
  42602. };
  42603. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  42604. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  42605. /**
  42606. A component for browsing and selecting a file or directory to open or save.
  42607. This contains a FileListComponent and adds various boxes and controls for
  42608. navigating and selecting a file. It can work in different modes so that it can
  42609. be used for loading or saving a file, or for choosing a directory.
  42610. @see FileChooserDialogBox, FileChooser, FileListComponent
  42611. */
  42612. class JUCE_API FileBrowserComponent : public Component,
  42613. public ChangeBroadcaster,
  42614. private FileBrowserListener,
  42615. private TextEditorListener,
  42616. private ButtonListener,
  42617. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  42618. private FileFilter
  42619. {
  42620. public:
  42621. /** Various options for the browser.
  42622. A combination of these is passed into the FileBrowserComponent constructor.
  42623. */
  42624. enum FileChooserFlags
  42625. {
  42626. openMode = 1, /**< specifies that the component should allow the user to
  42627. choose an existing file with the intention of opening it. */
  42628. saveMode = 2, /**< specifies that the component should allow the user to specify
  42629. the name of a file that will be used to save something. */
  42630. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  42631. conjunction with canSelectDirectories). */
  42632. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  42633. conjuction with canSelectFiles). */
  42634. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  42635. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  42636. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  42637. };
  42638. /** Creates a FileBrowserComponent.
  42639. @param flags A combination of flags from the FileChooserFlags enumeration,
  42640. used to specify the component's behaviour. The flags must contain
  42641. either openMode or saveMode, and canSelectFiles and/or
  42642. canSelectDirectories.
  42643. @param initialFileOrDirectory The file or directory that should be selected when
  42644. the component begins. If this is File::nonexistent,
  42645. a default directory will be chosen.
  42646. @param fileFilter an optional filter to use to determine which files
  42647. are shown. If this is 0 then all files are displayed. Note
  42648. that a pointer is kept internally to this object, so
  42649. make sure that it is not deleted before the browser object
  42650. is deleted.
  42651. @param previewComp an optional preview component that will be used to
  42652. show previews of files that the user selects
  42653. */
  42654. FileBrowserComponent (int flags,
  42655. const File& initialFileOrDirectory,
  42656. const FileFilter* fileFilter,
  42657. FilePreviewComponent* previewComp);
  42658. /** Destructor. */
  42659. ~FileBrowserComponent();
  42660. /** Returns the number of files that the user has got selected.
  42661. If multiple select isn't active, this will only be 0 or 1. To get the complete
  42662. list of files they've chosen, pass an index to getCurrentFile().
  42663. */
  42664. int getNumSelectedFiles() const noexcept;
  42665. /** Returns one of the files that the user has chosen.
  42666. If the box has multi-select enabled, the index lets you specify which of the files
  42667. to get - see getNumSelectedFiles() to find out how many files were chosen.
  42668. @see getHighlightedFile
  42669. */
  42670. File getSelectedFile (int index) const noexcept;
  42671. /** Deselects any files that are currently selected.
  42672. */
  42673. void deselectAllFiles();
  42674. /** Returns true if the currently selected file(s) are usable.
  42675. This can be used to decide whether the user can press "ok" for the
  42676. current file. What it does depends on the mode, so for example in an "open"
  42677. mode, this only returns true if a file has been selected and if it exists.
  42678. In a "save" mode, a non-existent file would also be valid.
  42679. */
  42680. bool currentFileIsValid() const;
  42681. /** This returns the last item in the view that the user has highlighted.
  42682. This may be different from getCurrentFile(), which returns the value
  42683. that is shown in the filename box, and if there are multiple selections,
  42684. this will only return one of them.
  42685. @see getSelectedFile
  42686. */
  42687. File getHighlightedFile() const noexcept;
  42688. /** Returns the directory whose contents are currently being shown in the listbox. */
  42689. const File& getRoot() const;
  42690. /** Changes the directory that's being shown in the listbox. */
  42691. void setRoot (const File& newRootDirectory);
  42692. /** Equivalent to pressing the "up" button to browse the parent directory. */
  42693. void goUp();
  42694. /** Refreshes the directory that's currently being listed. */
  42695. void refresh();
  42696. /** Changes the filter that's being used to sift the files. */
  42697. void setFileFilter (const FileFilter* newFileFilter);
  42698. /** Returns a verb to describe what should happen when the file is accepted.
  42699. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  42700. mode, it'll be "Save", etc.
  42701. */
  42702. virtual const String getActionVerb() const;
  42703. /** Returns true if the saveMode flag was set when this component was created.
  42704. */
  42705. bool isSaveMode() const noexcept;
  42706. /** Adds a listener to be told when the user selects and clicks on files.
  42707. @see removeListener
  42708. */
  42709. void addListener (FileBrowserListener* listener);
  42710. /** Removes a listener.
  42711. @see addListener
  42712. */
  42713. void removeListener (FileBrowserListener* listener);
  42714. /** @internal */
  42715. void resized();
  42716. /** @internal */
  42717. void buttonClicked (Button* b);
  42718. /** @internal */
  42719. void comboBoxChanged (ComboBox*);
  42720. /** @internal */
  42721. void textEditorTextChanged (TextEditor& editor);
  42722. /** @internal */
  42723. void textEditorReturnKeyPressed (TextEditor& editor);
  42724. /** @internal */
  42725. void textEditorEscapeKeyPressed (TextEditor& editor);
  42726. /** @internal */
  42727. void textEditorFocusLost (TextEditor& editor);
  42728. /** @internal */
  42729. bool keyPressed (const KeyPress& key);
  42730. /** @internal */
  42731. void selectionChanged();
  42732. /** @internal */
  42733. void fileClicked (const File& f, const MouseEvent& e);
  42734. /** @internal */
  42735. void fileDoubleClicked (const File& f);
  42736. /** @internal */
  42737. bool isFileSuitable (const File& file) const;
  42738. /** @internal */
  42739. bool isDirectorySuitable (const File&) const;
  42740. /** @internal */
  42741. FilePreviewComponent* getPreviewComponent() const noexcept;
  42742. protected:
  42743. /** Returns a list of names and paths for the default places the user might want to look.
  42744. Use an empty string to indicate a section break.
  42745. */
  42746. virtual void getRoots (StringArray& rootNames, StringArray& rootPaths);
  42747. /** Updates the items in the dropdown list of recent paths with the values from getRoots(). */
  42748. void resetRecentPaths();
  42749. private:
  42750. ScopedPointer <DirectoryContentsList> fileList;
  42751. const FileFilter* fileFilter;
  42752. int flags;
  42753. File currentRoot;
  42754. Array<File> chosenFiles;
  42755. ListenerList <FileBrowserListener> listeners;
  42756. ScopedPointer<DirectoryContentsDisplayComponent> fileListComponent;
  42757. FilePreviewComponent* previewComp;
  42758. ComboBox currentPathBox;
  42759. TextEditor filenameBox;
  42760. Label fileLabel;
  42761. ScopedPointer<Button> goUpButton;
  42762. TimeSliceThread thread;
  42763. void sendListenerChangeMessage();
  42764. bool isFileOrDirSuitable (const File& f) const;
  42765. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBrowserComponent);
  42766. };
  42767. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  42768. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  42769. #endif
  42770. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  42771. #endif
  42772. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  42773. /*** Start of inlined file: juce_FileChooser.h ***/
  42774. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  42775. #define __JUCE_FILECHOOSER_JUCEHEADER__
  42776. /**
  42777. Creates a dialog box to choose a file or directory to load or save.
  42778. To use a FileChooser:
  42779. - create one (as a local stack variable is the neatest way)
  42780. - call one of its browseFor.. methods
  42781. - if this returns true, the user has selected a file, so you can retrieve it
  42782. with the getResult() method.
  42783. e.g. @code
  42784. void loadMooseFile()
  42785. {
  42786. FileChooser myChooser ("Please select the moose you want to load...",
  42787. File::getSpecialLocation (File::userHomeDirectory),
  42788. "*.moose");
  42789. if (myChooser.browseForFileToOpen())
  42790. {
  42791. File mooseFile (myChooser.getResult());
  42792. loadMoose (mooseFile);
  42793. }
  42794. }
  42795. @endcode
  42796. */
  42797. class JUCE_API FileChooser
  42798. {
  42799. public:
  42800. /** Creates a FileChooser.
  42801. After creating one of these, use one of the browseFor... methods to display it.
  42802. @param dialogBoxTitle a text string to display in the dialog box to
  42803. tell the user what's going on
  42804. @param initialFileOrDirectory the file or directory that should be selected when
  42805. the dialog box opens. If this parameter is set to
  42806. File::nonexistent, a sensible default directory
  42807. will be used instead.
  42808. @param filePatternsAllowed a set of file patterns to specify which files can be
  42809. selected - each pattern should be separated by a
  42810. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  42811. empty string means that all files are allowed
  42812. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  42813. possible; if false, then a Juce-based browser dialog
  42814. box will always be used
  42815. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  42816. */
  42817. FileChooser (const String& dialogBoxTitle,
  42818. const File& initialFileOrDirectory = File::nonexistent,
  42819. const String& filePatternsAllowed = String::empty,
  42820. bool useOSNativeDialogBox = true);
  42821. /** Destructor. */
  42822. ~FileChooser();
  42823. /** Shows a dialog box to choose a file to open.
  42824. This will display the dialog box modally, using an "open file" mode, so that
  42825. it won't allow non-existent files or directories to be chosen.
  42826. @param previewComponent an optional component to display inside the dialog
  42827. box to show special info about the files that the user
  42828. is browsing. The component will not be deleted by this
  42829. object, so the caller must take care of it.
  42830. @returns true if the user selected a file, in which case, use the getResult()
  42831. method to find out what it was. Returns false if they cancelled instead.
  42832. @see browseForFileToSave, browseForDirectory
  42833. */
  42834. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  42835. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  42836. The files that are returned can be obtained by calling getResults(). See
  42837. browseForFileToOpen() for more info about the behaviour of this method.
  42838. */
  42839. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  42840. /** Shows a dialog box to choose a file to save.
  42841. This will display the dialog box modally, using an "save file" mode, so it
  42842. will allow non-existent files to be chosen, but not directories.
  42843. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  42844. the user if they're sure they want to overwrite a file that already
  42845. exists
  42846. @returns true if the user chose a file and pressed 'ok', in which case, use
  42847. the getResult() method to find out what the file was. Returns false
  42848. if they cancelled instead.
  42849. @see browseForFileToOpen, browseForDirectory
  42850. */
  42851. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  42852. /** Shows a dialog box to choose a directory.
  42853. This will display the dialog box modally, using an "open directory" mode, so it
  42854. will only allow directories to be returned, not files.
  42855. @returns true if the user chose a directory and pressed 'ok', in which case, use
  42856. the getResult() method to find out what they chose. Returns false
  42857. if they cancelled instead.
  42858. @see browseForFileToOpen, browseForFileToSave
  42859. */
  42860. bool browseForDirectory();
  42861. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  42862. The files that are returned can be obtained by calling getResults(). See
  42863. browseForFileToOpen() for more info about the behaviour of this method.
  42864. */
  42865. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  42866. /** Returns the last file that was chosen by one of the browseFor methods.
  42867. After calling the appropriate browseFor... method, this method lets you
  42868. find out what file or directory they chose.
  42869. Note that the file returned is only valid if the browse method returned true (i.e.
  42870. if the user pressed 'ok' rather than cancelling).
  42871. If you're using a multiple-file select, then use the getResults() method instead,
  42872. to obtain the list of all files chosen.
  42873. @see getResults
  42874. */
  42875. File getResult() const;
  42876. /** Returns a list of all the files that were chosen during the last call to a
  42877. browse method.
  42878. This array may be empty if no files were chosen, or can contain multiple entries
  42879. if multiple files were chosen.
  42880. @see getResult
  42881. */
  42882. const Array<File>& getResults() const;
  42883. private:
  42884. String title, filters;
  42885. File startingFile;
  42886. Array<File> results;
  42887. bool useNativeDialogBox;
  42888. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  42889. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  42890. FilePreviewComponent* previewComponent);
  42891. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  42892. const String& filters, bool selectsDirectories, bool selectsFiles,
  42893. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  42894. FilePreviewComponent* previewComponent);
  42895. JUCE_LEAK_DETECTOR (FileChooser);
  42896. };
  42897. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  42898. /*** End of inlined file: juce_FileChooser.h ***/
  42899. #endif
  42900. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42901. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  42902. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42903. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42904. /*** Start of inlined file: juce_ResizableWindow.h ***/
  42905. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42906. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42907. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  42908. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42909. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42910. /*** Start of inlined file: juce_DropShadower.h ***/
  42911. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  42912. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  42913. /**
  42914. Adds a drop-shadow to a component.
  42915. This object creates and manages a set of components which sit around a
  42916. component, creating a gaussian shadow around it. The components will track
  42917. the position of the component and if it's brought to the front they'll also
  42918. follow this.
  42919. For desktop windows you don't need to use this class directly - just
  42920. set the Component::windowHasDropShadow flag when calling
  42921. Component::addToDesktop(), and the system will create one of these if it's
  42922. needed (which it obviously isn't on the Mac, for example).
  42923. */
  42924. class JUCE_API DropShadower : public ComponentListener
  42925. {
  42926. public:
  42927. /** Creates a DropShadower.
  42928. @param alpha the opacity of the shadows, from 0 to 1.0
  42929. @param xOffset the horizontal displacement of the shadow, in pixels
  42930. @param yOffset the vertical displacement of the shadow, in pixels
  42931. @param blurRadius the radius of the blur to use for creating the shadow
  42932. */
  42933. DropShadower (float alpha = 0.5f,
  42934. int xOffset = 1,
  42935. int yOffset = 5,
  42936. float blurRadius = 10.0f);
  42937. /** Destructor. */
  42938. virtual ~DropShadower();
  42939. /** Attaches the DropShadower to the component you want to shadow. */
  42940. void setOwner (Component* componentToFollow);
  42941. /** @internal */
  42942. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  42943. /** @internal */
  42944. void componentBroughtToFront (Component& component);
  42945. /** @internal */
  42946. void componentParentHierarchyChanged (Component& component);
  42947. /** @internal */
  42948. void componentVisibilityChanged (Component& component);
  42949. private:
  42950. Component* owner;
  42951. OwnedArray<Component> shadowWindows;
  42952. Image shadowImageSections[12];
  42953. const int xOffset, yOffset;
  42954. const float alpha, blurRadius;
  42955. bool reentrant;
  42956. void updateShadows();
  42957. void setShadowImage (const Image& src, int num, int w, int h, int sx, int sy);
  42958. void bringShadowWindowsToFront();
  42959. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DropShadower);
  42960. };
  42961. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  42962. /*** End of inlined file: juce_DropShadower.h ***/
  42963. /**
  42964. A base class for top-level windows.
  42965. This class is used for components that are considered a major part of your
  42966. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  42967. etc. Things like menus that pop up briefly aren't derived from it.
  42968. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  42969. could itself be the child of another component.
  42970. The class manages a list of all instances of top-level windows that are in use,
  42971. and each one is also given the concept of being "active". The active window is
  42972. one that is actively being used by the user. This isn't quite the same as the
  42973. component with the keyboard focus, because there may be a popup menu or other
  42974. temporary window which gets keyboard focus while the active top level window is
  42975. unchanged.
  42976. A top-level window also has an optional drop-shadow.
  42977. @see ResizableWindow, DocumentWindow, DialogWindow
  42978. */
  42979. class JUCE_API TopLevelWindow : public Component
  42980. {
  42981. public:
  42982. /** Creates a TopLevelWindow.
  42983. @param name the name to give the component
  42984. @param addToDesktop if true, the window will be automatically added to the
  42985. desktop; if false, you can use it as a child component
  42986. */
  42987. TopLevelWindow (const String& name, bool addToDesktop);
  42988. /** Destructor. */
  42989. ~TopLevelWindow();
  42990. /** True if this is currently the TopLevelWindow that is actively being used.
  42991. This isn't quite the same as having keyboard focus, because the focus may be
  42992. on a child component or a temporary pop-up menu, etc, while this window is
  42993. still considered to be active.
  42994. @see activeWindowStatusChanged
  42995. */
  42996. bool isActiveWindow() const noexcept { return windowIsActive_; }
  42997. /** This will set the bounds of the window so that it's centred in front of another
  42998. window.
  42999. If your app has a few windows open and want to pop up a dialog box for one of
  43000. them, you can use this to show it in front of the relevent parent window, which
  43001. is a bit neater than just having it appear in the middle of the screen.
  43002. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  43003. be used instead. If no window is focused, it'll just default to the middle of the
  43004. screen.
  43005. */
  43006. void centreAroundComponent (Component* componentToCentreAround,
  43007. int width, int height);
  43008. /** Turns the drop-shadow on and off. */
  43009. void setDropShadowEnabled (bool useShadow);
  43010. /** Sets whether an OS-native title bar will be used, or a Juce one.
  43011. @see isUsingNativeTitleBar
  43012. */
  43013. void setUsingNativeTitleBar (bool useNativeTitleBar);
  43014. /** Returns true if the window is currently using an OS-native title bar.
  43015. @see setUsingNativeTitleBar
  43016. */
  43017. bool isUsingNativeTitleBar() const noexcept { return useNativeTitleBar && isOnDesktop(); }
  43018. /** Returns the number of TopLevelWindow objects currently in use.
  43019. @see getTopLevelWindow
  43020. */
  43021. static int getNumTopLevelWindows() noexcept;
  43022. /** Returns one of the TopLevelWindow objects currently in use.
  43023. The index is 0 to (getNumTopLevelWindows() - 1).
  43024. */
  43025. static TopLevelWindow* getTopLevelWindow (int index) noexcept;
  43026. /** Returns the currently-active top level window.
  43027. There might not be one, of course, so this can return 0.
  43028. */
  43029. static TopLevelWindow* getActiveTopLevelWindow() noexcept;
  43030. /** @internal */
  43031. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = nullptr);
  43032. protected:
  43033. /** This callback happens when this window becomes active or inactive.
  43034. @see isActiveWindow
  43035. */
  43036. virtual void activeWindowStatusChanged();
  43037. /** @internal */
  43038. void focusOfChildComponentChanged (FocusChangeType cause);
  43039. /** @internal */
  43040. void parentHierarchyChanged();
  43041. /** @internal */
  43042. virtual int getDesktopWindowStyleFlags() const;
  43043. /** @internal */
  43044. void recreateDesktopWindow();
  43045. /** @internal */
  43046. void visibilityChanged();
  43047. private:
  43048. friend class TopLevelWindowManager;
  43049. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  43050. ScopedPointer <DropShadower> shadower;
  43051. void setWindowActive (bool isNowActive);
  43052. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TopLevelWindow);
  43053. };
  43054. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  43055. /*** End of inlined file: juce_TopLevelWindow.h ***/
  43056. /*** Start of inlined file: juce_ComponentDragger.h ***/
  43057. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  43058. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  43059. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  43060. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  43061. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  43062. /**
  43063. A class that imposes restrictions on a Component's size or position.
  43064. This is used by classes such as ResizableCornerComponent,
  43065. ResizableBorderComponent and ResizableWindow.
  43066. The base class can impose some basic size and position limits, but you can
  43067. also subclass this for custom uses.
  43068. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  43069. */
  43070. class JUCE_API ComponentBoundsConstrainer
  43071. {
  43072. public:
  43073. /** When first created, the object will not impose any restrictions on the components. */
  43074. ComponentBoundsConstrainer() noexcept;
  43075. /** Destructor. */
  43076. virtual ~ComponentBoundsConstrainer();
  43077. /** Imposes a minimum width limit. */
  43078. void setMinimumWidth (int minimumWidth) noexcept;
  43079. /** Returns the current minimum width. */
  43080. int getMinimumWidth() const noexcept { return minW; }
  43081. /** Imposes a maximum width limit. */
  43082. void setMaximumWidth (int maximumWidth) noexcept;
  43083. /** Returns the current maximum width. */
  43084. int getMaximumWidth() const noexcept { return maxW; }
  43085. /** Imposes a minimum height limit. */
  43086. void setMinimumHeight (int minimumHeight) noexcept;
  43087. /** Returns the current minimum height. */
  43088. int getMinimumHeight() const noexcept { return minH; }
  43089. /** Imposes a maximum height limit. */
  43090. void setMaximumHeight (int maximumHeight) noexcept;
  43091. /** Returns the current maximum height. */
  43092. int getMaximumHeight() const noexcept { return maxH; }
  43093. /** Imposes a minimum width and height limit. */
  43094. void setMinimumSize (int minimumWidth,
  43095. int minimumHeight) noexcept;
  43096. /** Imposes a maximum width and height limit. */
  43097. void setMaximumSize (int maximumWidth,
  43098. int maximumHeight) noexcept;
  43099. /** Set all the maximum and minimum dimensions. */
  43100. void setSizeLimits (int minimumWidth,
  43101. int minimumHeight,
  43102. int maximumWidth,
  43103. int maximumHeight) noexcept;
  43104. /** Sets the amount by which the component is allowed to go off-screen.
  43105. The values indicate how many pixels must remain on-screen when dragged off
  43106. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  43107. when the component goes off the top of the screen, its y-position will be
  43108. clipped so that there are always at least 10 pixels on-screen. In other words,
  43109. the lowest y-position it can take would be (10 - the component's height).
  43110. If you pass 0 or less for one of these amounts, the component is allowed
  43111. to move beyond that edge completely, with no restrictions at all.
  43112. If you pass a very large number (i.e. larger that the dimensions of the
  43113. component itself), then the component won't be allowed to overlap that
  43114. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  43115. the component will bump into the left side of the screen and go no further.
  43116. */
  43117. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  43118. int minimumWhenOffTheLeft,
  43119. int minimumWhenOffTheBottom,
  43120. int minimumWhenOffTheRight) noexcept;
  43121. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  43122. int getMinimumWhenOffTheTop() const noexcept { return minOffTop; }
  43123. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  43124. int getMinimumWhenOffTheLeft() const noexcept { return minOffLeft; }
  43125. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  43126. int getMinimumWhenOffTheBottom() const noexcept { return minOffBottom; }
  43127. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  43128. int getMinimumWhenOffTheRight() const noexcept { return minOffRight; }
  43129. /** Specifies a width-to-height ratio that the resizer should always maintain.
  43130. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  43131. will always be maintained as this multiple of the height.
  43132. @see setResizeLimits
  43133. */
  43134. void setFixedAspectRatio (double widthOverHeight) noexcept;
  43135. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  43136. If no aspect ratio is being enforced, this will return 0.
  43137. */
  43138. double getFixedAspectRatio() const noexcept;
  43139. /** This callback changes the given co-ordinates to impose whatever the current
  43140. constraints are set to be.
  43141. @param bounds the target position that should be examined and adjusted
  43142. @param previousBounds the component's current size
  43143. @param limits the region in which the component can be positioned
  43144. @param isStretchingTop whether the top edge of the component is being resized
  43145. @param isStretchingLeft whether the left edge of the component is being resized
  43146. @param isStretchingBottom whether the bottom edge of the component is being resized
  43147. @param isStretchingRight whether the right edge of the component is being resized
  43148. */
  43149. virtual void checkBounds (Rectangle<int>& bounds,
  43150. const Rectangle<int>& previousBounds,
  43151. const Rectangle<int>& limits,
  43152. bool isStretchingTop,
  43153. bool isStretchingLeft,
  43154. bool isStretchingBottom,
  43155. bool isStretchingRight);
  43156. /** This callback happens when the resizer is about to start dragging. */
  43157. virtual void resizeStart();
  43158. /** This callback happens when the resizer has finished dragging. */
  43159. virtual void resizeEnd();
  43160. /** Checks the given bounds, and then sets the component to the corrected size. */
  43161. void setBoundsForComponent (Component* component,
  43162. const Rectangle<int>& bounds,
  43163. bool isStretchingTop,
  43164. bool isStretchingLeft,
  43165. bool isStretchingBottom,
  43166. bool isStretchingRight);
  43167. /** Performs a check on the current size of a component, and moves or resizes
  43168. it if it fails the constraints.
  43169. */
  43170. void checkComponentBounds (Component* component);
  43171. /** Called by setBoundsForComponent() to apply a new constrained size to a
  43172. component.
  43173. By default this just calls setBounds(), but it virtual in case it's needed for
  43174. extremely cunning purposes.
  43175. */
  43176. virtual void applyBoundsToComponent (Component* component,
  43177. const Rectangle<int>& bounds);
  43178. private:
  43179. int minW, maxW, minH, maxH;
  43180. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  43181. double aspectRatio;
  43182. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBoundsConstrainer);
  43183. };
  43184. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  43185. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  43186. /**
  43187. An object to take care of the logic for dragging components around with the mouse.
  43188. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  43189. then in your mouseDrag() callback, call dragComponent().
  43190. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  43191. to limit the component's position and keep it on-screen.
  43192. e.g. @code
  43193. class MyDraggableComp
  43194. {
  43195. ComponentDragger myDragger;
  43196. void mouseDown (const MouseEvent& e)
  43197. {
  43198. myDragger.startDraggingComponent (this, e);
  43199. }
  43200. void mouseDrag (const MouseEvent& e)
  43201. {
  43202. myDragger.dragComponent (this, e, nullptr);
  43203. }
  43204. };
  43205. @endcode
  43206. */
  43207. class JUCE_API ComponentDragger
  43208. {
  43209. public:
  43210. /** Creates a ComponentDragger. */
  43211. ComponentDragger();
  43212. /** Destructor. */
  43213. virtual ~ComponentDragger();
  43214. /** Call this from your component's mouseDown() method, to prepare for dragging.
  43215. @param componentToDrag the component that you want to drag
  43216. @param e the mouse event that is triggering the drag
  43217. @see dragComponent
  43218. */
  43219. void startDraggingComponent (Component* componentToDrag,
  43220. const MouseEvent& e);
  43221. /** Call this from your mouseDrag() callback to move the component.
  43222. This will move the component, but will first check the validity of the
  43223. component's new position using the checkPosition() method, which you
  43224. can override if you need to enforce special positioning limits on the
  43225. component.
  43226. @param componentToDrag the component that you want to drag
  43227. @param e the current mouse-drag event
  43228. @param constrainer an optional constrainer object that should be used
  43229. to apply limits to the component's position. Pass
  43230. null if you don't want to contrain the movement.
  43231. @see startDraggingComponent
  43232. */
  43233. void dragComponent (Component* componentToDrag,
  43234. const MouseEvent& e,
  43235. ComponentBoundsConstrainer* constrainer);
  43236. private:
  43237. Point<int> mouseDownWithinTarget;
  43238. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentDragger);
  43239. };
  43240. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  43241. /*** End of inlined file: juce_ComponentDragger.h ***/
  43242. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  43243. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  43244. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  43245. /**
  43246. A component that resizes its parent component when dragged.
  43247. This component forms a frame around the edge of a component, allowing it to
  43248. be dragged by the edges or corners to resize it - like the way windows are
  43249. resized in MSWindows or Linux.
  43250. To use it, just add it to your component, making it fill the entire parent component
  43251. (there's a mouse hit-test that only traps mouse-events which land around the
  43252. edge of the component, so it's even ok to put it on top of any other components
  43253. you're using). Make sure you rescale the resizer component to fill the parent
  43254. each time the parent's size changes.
  43255. @see ResizableCornerComponent
  43256. */
  43257. class JUCE_API ResizableBorderComponent : public Component
  43258. {
  43259. public:
  43260. /** Creates a resizer.
  43261. Pass in the target component which you want to be resized when this one is
  43262. dragged.
  43263. The target component will usually be a parent of the resizer component, but this
  43264. isn't mandatory.
  43265. Remember that when the target component is resized, it'll need to move and
  43266. resize this component to keep it in place, as this won't happen automatically.
  43267. If the constrainer parameter is non-zero, then this object will be used to enforce
  43268. limits on the size and position that the component can be stretched to. Make sure
  43269. that the constrainer isn't deleted while still in use by this object.
  43270. @see ComponentBoundsConstrainer
  43271. */
  43272. ResizableBorderComponent (Component* componentToResize,
  43273. ComponentBoundsConstrainer* constrainer);
  43274. /** Destructor. */
  43275. ~ResizableBorderComponent();
  43276. /** Specifies how many pixels wide the draggable edges of this component are.
  43277. @see getBorderThickness
  43278. */
  43279. void setBorderThickness (const BorderSize<int>& newBorderSize);
  43280. /** Returns the number of pixels wide that the draggable edges of this component are.
  43281. @see setBorderThickness
  43282. */
  43283. const BorderSize<int> getBorderThickness() const;
  43284. /** Represents the different sections of a resizable border, which allow it to
  43285. resized in different ways.
  43286. */
  43287. class Zone
  43288. {
  43289. public:
  43290. enum Zones
  43291. {
  43292. centre = 0,
  43293. left = 1,
  43294. top = 2,
  43295. right = 4,
  43296. bottom = 8
  43297. };
  43298. /** Creates a Zone from a combination of the flags in \enum Zones. */
  43299. explicit Zone (int zoneFlags = 0) noexcept;
  43300. Zone (const Zone& other) noexcept;
  43301. Zone& operator= (const Zone& other) noexcept;
  43302. bool operator== (const Zone& other) const noexcept;
  43303. bool operator!= (const Zone& other) const noexcept;
  43304. /** Given a point within a rectangle with a resizable border, this returns the
  43305. zone that the point lies within.
  43306. */
  43307. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  43308. const BorderSize<int>& border,
  43309. const Point<int>& position);
  43310. /** Returns an appropriate mouse-cursor for this resize zone. */
  43311. const MouseCursor getMouseCursor() const noexcept;
  43312. /** Returns true if dragging this zone will move the enire object without resizing it. */
  43313. bool isDraggingWholeObject() const noexcept { return zone == centre; }
  43314. /** Returns true if dragging this zone will move the object's left edge. */
  43315. bool isDraggingLeftEdge() const noexcept { return (zone & left) != 0; }
  43316. /** Returns true if dragging this zone will move the object's right edge. */
  43317. bool isDraggingRightEdge() const noexcept { return (zone & right) != 0; }
  43318. /** Returns true if dragging this zone will move the object's top edge. */
  43319. bool isDraggingTopEdge() const noexcept { return (zone & top) != 0; }
  43320. /** Returns true if dragging this zone will move the object's bottom edge. */
  43321. bool isDraggingBottomEdge() const noexcept { return (zone & bottom) != 0; }
  43322. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  43323. applies to.
  43324. */
  43325. template <typename ValueType>
  43326. const Rectangle<ValueType> resizeRectangleBy (Rectangle<ValueType> original,
  43327. const Point<ValueType>& distance) const noexcept
  43328. {
  43329. if (isDraggingWholeObject())
  43330. return original + distance;
  43331. if (isDraggingLeftEdge())
  43332. original.setLeft (jmin (original.getRight(), original.getX() + distance.getX()));
  43333. if (isDraggingRightEdge())
  43334. original.setWidth (jmax (ValueType(), original.getWidth() + distance.getX()));
  43335. if (isDraggingTopEdge())
  43336. original.setTop (jmin (original.getBottom(), original.getY() + distance.getY()));
  43337. if (isDraggingBottomEdge())
  43338. original.setHeight (jmax (ValueType(), original.getHeight() + distance.getY()));
  43339. return original;
  43340. }
  43341. /** Returns the raw flags for this zone. */
  43342. int getZoneFlags() const noexcept { return zone; }
  43343. private:
  43344. int zone;
  43345. };
  43346. protected:
  43347. /** @internal */
  43348. void paint (Graphics& g);
  43349. /** @internal */
  43350. void mouseEnter (const MouseEvent& e);
  43351. /** @internal */
  43352. void mouseMove (const MouseEvent& e);
  43353. /** @internal */
  43354. void mouseDown (const MouseEvent& e);
  43355. /** @internal */
  43356. void mouseDrag (const MouseEvent& e);
  43357. /** @internal */
  43358. void mouseUp (const MouseEvent& e);
  43359. /** @internal */
  43360. bool hitTest (int x, int y);
  43361. private:
  43362. WeakReference<Component> component;
  43363. ComponentBoundsConstrainer* constrainer;
  43364. BorderSize<int> borderSize;
  43365. Rectangle<int> originalBounds;
  43366. Zone mouseZone;
  43367. void updateMouseZone (const MouseEvent& e);
  43368. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableBorderComponent);
  43369. };
  43370. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  43371. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  43372. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  43373. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  43374. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  43375. /** A component that resizes a parent component when dragged.
  43376. This is the small triangular stripey resizer component you get in the bottom-right
  43377. of windows (more commonly on the Mac than Windows). Put one in the corner of
  43378. a larger component and it will automatically resize its parent when it gets dragged
  43379. around.
  43380. @see ResizableFrameComponent
  43381. */
  43382. class JUCE_API ResizableCornerComponent : public Component
  43383. {
  43384. public:
  43385. /** Creates a resizer.
  43386. Pass in the target component which you want to be resized when this one is
  43387. dragged.
  43388. The target component will usually be a parent of the resizer component, but this
  43389. isn't mandatory.
  43390. Remember that when the target component is resized, it'll need to move and
  43391. resize this component to keep it in place, as this won't happen automatically.
  43392. If the constrainer parameter is non-zero, then this object will be used to enforce
  43393. limits on the size and position that the component can be stretched to. Make sure
  43394. that the constrainer isn't deleted while still in use by this object. If you
  43395. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  43396. @see ComponentBoundsConstrainer
  43397. */
  43398. ResizableCornerComponent (Component* componentToResize,
  43399. ComponentBoundsConstrainer* constrainer);
  43400. /** Destructor. */
  43401. ~ResizableCornerComponent();
  43402. protected:
  43403. /** @internal */
  43404. void paint (Graphics& g);
  43405. /** @internal */
  43406. void mouseDown (const MouseEvent& e);
  43407. /** @internal */
  43408. void mouseDrag (const MouseEvent& e);
  43409. /** @internal */
  43410. void mouseUp (const MouseEvent& e);
  43411. /** @internal */
  43412. bool hitTest (int x, int y);
  43413. private:
  43414. WeakReference<Component> component;
  43415. ComponentBoundsConstrainer* constrainer;
  43416. Rectangle<int> originalBounds;
  43417. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableCornerComponent);
  43418. };
  43419. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  43420. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  43421. /**
  43422. A base class for top-level windows that can be dragged around and resized.
  43423. To add content to the window, use its setContentOwned() or setContentNonOwned() methods
  43424. to give it a component that will remain positioned inside it (leaving a gap around
  43425. the edges for a border).
  43426. It's not advisable to add child components directly to a ResizableWindow: put them
  43427. inside your content component instead. And overriding methods like resized(), moved(), etc
  43428. is also not recommended - instead override these methods for your content component.
  43429. (If for some obscure reason you do need to override these methods, always remember to
  43430. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  43431. decorations correctly).
  43432. By default resizing isn't enabled - use the setResizable() method to enable it and
  43433. to choose the style of resizing to use.
  43434. @see TopLevelWindow
  43435. */
  43436. class JUCE_API ResizableWindow : public TopLevelWindow
  43437. {
  43438. public:
  43439. /** Creates a ResizableWindow.
  43440. This constructor doesn't specify a background colour, so the LookAndFeel's default
  43441. background colour will be used.
  43442. @param name the name to give the component
  43443. @param addToDesktop if true, the window will be automatically added to the
  43444. desktop; if false, you can use it as a child component
  43445. */
  43446. ResizableWindow (const String& name,
  43447. bool addToDesktop);
  43448. /** Creates a ResizableWindow.
  43449. @param name the name to give the component
  43450. @param backgroundColour the colour to use for filling the window's background.
  43451. @param addToDesktop if true, the window will be automatically added to the
  43452. desktop; if false, you can use it as a child component
  43453. */
  43454. ResizableWindow (const String& name,
  43455. const Colour& backgroundColour,
  43456. bool addToDesktop);
  43457. /** Destructor.
  43458. If a content component has been set with setContentOwned(), it will be deleted.
  43459. */
  43460. ~ResizableWindow();
  43461. /** Returns the colour currently being used for the window's background.
  43462. As a convenience the window will fill itself with this colour, but you
  43463. can override the paint() method if you need more customised behaviour.
  43464. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  43465. @see setBackgroundColour
  43466. */
  43467. const Colour getBackgroundColour() const noexcept;
  43468. /** Changes the colour currently being used for the window's background.
  43469. As a convenience the window will fill itself with this colour, but you
  43470. can override the paint() method if you need more customised behaviour.
  43471. Note that the opaque state of this window is altered by this call to reflect
  43472. the opacity of the colour passed-in. On window systems which can't support
  43473. semi-transparent windows this might cause problems, (though it's unlikely you'll
  43474. be using this class as a base for a semi-transparent component anyway).
  43475. You can also use the ResizableWindow::backgroundColourId colour id to set
  43476. this colour.
  43477. @see getBackgroundColour
  43478. */
  43479. void setBackgroundColour (const Colour& newColour);
  43480. /** Make the window resizable or fixed.
  43481. @param shouldBeResizable whether it's resizable at all
  43482. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  43483. bottom-right; if false, it'll use a ResizableBorderComponent
  43484. around the edge
  43485. @see setResizeLimits, isResizable
  43486. */
  43487. void setResizable (bool shouldBeResizable,
  43488. bool useBottomRightCornerResizer);
  43489. /** True if resizing is enabled.
  43490. @see setResizable
  43491. */
  43492. bool isResizable() const noexcept;
  43493. /** This sets the maximum and minimum sizes for the window.
  43494. If the window's current size is outside these limits, it will be resized to
  43495. make sure it's within them.
  43496. Calling setBounds() on the component will bypass any size checking - it's only when
  43497. the window is being resized by the user that these values are enforced.
  43498. @see setResizable, setFixedAspectRatio
  43499. */
  43500. void setResizeLimits (int newMinimumWidth,
  43501. int newMinimumHeight,
  43502. int newMaximumWidth,
  43503. int newMaximumHeight) noexcept;
  43504. /** Returns the bounds constrainer object that this window is using.
  43505. You can access this to change its properties.
  43506. */
  43507. ComponentBoundsConstrainer* getConstrainer() noexcept { return constrainer; }
  43508. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  43509. A pointer to the object you pass in will be kept, but it won't be deleted
  43510. by this object, so it's the caller's responsiblity to manage it.
  43511. If you pass 0, then no contraints will be placed on the positioning of the window.
  43512. */
  43513. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  43514. /** Calls the window's setBounds method, after first checking these bounds
  43515. with the current constrainer.
  43516. @see setConstrainer
  43517. */
  43518. void setBoundsConstrained (const Rectangle<int>& bounds);
  43519. /** Returns true if the window is currently in full-screen mode.
  43520. @see setFullScreen
  43521. */
  43522. bool isFullScreen() const;
  43523. /** Puts the window into full-screen mode, or restores it to its normal size.
  43524. If true, the window will become full-screen; if false, it will return to the
  43525. last size it was before being made full-screen.
  43526. @see isFullScreen
  43527. */
  43528. void setFullScreen (bool shouldBeFullScreen);
  43529. /** Returns true if the window is currently minimised.
  43530. @see setMinimised
  43531. */
  43532. bool isMinimised() const;
  43533. /** Minimises the window, or restores it to its previous position and size.
  43534. When being un-minimised, it'll return to the last position and size it
  43535. was in before being minimised.
  43536. @see isMinimised
  43537. */
  43538. void setMinimised (bool shouldMinimise);
  43539. /** Adds the window to the desktop using the default flags. */
  43540. void addToDesktop();
  43541. /** Returns a string which encodes the window's current size and position.
  43542. This string will encapsulate the window's size, position, and whether it's
  43543. in full-screen mode. It's intended for letting your application save and
  43544. restore a window's position.
  43545. Use the restoreWindowStateFromString() to restore from a saved state.
  43546. @see restoreWindowStateFromString
  43547. */
  43548. String getWindowStateAsString();
  43549. /** Restores the window to a previously-saved size and position.
  43550. This restores the window's size, positon and full-screen status from an
  43551. string that was previously created with the getWindowStateAsString()
  43552. method.
  43553. @returns false if the string wasn't a valid window state
  43554. @see getWindowStateAsString
  43555. */
  43556. bool restoreWindowStateFromString (const String& previousState);
  43557. /** Returns the current content component.
  43558. This will be the component set by setContentOwned() or setContentNonOwned, or 0 if none
  43559. has yet been specified.
  43560. @see setContentOwned, setContentNonOwned
  43561. */
  43562. Component* getContentComponent() const noexcept { return contentComponent; }
  43563. /** Changes the current content component.
  43564. This sets a component that will be placed in the centre of the ResizableWindow,
  43565. (leaving a space around the edge for the border).
  43566. You should never add components directly to a ResizableWindow (or any of its subclasses)
  43567. with addChildComponent(). Instead, add them to the content component.
  43568. @param newContentComponent the new component to use - this component will be deleted when it's
  43569. no longer needed (i.e. when the window is deleted or a new content
  43570. component is set for it). To set a component that this window will not
  43571. delete, call setContentNonOwned() instead.
  43572. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  43573. such that it always fits around the size of the content component. If false,
  43574. the new content will be resized to fit the current space available.
  43575. */
  43576. void setContentOwned (Component* newContentComponent,
  43577. bool resizeToFitWhenContentChangesSize);
  43578. /** Changes the current content component.
  43579. This sets a component that will be placed in the centre of the ResizableWindow,
  43580. (leaving a space around the edge for the border).
  43581. You should never add components directly to a ResizableWindow (or any of its subclasses)
  43582. with addChildComponent(). Instead, add them to the content component.
  43583. @param newContentComponent the new component to use - this component will NOT be deleted by this
  43584. component, so it's the caller's responsibility to manage its lifetime (it's
  43585. ok to delete it while this window is still using it). To set a content
  43586. component that the window will delete, call setContentOwned() instead.
  43587. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  43588. such that it always fits around the size of the content component. If false,
  43589. the new content will be resized to fit the current space available.
  43590. */
  43591. void setContentNonOwned (Component* newContentComponent,
  43592. bool resizeToFitWhenContentChangesSize);
  43593. /** Removes the current content component.
  43594. If the previous content component was added with setContentOwned(), it will also be deleted. If
  43595. it was added with setContentNonOwned(), it will simply be removed from this component.
  43596. */
  43597. void clearContentComponent();
  43598. /** Changes the window so that the content component ends up with the specified size.
  43599. This is basically a setSize call on the window, but which adds on the borders,
  43600. so you can specify the content component's target size.
  43601. */
  43602. void setContentComponentSize (int width, int height);
  43603. /** Returns the width of the frame to use around the window.
  43604. @see getContentComponentBorder
  43605. */
  43606. virtual const BorderSize<int> getBorderThickness();
  43607. /** Returns the insets to use when positioning the content component.
  43608. @see getBorderThickness
  43609. */
  43610. virtual const BorderSize<int> getContentComponentBorder();
  43611. /** A set of colour IDs to use to change the colour of various aspects of the window.
  43612. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43613. methods.
  43614. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43615. */
  43616. enum ColourIds
  43617. {
  43618. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  43619. };
  43620. /** @deprecated - use setContentOwned() and setContentNonOwned() instead. */
  43621. JUCE_DEPRECATED (void setContentComponent (Component* newContentComponent,
  43622. bool deleteOldOne = true,
  43623. bool resizeToFit = false));
  43624. protected:
  43625. /** @internal */
  43626. void paint (Graphics& g);
  43627. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  43628. void moved();
  43629. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  43630. void resized();
  43631. /** @internal */
  43632. void mouseDown (const MouseEvent& e);
  43633. /** @internal */
  43634. void mouseDrag (const MouseEvent& e);
  43635. /** @internal */
  43636. void lookAndFeelChanged();
  43637. /** @internal */
  43638. void childBoundsChanged (Component* child);
  43639. /** @internal */
  43640. void parentSizeChanged();
  43641. /** @internal */
  43642. void visibilityChanged();
  43643. /** @internal */
  43644. void activeWindowStatusChanged();
  43645. /** @internal */
  43646. int getDesktopWindowStyleFlags() const;
  43647. #if JUCE_DEBUG
  43648. /** Overridden to warn people about adding components directly to this component
  43649. instead of using setContentOwned().
  43650. If you know what you're doing and are sure you really want to add a component, specify
  43651. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  43652. */
  43653. void addChildComponent (Component* child, int zOrder = -1);
  43654. /** Overridden to warn people about adding components directly to this component
  43655. instead of using setContentOwned().
  43656. If you know what you're doing and are sure you really want to add a component, specify
  43657. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  43658. */
  43659. void addAndMakeVisible (Component* child, int zOrder = -1);
  43660. #endif
  43661. ScopedPointer <ResizableCornerComponent> resizableCorner;
  43662. ScopedPointer <ResizableBorderComponent> resizableBorder;
  43663. private:
  43664. Component::SafePointer <Component> contentComponent;
  43665. bool ownsContentComponent, resizeToFitContent, fullscreen;
  43666. ComponentDragger dragger;
  43667. Rectangle<int> lastNonFullScreenPos;
  43668. ComponentBoundsConstrainer defaultConstrainer;
  43669. ComponentBoundsConstrainer* constrainer;
  43670. #if JUCE_DEBUG
  43671. bool hasBeenResized;
  43672. #endif
  43673. void initialise (bool addToDesktop);
  43674. void updateLastPos();
  43675. void setContent (Component* newComp, bool takeOwnership, bool resizeToFit);
  43676. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  43677. // The parameters for these methods have changed - please update your code!
  43678. JUCE_DEPRECATED (void getBorderThickness (int& left, int& top, int& right, int& bottom));
  43679. JUCE_DEPRECATED (void getContentComponentBorder (int& left, int& top, int& right, int& bottom));
  43680. #endif
  43681. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableWindow);
  43682. };
  43683. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  43684. /*** End of inlined file: juce_ResizableWindow.h ***/
  43685. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  43686. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43687. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43688. /**
  43689. A glyph from a particular font, with a particular size, style,
  43690. typeface and position.
  43691. You should rarely need to use this class directly - for most purposes, the
  43692. GlyphArrangement class will do what you need for text layout.
  43693. @see GlyphArrangement, Font
  43694. */
  43695. class JUCE_API PositionedGlyph
  43696. {
  43697. public:
  43698. PositionedGlyph (const Font& font, juce_wchar character, int glyphNumber,
  43699. float anchorX, float baselineY, float width, bool isWhitespace);
  43700. PositionedGlyph (const PositionedGlyph& other);
  43701. PositionedGlyph& operator= (const PositionedGlyph& other);
  43702. ~PositionedGlyph();
  43703. /** Returns the character the glyph represents. */
  43704. juce_wchar getCharacter() const noexcept { return character; }
  43705. /** Checks whether the glyph is actually empty. */
  43706. bool isWhitespace() const noexcept { return whitespace; }
  43707. /** Returns the position of the glyph's left-hand edge. */
  43708. float getLeft() const noexcept { return x; }
  43709. /** Returns the position of the glyph's right-hand edge. */
  43710. float getRight() const noexcept { return x + w; }
  43711. /** Returns the y position of the glyph's baseline. */
  43712. float getBaselineY() const noexcept { return y; }
  43713. /** Returns the y position of the top of the glyph. */
  43714. float getTop() const { return y - font.getAscent(); }
  43715. /** Returns the y position of the bottom of the glyph. */
  43716. float getBottom() const { return y + font.getDescent(); }
  43717. /** Returns the bounds of the glyph. */
  43718. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  43719. /** Shifts the glyph's position by a relative amount. */
  43720. void moveBy (float deltaX, float deltaY);
  43721. /** Draws the glyph into a graphics context. */
  43722. void draw (const Graphics& g) const;
  43723. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  43724. void draw (const Graphics& g, const AffineTransform& transform) const;
  43725. /** Returns the path for this glyph.
  43726. @param path the glyph's outline will be appended to this path
  43727. */
  43728. void createPath (Path& path) const;
  43729. /** Checks to see if a point lies within this glyph. */
  43730. bool hitTest (float x, float y) const;
  43731. private:
  43732. friend class GlyphArrangement;
  43733. Font font;
  43734. juce_wchar character;
  43735. int glyph;
  43736. float x, y, w;
  43737. bool whitespace;
  43738. JUCE_LEAK_DETECTOR (PositionedGlyph);
  43739. };
  43740. /**
  43741. A set of glyphs, each with a position.
  43742. You can create a GlyphArrangement, text to it and then draw it onto a
  43743. graphics context. It's used internally by the text methods in the
  43744. Graphics class, but can be used directly if more control is needed.
  43745. @see Font, PositionedGlyph
  43746. */
  43747. class JUCE_API GlyphArrangement
  43748. {
  43749. public:
  43750. /** Creates an empty arrangement. */
  43751. GlyphArrangement();
  43752. /** Takes a copy of another arrangement. */
  43753. GlyphArrangement (const GlyphArrangement& other);
  43754. /** Copies another arrangement onto this one.
  43755. To add another arrangement without clearing this one, use addGlyphArrangement().
  43756. */
  43757. GlyphArrangement& operator= (const GlyphArrangement& other);
  43758. /** Destructor. */
  43759. ~GlyphArrangement();
  43760. /** Returns the total number of glyphs in the arrangement. */
  43761. int getNumGlyphs() const noexcept { return glyphs.size(); }
  43762. /** Returns one of the glyphs from the arrangement.
  43763. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  43764. careful not to pass an out-of-range index here, as it
  43765. doesn't do any bounds-checking.
  43766. */
  43767. PositionedGlyph& getGlyph (int index) const;
  43768. /** Clears all text from the arrangement and resets it.
  43769. */
  43770. void clear();
  43771. /** Appends a line of text to the arrangement.
  43772. This will add the text as a single line, where x is the left-hand edge of the
  43773. first character, and y is the position for the text's baseline.
  43774. If the text contains new-lines or carriage-returns, this will ignore them - use
  43775. addJustifiedText() to add multi-line arrangements.
  43776. */
  43777. void addLineOfText (const Font& font,
  43778. const String& text,
  43779. float x, float y);
  43780. /** Adds a line of text, truncating it if it's wider than a specified size.
  43781. This is the same as addLineOfText(), but if the line's width exceeds the value
  43782. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  43783. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  43784. */
  43785. void addCurtailedLineOfText (const Font& font,
  43786. const String& text,
  43787. float x, float y,
  43788. float maxWidthPixels,
  43789. bool useEllipsis);
  43790. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  43791. This will add text to the arrangement, breaking it into new lines either where there
  43792. is a new-line or carriage-return character in the text, or where a line's width
  43793. exceeds the value set in maxLineWidth.
  43794. Each line that is added will be laid out using the flags set in horizontalLayout, so
  43795. the lines can be left- or right-justified, or centred horizontally in the space
  43796. between x and (x + maxLineWidth).
  43797. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  43798. lines will be placed below it, separated by a distance of font.getHeight().
  43799. */
  43800. void addJustifiedText (const Font& font,
  43801. const String& text,
  43802. float x, float y,
  43803. float maxLineWidth,
  43804. const Justification& horizontalLayout);
  43805. /** Tries to fit some text withing a given space.
  43806. This does its best to make the given text readable within the specified rectangle,
  43807. so it useful for labelling things.
  43808. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  43809. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  43810. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  43811. it's been truncated.
  43812. A Justification parameter lets you specify how the text is laid out within the rectangle,
  43813. both horizontally and vertically.
  43814. @see Graphics::drawFittedText
  43815. */
  43816. void addFittedText (const Font& font,
  43817. const String& text,
  43818. float x, float y, float width, float height,
  43819. const Justification& layout,
  43820. int maximumLinesToUse,
  43821. float minimumHorizontalScale = 0.7f);
  43822. /** Appends another glyph arrangement to this one. */
  43823. void addGlyphArrangement (const GlyphArrangement& other);
  43824. /** Appends a custom glyph to the arrangement. */
  43825. void addGlyph (const PositionedGlyph& glyph);
  43826. /** Draws this glyph arrangement to a graphics context.
  43827. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  43828. method, which renders the glyphs as filled vectors.
  43829. */
  43830. void draw (const Graphics& g) const;
  43831. /** Draws this glyph arrangement to a graphics context.
  43832. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  43833. method for non-transformed arrangements.
  43834. */
  43835. void draw (const Graphics& g, const AffineTransform& transform) const;
  43836. /** Converts the set of glyphs into a path.
  43837. @param path the glyphs' outlines will be appended to this path
  43838. */
  43839. void createPath (Path& path) const;
  43840. /** Looks for a glyph that contains the given co-ordinate.
  43841. @returns the index of the glyph, or -1 if none were found.
  43842. */
  43843. int findGlyphIndexAt (float x, float y) const;
  43844. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  43845. @param startIndex the first glyph to test
  43846. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  43847. startIndex will be included
  43848. @param includeWhitespace if true, the extent of any whitespace characters will also
  43849. be taken into account
  43850. */
  43851. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  43852. /** Shifts a set of glyphs by a given amount.
  43853. @param startIndex the first glyph to transform
  43854. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  43855. startIndex will be used
  43856. @param deltaX the amount to add to their x-positions
  43857. @param deltaY the amount to add to their y-positions
  43858. */
  43859. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  43860. float deltaX, float deltaY);
  43861. /** Removes a set of glyphs from the arrangement.
  43862. @param startIndex the first glyph to remove
  43863. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  43864. startIndex will be deleted
  43865. */
  43866. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  43867. /** Expands or compresses a set of glyphs horizontally.
  43868. @param startIndex the first glyph to transform
  43869. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  43870. startIndex will be used
  43871. @param horizontalScaleFactor how much to scale their horizontal width by
  43872. */
  43873. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  43874. float horizontalScaleFactor);
  43875. /** Justifies a set of glyphs within a given space.
  43876. This moves the glyphs as a block so that the whole thing is located within the
  43877. given rectangle with the specified layout.
  43878. If the Justification::horizontallyJustified flag is specified, each line will
  43879. be stretched out to fill the specified width.
  43880. */
  43881. void justifyGlyphs (int startIndex, int numGlyphs,
  43882. float x, float y, float width, float height,
  43883. const Justification& justification);
  43884. private:
  43885. OwnedArray <PositionedGlyph> glyphs;
  43886. int insertEllipsis (const Font&, float maxXPos, int startIndex, int endIndex);
  43887. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font&,
  43888. const Justification&, float minimumHorizontalScale);
  43889. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  43890. JUCE_LEAK_DETECTOR (GlyphArrangement);
  43891. };
  43892. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43893. /*** End of inlined file: juce_GlyphArrangement.h ***/
  43894. /*** Start of inlined file: juce_AlertWindow.h ***/
  43895. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  43896. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  43897. /*** Start of inlined file: juce_TextLayout.h ***/
  43898. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  43899. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  43900. class Graphics;
  43901. /**
  43902. A laid-out arrangement of text.
  43903. You can add text in different fonts to a TextLayout object, then call its
  43904. layout() method to word-wrap it into lines. The layout can then be drawn
  43905. using a graphics context.
  43906. It's handy if you've got a message to display, because you can format it,
  43907. measure the extent of the layout, and then create a suitably-sized window
  43908. to show it in.
  43909. @see Font, Graphics::drawFittedText, GlyphArrangement
  43910. */
  43911. class JUCE_API TextLayout
  43912. {
  43913. public:
  43914. /** Creates an empty text layout.
  43915. Text can then be appended using the appendText() method.
  43916. */
  43917. TextLayout();
  43918. /** Creates a copy of another layout object. */
  43919. TextLayout (const TextLayout& other);
  43920. /** Creates a text layout from an initial string and font. */
  43921. TextLayout (const String& text, const Font& font);
  43922. /** Destructor. */
  43923. ~TextLayout();
  43924. /** Copies another layout onto this one. */
  43925. TextLayout& operator= (const TextLayout& layoutToCopy);
  43926. /** Clears the layout, removing all its text. */
  43927. void clear();
  43928. /** Adds a string to the end of the arrangement.
  43929. The string will be broken onto new lines wherever it contains
  43930. carriage-returns or linefeeds. After adding it, you can call layout()
  43931. to wrap long lines into a paragraph and justify it.
  43932. */
  43933. void appendText (const String& textToAppend,
  43934. const Font& fontToUse);
  43935. /** Replaces all the text with a new string.
  43936. This is equivalent to calling clear() followed by appendText().
  43937. */
  43938. void setText (const String& newText,
  43939. const Font& fontToUse);
  43940. /** Returns true if the layout has not had any text added yet. */
  43941. bool isEmpty() const;
  43942. /** Breaks the text up to form a paragraph with the given width.
  43943. @param maximumWidth any text wider than this will be split
  43944. across multiple lines
  43945. @param justification how the lines are to be laid-out horizontally
  43946. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  43947. width that keeps all the lines of text at a
  43948. similar length - this is good when you're displaying
  43949. a short message and don't want it to get split
  43950. onto two lines with only a couple of words on
  43951. the second line, which looks untidy.
  43952. */
  43953. void layout (int maximumWidth,
  43954. const Justification& justification,
  43955. bool attemptToBalanceLineLengths);
  43956. /** Returns the overall width of the entire text layout. */
  43957. int getWidth() const;
  43958. /** Returns the overall height of the entire text layout. */
  43959. int getHeight() const;
  43960. /** Returns the total number of lines of text. */
  43961. int getNumLines() const { return totalLines; }
  43962. /** Returns the width of a particular line of text.
  43963. @param lineNumber the line, from 0 to (getNumLines() - 1)
  43964. */
  43965. int getLineWidth (int lineNumber) const;
  43966. /** Renders the text at a specified position using a graphics context.
  43967. */
  43968. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  43969. /** Renders the text within a specified rectangle using a graphics context.
  43970. The justification flags dictate how the block of text should be positioned
  43971. within the rectangle.
  43972. */
  43973. void drawWithin (Graphics& g,
  43974. int x, int y, int w, int h,
  43975. const Justification& layoutFlags) const;
  43976. private:
  43977. class Token;
  43978. friend class OwnedArray <Token>;
  43979. OwnedArray <Token> tokens;
  43980. int totalLines;
  43981. JUCE_LEAK_DETECTOR (TextLayout);
  43982. };
  43983. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  43984. /*** End of inlined file: juce_TextLayout.h ***/
  43985. /** A window that displays a message and has buttons for the user to react to it.
  43986. For simple dialog boxes with just a couple of buttons on them, there are
  43987. some static methods for running these.
  43988. For more complex dialogs, an AlertWindow can be created, then it can have some
  43989. buttons and components added to it, and its runModalLoop() method is then used to
  43990. show it. The value returned by runModalLoop() shows which button the
  43991. user pressed to dismiss the box.
  43992. @see ThreadWithProgressWindow
  43993. */
  43994. class JUCE_API AlertWindow : public TopLevelWindow,
  43995. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  43996. {
  43997. public:
  43998. /** The type of icon to show in the dialog box. */
  43999. enum AlertIconType
  44000. {
  44001. NoIcon, /**< No icon will be shown on the dialog box. */
  44002. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  44003. user to answer a question. */
  44004. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  44005. warning about something and shouldn't be ignored. */
  44006. InfoIcon /**< An icon that indicates that the dialog box is just
  44007. giving the user some information, which doesn't require
  44008. a response from them. */
  44009. };
  44010. /** Creates an AlertWindow.
  44011. @param title the headline to show at the top of the dialog box
  44012. @param message a longer, more descriptive message to show underneath the
  44013. headline
  44014. @param iconType the type of icon to display
  44015. @param associatedComponent if this is non-null, it specifies the component that the
  44016. alert window should be associated with. Depending on the look
  44017. and feel, this might be used for positioning of the alert window.
  44018. */
  44019. AlertWindow (const String& title,
  44020. const String& message,
  44021. AlertIconType iconType,
  44022. Component* associatedComponent = nullptr);
  44023. /** Destroys the AlertWindow */
  44024. ~AlertWindow();
  44025. /** Returns the type of alert icon that was specified when the window
  44026. was created. */
  44027. AlertIconType getAlertType() const noexcept { return alertIconType; }
  44028. /** Changes the dialog box's message.
  44029. This will also resize the window to fit the new message if required.
  44030. */
  44031. void setMessage (const String& message);
  44032. /** Adds a button to the window.
  44033. @param name the text to show on the button
  44034. @param returnValue the value that should be returned from runModalLoop()
  44035. if this is the button that the user presses.
  44036. @param shortcutKey1 an optional key that can be pressed to trigger this button
  44037. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  44038. */
  44039. void addButton (const String& name,
  44040. int returnValue,
  44041. const KeyPress& shortcutKey1 = KeyPress(),
  44042. const KeyPress& shortcutKey2 = KeyPress());
  44043. /** Returns the number of buttons that the window currently has. */
  44044. int getNumButtons() const;
  44045. /** Invokes a click of one of the buttons. */
  44046. void triggerButtonClick (const String& buttonName);
  44047. /** Adds a textbox to the window for entering strings.
  44048. @param name an internal name for the text-box. This is the name to pass to
  44049. the getTextEditorContents() method to find out what the
  44050. user typed-in.
  44051. @param initialContents a string to show in the text box when it's first shown
  44052. @param onScreenLabel if this is non-empty, it will be displayed next to the
  44053. text-box to label it.
  44054. @param isPasswordBox if true, the text editor will display asterisks instead of
  44055. the actual text
  44056. @see getTextEditorContents
  44057. */
  44058. void addTextEditor (const String& name,
  44059. const String& initialContents,
  44060. const String& onScreenLabel = String::empty,
  44061. bool isPasswordBox = false);
  44062. /** Returns the contents of a named textbox.
  44063. After showing an AlertWindow that contains a text editor, this can be
  44064. used to find out what the user has typed into it.
  44065. @param nameOfTextEditor the name of the text box that you're interested in
  44066. @see addTextEditor
  44067. */
  44068. String getTextEditorContents (const String& nameOfTextEditor) const;
  44069. /** Returns a pointer to a textbox that was added with addTextEditor(). */
  44070. TextEditor* getTextEditor (const String& nameOfTextEditor) const;
  44071. /** Adds a drop-down list of choices to the box.
  44072. After the box has been shown, the getComboBoxComponent() method can
  44073. be used to find out which item the user picked.
  44074. @param name the label to use for the drop-down list
  44075. @param items the list of items to show in it
  44076. @param onScreenLabel if this is non-empty, it will be displayed next to the
  44077. combo-box to label it.
  44078. @see getComboBoxComponent
  44079. */
  44080. void addComboBox (const String& name,
  44081. const StringArray& items,
  44082. const String& onScreenLabel = String::empty);
  44083. /** Returns a drop-down list that was added to the AlertWindow.
  44084. @param nameOfList the name that was passed into the addComboBox() method
  44085. when creating the drop-down
  44086. @returns the ComboBox component, or 0 if none was found for the given name.
  44087. */
  44088. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  44089. /** Adds a block of text.
  44090. This is handy for adding a multi-line note next to a textbox or combo-box,
  44091. to provide more details about what's going on.
  44092. */
  44093. void addTextBlock (const String& text);
  44094. /** Adds a progress-bar to the window.
  44095. @param progressValue a variable that will be repeatedly checked while the
  44096. dialog box is visible, to see how far the process has
  44097. got. The value should be in the range 0 to 1.0
  44098. */
  44099. void addProgressBarComponent (double& progressValue);
  44100. /** Adds a user-defined component to the dialog box.
  44101. @param component the component to add - its size should be set up correctly
  44102. before it is passed in. The caller is responsible for deleting
  44103. the component later on - the AlertWindow won't delete it.
  44104. */
  44105. void addCustomComponent (Component* component);
  44106. /** Returns the number of custom components in the dialog box.
  44107. @see getCustomComponent, addCustomComponent
  44108. */
  44109. int getNumCustomComponents() const;
  44110. /** Returns one of the custom components in the dialog box.
  44111. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  44112. will return 0
  44113. @see getNumCustomComponents, addCustomComponent
  44114. */
  44115. Component* getCustomComponent (int index) const;
  44116. /** Removes one of the custom components in the dialog box.
  44117. Note that this won't delete it, it just removes the component from the window
  44118. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  44119. will return 0
  44120. @returns the component that was removed (or null)
  44121. @see getNumCustomComponents, addCustomComponent
  44122. */
  44123. Component* removeCustomComponent (int index);
  44124. /** Returns true if the window contains any components other than just buttons.*/
  44125. bool containsAnyExtraComponents() const;
  44126. // easy-to-use message box functions:
  44127. /** Shows a dialog box that just has a message and a single button to get rid of it.
  44128. If the callback parameter is null, the box is shown modally, and the method will
  44129. block until the user has clicked the button (or pressed the escape or return keys).
  44130. If the callback parameter is non-null, the box will be displayed and placed into a
  44131. modal state, but this method will return immediately, and the callback will be invoked
  44132. later when the user dismisses the box.
  44133. @param iconType the type of icon to show
  44134. @param title the headline to show at the top of the box
  44135. @param message a longer, more descriptive message to show underneath the
  44136. headline
  44137. @param buttonText the text to show in the button - if this string is empty, the
  44138. default string "ok" (or a localised version) will be used.
  44139. @param associatedComponent if this is non-null, it specifies the component that the
  44140. alert window should be associated with. Depending on the look
  44141. and feel, this might be used for positioning of the alert window.
  44142. */
  44143. #if JUCE_MODAL_LOOPS_PERMITTED
  44144. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  44145. const String& title,
  44146. const String& message,
  44147. const String& buttonText = String::empty,
  44148. Component* associatedComponent = nullptr);
  44149. #endif
  44150. /** Shows a dialog box that just has a message and a single button to get rid of it.
  44151. If the callback parameter is null, the box is shown modally, and the method will
  44152. block until the user has clicked the button (or pressed the escape or return keys).
  44153. If the callback parameter is non-null, the box will be displayed and placed into a
  44154. modal state, but this method will return immediately, and the callback will be invoked
  44155. later when the user dismisses the box.
  44156. @param iconType the type of icon to show
  44157. @param title the headline to show at the top of the box
  44158. @param message a longer, more descriptive message to show underneath the
  44159. headline
  44160. @param buttonText the text to show in the button - if this string is empty, the
  44161. default string "ok" (or a localised version) will be used.
  44162. @param associatedComponent if this is non-null, it specifies the component that the
  44163. alert window should be associated with. Depending on the look
  44164. and feel, this might be used for positioning of the alert window.
  44165. */
  44166. static void JUCE_CALLTYPE showMessageBoxAsync (AlertIconType iconType,
  44167. const String& title,
  44168. const String& message,
  44169. const String& buttonText = String::empty,
  44170. Component* associatedComponent = nullptr);
  44171. /** Shows a dialog box with two buttons.
  44172. Ideal for ok/cancel or yes/no choices. The return key can also be used
  44173. to trigger the first button, and the escape key for the second button.
  44174. If the callback parameter is null, the box is shown modally, and the method will
  44175. block until the user has clicked the button (or pressed the escape or return keys).
  44176. If the callback parameter is non-null, the box will be displayed and placed into a
  44177. modal state, but this method will return immediately, and the callback will be invoked
  44178. later when the user dismisses the box.
  44179. @param iconType the type of icon to show
  44180. @param title the headline to show at the top of the box
  44181. @param message a longer, more descriptive message to show underneath the
  44182. headline
  44183. @param button1Text the text to show in the first button - if this string is
  44184. empty, the default string "ok" (or a localised version of it)
  44185. will be used.
  44186. @param button2Text the text to show in the second button - if this string is
  44187. empty, the default string "cancel" (or a localised version of it)
  44188. will be used.
  44189. @param associatedComponent if this is non-null, it specifies the component that the
  44190. alert window should be associated with. Depending on the look
  44191. and feel, this might be used for positioning of the alert window.
  44192. @param callback if this is non-null, the menu will be launched asynchronously,
  44193. returning immediately, and the callback will receive a call to its
  44194. modalStateFinished() when the box is dismissed, with its parameter
  44195. being 1 if the ok button was pressed, or 0 for cancel, The callback object
  44196. will be owned and deleted by the system, so make sure that it works
  44197. safely and doesn't keep any references to objects that might be deleted
  44198. before it gets called.
  44199. @returns true if button 1 was clicked, false if it was button 2. If the callback parameter
  44200. is not null, the method always returns false, and the user's choice is delivered
  44201. later by the callback.
  44202. */
  44203. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  44204. const String& title,
  44205. const String& message,
  44206. #if JUCE_MODAL_LOOPS_PERMITTED
  44207. const String& button1Text = String::empty,
  44208. const String& button2Text = String::empty,
  44209. Component* associatedComponent = nullptr,
  44210. ModalComponentManager::Callback* callback = nullptr);
  44211. #else
  44212. const String& button1Text,
  44213. const String& button2Text,
  44214. Component* associatedComponent,
  44215. ModalComponentManager::Callback* callback);
  44216. #endif
  44217. /** Shows a dialog box with three buttons.
  44218. Ideal for yes/no/cancel boxes.
  44219. The escape key can be used to trigger the third button.
  44220. If the callback parameter is null, the box is shown modally, and the method will
  44221. block until the user has clicked the button (or pressed the escape or return keys).
  44222. If the callback parameter is non-null, the box will be displayed and placed into a
  44223. modal state, but this method will return immediately, and the callback will be invoked
  44224. later when the user dismisses the box.
  44225. @param iconType the type of icon to show
  44226. @param title the headline to show at the top of the box
  44227. @param message a longer, more descriptive message to show underneath the
  44228. headline
  44229. @param button1Text the text to show in the first button - if an empty string, then
  44230. "yes" will be used (or a localised version of it)
  44231. @param button2Text the text to show in the first button - if an empty string, then
  44232. "no" will be used (or a localised version of it)
  44233. @param button3Text the text to show in the first button - if an empty string, then
  44234. "cancel" will be used (or a localised version of it)
  44235. @param associatedComponent if this is non-null, it specifies the component that the
  44236. alert window should be associated with. Depending on the look
  44237. and feel, this might be used for positioning of the alert window.
  44238. @param callback if this is non-null, the menu will be launched asynchronously,
  44239. returning immediately, and the callback will receive a call to its
  44240. modalStateFinished() when the box is dismissed, with its parameter
  44241. being 1 if the "yes" button was pressed, 2 for the "no" button, or 0
  44242. if it was cancelled, The callback object will be owned and deleted by the
  44243. system, so make sure that it works safely and doesn't keep any references
  44244. to objects that might be deleted before it gets called.
  44245. @returns If the callback parameter has been set, this returns 0. Otherwise, it
  44246. returns one of the following values:
  44247. - 0 if the third button was pressed (normally used for 'cancel')
  44248. - 1 if the first button was pressed (normally used for 'yes')
  44249. - 2 if the middle button was pressed (normally used for 'no')
  44250. */
  44251. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  44252. const String& title,
  44253. const String& message,
  44254. #if JUCE_MODAL_LOOPS_PERMITTED
  44255. const String& button1Text = String::empty,
  44256. const String& button2Text = String::empty,
  44257. const String& button3Text = String::empty,
  44258. Component* associatedComponent = nullptr,
  44259. ModalComponentManager::Callback* callback = nullptr);
  44260. #else
  44261. const String& button1Text,
  44262. const String& button2Text,
  44263. const String& button3Text,
  44264. Component* associatedComponent,
  44265. ModalComponentManager::Callback* callback);
  44266. #endif
  44267. /** Shows an operating-system native dialog box.
  44268. @param title the title to use at the top
  44269. @param bodyText the longer message to show
  44270. @param isOkCancel if true, this will show an ok/cancel box, if false,
  44271. it'll show a box with just an ok button
  44272. @returns true if the ok button was pressed, false if they pressed cancel.
  44273. */
  44274. #if JUCE_MODAL_LOOPS_PERMITTED
  44275. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  44276. const String& bodyText,
  44277. bool isOkCancel);
  44278. #endif
  44279. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  44280. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44281. methods.
  44282. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44283. */
  44284. enum ColourIds
  44285. {
  44286. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  44287. textColourId = 0x1001810, /**< The colour for the text. */
  44288. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  44289. };
  44290. protected:
  44291. /** @internal */
  44292. void paint (Graphics& g);
  44293. /** @internal */
  44294. void mouseDown (const MouseEvent& e);
  44295. /** @internal */
  44296. void mouseDrag (const MouseEvent& e);
  44297. /** @internal */
  44298. bool keyPressed (const KeyPress& key);
  44299. /** @internal */
  44300. void buttonClicked (Button* button);
  44301. /** @internal */
  44302. void lookAndFeelChanged();
  44303. /** @internal */
  44304. void userTriedToCloseWindow();
  44305. /** @internal */
  44306. int getDesktopWindowStyleFlags() const;
  44307. private:
  44308. String text;
  44309. TextLayout textLayout;
  44310. AlertIconType alertIconType;
  44311. ComponentBoundsConstrainer constrainer;
  44312. ComponentDragger dragger;
  44313. Rectangle<int> textArea;
  44314. OwnedArray<TextButton> buttons;
  44315. OwnedArray<TextEditor> textBoxes;
  44316. OwnedArray<ComboBox> comboBoxes;
  44317. OwnedArray<ProgressBar> progressBars;
  44318. Array<Component*> customComps;
  44319. OwnedArray<Component> textBlocks;
  44320. Array<Component*> allComps;
  44321. StringArray textboxNames, comboBoxNames;
  44322. Font font;
  44323. Component* associatedComponent;
  44324. void updateLayout (bool onlyIncreaseSize);
  44325. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AlertWindow);
  44326. };
  44327. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  44328. /*** End of inlined file: juce_AlertWindow.h ***/
  44329. /**
  44330. A file open/save dialog box.
  44331. This is a Juce-based file dialog box; to use a native file chooser, see the
  44332. FileChooser class.
  44333. To use one of these, create it and call its show() method. e.g.
  44334. @code
  44335. {
  44336. WildcardFileFilter wildcardFilter ("*.foo", String::empty, "Foo files");
  44337. FileBrowserComponent browser (FileBrowserComponent::canSelectFiles,
  44338. File::nonexistent,
  44339. &wildcardFilter,
  44340. nullptr);
  44341. FileChooserDialogBox dialogBox ("Open some kind of file",
  44342. "Please choose some kind of file that you want to open...",
  44343. browser,
  44344. false,
  44345. Colours::lightgrey);
  44346. if (dialogBox.show())
  44347. {
  44348. File selectedFile = browser.getSelectedFile (0);
  44349. ...etc..
  44350. }
  44351. }
  44352. @endcode
  44353. @see FileChooser
  44354. */
  44355. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  44356. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  44357. public FileBrowserListener
  44358. {
  44359. public:
  44360. /** Creates a file chooser box.
  44361. @param title the main title to show at the top of the box
  44362. @param instructions an optional longer piece of text to show below the title in
  44363. a smaller font, describing in more detail what's required.
  44364. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  44365. box. Make sure you delete this after (but not before!) the
  44366. dialog box has been deleted.
  44367. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  44368. if they try to select a file that already exists. (This
  44369. flag is only used when saving files)
  44370. @param backgroundColour the background colour for the top level window
  44371. @see FileBrowserComponent, FilePreviewComponent
  44372. */
  44373. FileChooserDialogBox (const String& title,
  44374. const String& instructions,
  44375. FileBrowserComponent& browserComponent,
  44376. bool warnAboutOverwritingExistingFiles,
  44377. const Colour& backgroundColour);
  44378. /** Destructor. */
  44379. ~FileChooserDialogBox();
  44380. #if JUCE_MODAL_LOOPS_PERMITTED
  44381. /** Displays and runs the dialog box modally.
  44382. This will show the box with the specified size, returning true if the user
  44383. pressed 'ok', or false if they cancelled.
  44384. Leave the width or height as 0 to use the default size
  44385. */
  44386. bool show (int width = 0, int height = 0);
  44387. /** Displays and runs the dialog box modally.
  44388. This will show the box with the specified size at the specified location,
  44389. returning true if the user pressed 'ok', or false if they cancelled.
  44390. Leave the width or height as 0 to use the default size.
  44391. */
  44392. bool showAt (int x, int y, int width, int height);
  44393. #endif
  44394. /** Sets the size of this dialog box to its default and positions it either in the
  44395. centre of the screen, or centred around a component that is provided.
  44396. */
  44397. void centreWithDefaultSize (Component* componentToCentreAround = 0);
  44398. /** A set of colour IDs to use to change the colour of various aspects of the box.
  44399. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44400. methods.
  44401. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44402. */
  44403. enum ColourIds
  44404. {
  44405. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  44406. };
  44407. /** @internal */
  44408. void buttonClicked (Button* button);
  44409. /** @internal */
  44410. void closeButtonPressed();
  44411. /** @internal */
  44412. void selectionChanged();
  44413. /** @internal */
  44414. void fileClicked (const File& file, const MouseEvent& e);
  44415. /** @internal */
  44416. void fileDoubleClicked (const File& file);
  44417. private:
  44418. class ContentComponent;
  44419. ContentComponent* content;
  44420. const bool warnAboutOverwritingExistingFiles;
  44421. void okButtonPressed();
  44422. void createNewFolder();
  44423. void createNewFolderConfirmed (const String& name);
  44424. static void okToOverwriteFileCallback (int result, FileChooserDialogBox*);
  44425. static void createNewFolderCallback (int result, FileChooserDialogBox*, Component::SafePointer<AlertWindow>);
  44426. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileChooserDialogBox);
  44427. };
  44428. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  44429. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  44430. #endif
  44431. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  44432. #endif
  44433. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  44434. /*** Start of inlined file: juce_FileListComponent.h ***/
  44435. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  44436. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  44437. /**
  44438. A component that displays the files in a directory as a listbox.
  44439. This implements the DirectoryContentsDisplayComponent base class so that
  44440. it can be used in a FileBrowserComponent.
  44441. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  44442. class and the FileBrowserListener class.
  44443. @see DirectoryContentsList, FileTreeComponent
  44444. */
  44445. class JUCE_API FileListComponent : public ListBox,
  44446. public DirectoryContentsDisplayComponent,
  44447. private ListBoxModel,
  44448. private ChangeListener
  44449. {
  44450. public:
  44451. /** Creates a listbox to show the contents of a specified directory.
  44452. */
  44453. FileListComponent (DirectoryContentsList& listToShow);
  44454. /** Destructor. */
  44455. ~FileListComponent();
  44456. /** Returns the number of files the user has got selected.
  44457. @see getSelectedFile
  44458. */
  44459. int getNumSelectedFiles() const;
  44460. /** Returns one of the files that the user has currently selected.
  44461. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  44462. @see getNumSelectedFiles
  44463. */
  44464. const File getSelectedFile (int index = 0) const;
  44465. /** Deselects any files that are currently selected. */
  44466. void deselectAllFiles();
  44467. /** Scrolls to the top of the list. */
  44468. void scrollToTop();
  44469. /** @internal */
  44470. void changeListenerCallback (ChangeBroadcaster*);
  44471. /** @internal */
  44472. int getNumRows();
  44473. /** @internal */
  44474. void paintListBoxItem (int, Graphics&, int, int, bool);
  44475. /** @internal */
  44476. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  44477. /** @internal */
  44478. void selectedRowsChanged (int lastRowSelected);
  44479. /** @internal */
  44480. void deleteKeyPressed (int currentSelectedRow);
  44481. /** @internal */
  44482. void returnKeyPressed (int currentSelectedRow);
  44483. private:
  44484. File lastDirectory;
  44485. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListComponent);
  44486. };
  44487. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  44488. /*** End of inlined file: juce_FileListComponent.h ***/
  44489. #endif
  44490. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  44491. /*** Start of inlined file: juce_FilenameComponent.h ***/
  44492. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  44493. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  44494. class FilenameComponent;
  44495. /**
  44496. Listens for events happening to a FilenameComponent.
  44497. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  44498. register one of these objects for event callbacks when the filename is changed.
  44499. @see FilenameComponent
  44500. */
  44501. class JUCE_API FilenameComponentListener
  44502. {
  44503. public:
  44504. /** Destructor. */
  44505. virtual ~FilenameComponentListener() {}
  44506. /** This method is called after the FilenameComponent's file has been changed. */
  44507. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  44508. };
  44509. /**
  44510. Shows a filename as an editable text box, with a 'browse' button and a
  44511. drop-down list for recently selected files.
  44512. A handy component for dialogue boxes where you want the user to be able to
  44513. select a file or directory.
  44514. Attach an FilenameComponentListener using the addListener() method, and it will
  44515. get called each time the user changes the filename, either by browsing for a file
  44516. and clicking 'ok', or by typing a new filename into the box and pressing return.
  44517. @see FileChooser, ComboBox
  44518. */
  44519. class JUCE_API FilenameComponent : public Component,
  44520. public SettableTooltipClient,
  44521. public FileDragAndDropTarget,
  44522. private AsyncUpdater,
  44523. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  44524. private ComboBoxListener
  44525. {
  44526. public:
  44527. /** Creates a FilenameComponent.
  44528. @param name the name for this component.
  44529. @param currentFile the file to initially show in the box
  44530. @param canEditFilename if true, the user can manually edit the filename; if false,
  44531. they can only change it by browsing for a new file
  44532. @param isDirectory if true, the file will be treated as a directory, and
  44533. an appropriate directory browser used
  44534. @param isForSaving if true, the file browser will allow non-existent files to
  44535. be picked, as the file is assumed to be used for saving rather
  44536. than loading
  44537. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  44538. If an empty string is passed in, then the pattern is assumed to be "*"
  44539. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  44540. to any filenames that are entered or chosen
  44541. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  44542. will only appear if the initial file isn't valid)
  44543. */
  44544. FilenameComponent (const String& name,
  44545. const File& currentFile,
  44546. bool canEditFilename,
  44547. bool isDirectory,
  44548. bool isForSaving,
  44549. const String& fileBrowserWildcard,
  44550. const String& enforcedSuffix,
  44551. const String& textWhenNothingSelected);
  44552. /** Destructor. */
  44553. ~FilenameComponent();
  44554. /** Returns the currently displayed filename. */
  44555. File getCurrentFile() const;
  44556. /** Changes the current filename.
  44557. If addToRecentlyUsedList is true, the filename will also be added to the
  44558. drop-down list of recent files.
  44559. If sendChangeNotification is false, then the listeners won't be told of the
  44560. change.
  44561. */
  44562. void setCurrentFile (File newFile,
  44563. bool addToRecentlyUsedList,
  44564. bool sendChangeNotification = true);
  44565. /** Changes whether the use can type into the filename box.
  44566. */
  44567. void setFilenameIsEditable (bool shouldBeEditable);
  44568. /** Sets a file or directory to be the default starting point for the browser to show.
  44569. This is only used if the current file hasn't been set.
  44570. */
  44571. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  44572. /** Returns all the entries on the recent files list.
  44573. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  44574. state of this list.
  44575. @see setRecentlyUsedFilenames
  44576. */
  44577. StringArray getRecentlyUsedFilenames() const;
  44578. /** Sets all the entries on the recent files list.
  44579. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  44580. state of this list.
  44581. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  44582. */
  44583. void setRecentlyUsedFilenames (const StringArray& filenames);
  44584. /** Adds an entry to the recently-used files dropdown list.
  44585. If the file is already in the list, it will be moved to the top. A limit
  44586. is also placed on the number of items that are kept in the list.
  44587. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  44588. */
  44589. void addRecentlyUsedFile (const File& file);
  44590. /** Changes the limit for the number of files that will be stored in the recent-file list.
  44591. */
  44592. void setMaxNumberOfRecentFiles (int newMaximum);
  44593. /** Changes the text shown on the 'browse' button.
  44594. By default this button just says "..." but you can change it. The button itself
  44595. can be changed using the look-and-feel classes, so it might not actually have any
  44596. text on it.
  44597. */
  44598. void setBrowseButtonText (const String& browseButtonText);
  44599. /** Adds a listener that will be called when the selected file is changed. */
  44600. void addListener (FilenameComponentListener* listener);
  44601. /** Removes a previously-registered listener. */
  44602. void removeListener (FilenameComponentListener* listener);
  44603. /** Gives the component a tooltip. */
  44604. void setTooltip (const String& newTooltip);
  44605. /** @internal */
  44606. void paintOverChildren (Graphics& g);
  44607. /** @internal */
  44608. void resized();
  44609. /** @internal */
  44610. void lookAndFeelChanged();
  44611. /** @internal */
  44612. bool isInterestedInFileDrag (const StringArray& files);
  44613. /** @internal */
  44614. void filesDropped (const StringArray& files, int, int);
  44615. /** @internal */
  44616. void fileDragEnter (const StringArray& files, int, int);
  44617. /** @internal */
  44618. void fileDragExit (const StringArray& files);
  44619. private:
  44620. ComboBox filenameBox;
  44621. String lastFilename;
  44622. ScopedPointer<Button> browseButton;
  44623. int maxRecentFiles;
  44624. bool isDir, isSaving, isFileDragOver;
  44625. String wildcard, enforcedSuffix, browseButtonText;
  44626. ListenerList <FilenameComponentListener> listeners;
  44627. File defaultBrowseFile;
  44628. void comboBoxChanged (ComboBox*);
  44629. void buttonClicked (Button* button);
  44630. void handleAsyncUpdate();
  44631. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilenameComponent);
  44632. };
  44633. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  44634. /*** End of inlined file: juce_FilenameComponent.h ***/
  44635. #endif
  44636. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  44637. #endif
  44638. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44639. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  44640. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44641. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44642. /**
  44643. Shows a set of file paths in a list, allowing them to be added, removed or
  44644. re-ordered.
  44645. @see FileSearchPath
  44646. */
  44647. class JUCE_API FileSearchPathListComponent : public Component,
  44648. public SettableTooltipClient,
  44649. public FileDragAndDropTarget,
  44650. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  44651. private ListBoxModel
  44652. {
  44653. public:
  44654. /** Creates an empty FileSearchPathListComponent. */
  44655. FileSearchPathListComponent();
  44656. /** Destructor. */
  44657. ~FileSearchPathListComponent();
  44658. /** Returns the path as it is currently shown. */
  44659. const FileSearchPath& getPath() const noexcept { return path; }
  44660. /** Changes the current path. */
  44661. void setPath (const FileSearchPath& newPath);
  44662. /** Sets a file or directory to be the default starting point for the browser to show.
  44663. This is only used if the current file hasn't been set.
  44664. */
  44665. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  44666. /** A set of colour IDs to use to change the colour of various aspects of the label.
  44667. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44668. methods.
  44669. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44670. */
  44671. enum ColourIds
  44672. {
  44673. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  44674. Make this transparent if you don't want the background to be filled. */
  44675. };
  44676. /** @internal */
  44677. int getNumRows();
  44678. /** @internal */
  44679. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  44680. /** @internal */
  44681. void deleteKeyPressed (int lastRowSelected);
  44682. /** @internal */
  44683. void returnKeyPressed (int lastRowSelected);
  44684. /** @internal */
  44685. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  44686. /** @internal */
  44687. void selectedRowsChanged (int lastRowSelected);
  44688. /** @internal */
  44689. void resized();
  44690. /** @internal */
  44691. void paint (Graphics& g);
  44692. /** @internal */
  44693. bool isInterestedInFileDrag (const StringArray& files);
  44694. /** @internal */
  44695. void filesDropped (const StringArray& files, int, int);
  44696. /** @internal */
  44697. void buttonClicked (Button* button);
  44698. private:
  44699. FileSearchPath path;
  44700. File defaultBrowseTarget;
  44701. ListBox listBox;
  44702. TextButton addButton, removeButton, changeButton;
  44703. DrawableButton upButton, downButton;
  44704. void changed();
  44705. void updateButtons();
  44706. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileSearchPathListComponent);
  44707. };
  44708. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  44709. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  44710. #endif
  44711. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44712. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  44713. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44714. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44715. /**
  44716. A component that displays the files in a directory as a treeview.
  44717. This implements the DirectoryContentsDisplayComponent base class so that
  44718. it can be used in a FileBrowserComponent.
  44719. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  44720. class and the FileBrowserListener class.
  44721. @see DirectoryContentsList, FileListComponent
  44722. */
  44723. class JUCE_API FileTreeComponent : public TreeView,
  44724. public DirectoryContentsDisplayComponent
  44725. {
  44726. public:
  44727. /** Creates a listbox to show the contents of a specified directory.
  44728. */
  44729. FileTreeComponent (DirectoryContentsList& listToShow);
  44730. /** Destructor. */
  44731. ~FileTreeComponent();
  44732. /** Returns the number of files the user has got selected.
  44733. @see getSelectedFile
  44734. */
  44735. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  44736. /** Returns one of the files that the user has currently selected.
  44737. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  44738. @see getNumSelectedFiles
  44739. */
  44740. const File getSelectedFile (int index = 0) const;
  44741. /** Deselects any files that are currently selected. */
  44742. void deselectAllFiles();
  44743. /** Scrolls the list to the top. */
  44744. void scrollToTop();
  44745. /** Setting a name for this allows tree items to be dragged.
  44746. The string that you pass in here will be returned by the getDragSourceDescription()
  44747. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  44748. */
  44749. void setDragAndDropDescription (const String& description);
  44750. /** Returns the last value that was set by setDragAndDropDescription().
  44751. */
  44752. const String& getDragAndDropDescription() const noexcept { return dragAndDropDescription; }
  44753. private:
  44754. String dragAndDropDescription;
  44755. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileTreeComponent);
  44756. };
  44757. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  44758. /*** End of inlined file: juce_FileTreeComponent.h ***/
  44759. #endif
  44760. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44761. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  44762. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44763. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44764. /**
  44765. A simple preview component that shows thumbnails of image files.
  44766. @see FileChooserDialogBox, FilePreviewComponent
  44767. */
  44768. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  44769. private Timer
  44770. {
  44771. public:
  44772. /** Creates an ImagePreviewComponent. */
  44773. ImagePreviewComponent();
  44774. /** Destructor. */
  44775. ~ImagePreviewComponent();
  44776. /** @internal */
  44777. void selectedFileChanged (const File& newSelectedFile);
  44778. /** @internal */
  44779. void paint (Graphics& g);
  44780. /** @internal */
  44781. void timerCallback();
  44782. private:
  44783. File fileToLoad;
  44784. Image currentThumbnail;
  44785. String currentDetails;
  44786. void getThumbSize (int& w, int& h) const;
  44787. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImagePreviewComponent);
  44788. };
  44789. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  44790. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  44791. #endif
  44792. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44793. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  44794. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44795. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44796. /**
  44797. A type of FileFilter that works by wildcard pattern matching.
  44798. This filter only allows files that match one of the specified patterns, but
  44799. allows all directories through.
  44800. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  44801. */
  44802. class JUCE_API WildcardFileFilter : public FileFilter
  44803. {
  44804. public:
  44805. /**
  44806. Creates a wildcard filter for one or more patterns.
  44807. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  44808. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  44809. or .aiff.
  44810. Passing an empty string as a pattern will fail to match anything, so by leaving
  44811. either the file or directory pattern parameter empty means you can control
  44812. whether files or directories are found.
  44813. The description is a name to show the user in a list of possible patterns, so
  44814. for the wav/aiff example, your description might be "audio files".
  44815. */
  44816. WildcardFileFilter (const String& fileWildcardPatterns,
  44817. const String& directoryWildcardPatterns,
  44818. const String& description);
  44819. /** Destructor. */
  44820. ~WildcardFileFilter();
  44821. /** Returns true if the filename matches one of the patterns specified. */
  44822. bool isFileSuitable (const File& file) const;
  44823. /** This always returns true. */
  44824. bool isDirectorySuitable (const File& file) const;
  44825. private:
  44826. StringArray fileWildcards, directoryWildcards;
  44827. static void parse (const String& pattern, StringArray& result);
  44828. static bool match (const File& file, const StringArray& wildcards);
  44829. JUCE_LEAK_DETECTOR (WildcardFileFilter);
  44830. };
  44831. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44832. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  44833. #endif
  44834. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  44835. #endif
  44836. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  44837. #endif
  44838. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  44839. #endif
  44840. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  44841. #endif
  44842. #ifndef __JUCE_CARETCOMPONENT_JUCEHEADER__
  44843. #endif
  44844. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  44845. #endif
  44846. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  44847. #endif
  44848. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44849. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  44850. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44851. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44852. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  44853. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44854. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44855. /**
  44856. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  44857. command in a ApplicationCommandManager.
  44858. Normally, you won't actually create a KeyPressMappingSet directly, because
  44859. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  44860. you'd create yourself an ApplicationCommandManager, and call its
  44861. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  44862. KeyPressMappingSet.
  44863. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  44864. to the top-level component for which you want to handle keystrokes. So for example:
  44865. @code
  44866. class MyMainWindow : public Component
  44867. {
  44868. ApplicationCommandManager* myCommandManager;
  44869. public:
  44870. MyMainWindow()
  44871. {
  44872. myCommandManager = new ApplicationCommandManager();
  44873. // first, make sure the command manager has registered all the commands that its
  44874. // targets can perform..
  44875. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  44876. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  44877. // this will use the command manager to initialise the KeyPressMappingSet with
  44878. // the default keypresses that were specified when the targets added their commands
  44879. // to the manager.
  44880. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  44881. // having set up the default key-mappings, you might now want to load the last set
  44882. // of mappings that the user configured.
  44883. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  44884. // Now tell our top-level window to send any keypresses that arrive to the
  44885. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  44886. addKeyListener (myCommandManager->getKeyMappings());
  44887. }
  44888. ...
  44889. }
  44890. @endcode
  44891. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  44892. register to be told when a command or mapping is added, removed, etc.
  44893. There's also a UI component called KeyMappingEditorComponent that can be used
  44894. to easily edit the key mappings.
  44895. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  44896. */
  44897. class JUCE_API KeyPressMappingSet : public KeyListener,
  44898. public ChangeBroadcaster,
  44899. public FocusChangeListener
  44900. {
  44901. public:
  44902. /** Creates a KeyPressMappingSet for a given command manager.
  44903. Normally, you won't actually create a KeyPressMappingSet directly, because
  44904. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  44905. best thing to do is to create your ApplicationCommandManager, and use the
  44906. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  44907. When a suitable keypress happens, the manager's invoke() method will be
  44908. used to invoke the appropriate command.
  44909. @see ApplicationCommandManager
  44910. */
  44911. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  44912. /** Creates an copy of a KeyPressMappingSet. */
  44913. KeyPressMappingSet (const KeyPressMappingSet& other);
  44914. /** Destructor. */
  44915. ~KeyPressMappingSet();
  44916. ApplicationCommandManager* getCommandManager() const noexcept { return commandManager; }
  44917. /** Returns a list of keypresses that are assigned to a particular command.
  44918. @param commandID the command's ID
  44919. */
  44920. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  44921. /** Assigns a keypress to a command.
  44922. If the keypress is already assigned to a different command, it will first be
  44923. removed from that command, to avoid it triggering multiple functions.
  44924. @param commandID the ID of the command that you want to add a keypress to. If
  44925. this is 0, the keypress will be removed from anything that it
  44926. was previously assigned to, but not re-assigned
  44927. @param newKeyPress the new key-press
  44928. @param insertIndex if this is less than zero, the key will be appended to the
  44929. end of the list of keypresses; otherwise the new keypress will
  44930. be inserted into the existing list at this index
  44931. */
  44932. void addKeyPress (CommandID commandID,
  44933. const KeyPress& newKeyPress,
  44934. int insertIndex = -1);
  44935. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  44936. @see resetToDefaultMapping
  44937. */
  44938. void resetToDefaultMappings();
  44939. /** Resets all key-mappings to the defaults for a particular command.
  44940. @see resetToDefaultMappings
  44941. */
  44942. void resetToDefaultMapping (CommandID commandID);
  44943. /** Removes all keypresses that are assigned to any commands. */
  44944. void clearAllKeyPresses();
  44945. /** Removes all keypresses that are assigned to a particular command. */
  44946. void clearAllKeyPresses (CommandID commandID);
  44947. /** Removes one of the keypresses that are assigned to a command.
  44948. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  44949. which the keyPressIndex refers.
  44950. */
  44951. void removeKeyPress (CommandID commandID, int keyPressIndex);
  44952. /** Removes a keypress from any command that it may be assigned to.
  44953. */
  44954. void removeKeyPress (const KeyPress& keypress);
  44955. /** Returns true if the given command is linked to this key. */
  44956. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const noexcept;
  44957. /** Looks for a command that corresponds to a keypress.
  44958. @returns the UID of the command or 0 if none was found
  44959. */
  44960. CommandID findCommandForKeyPress (const KeyPress& keyPress) const noexcept;
  44961. /** Tries to recreate the mappings from a previously stored state.
  44962. The XML passed in must have been created by the createXml() method.
  44963. If the stored state makes any reference to commands that aren't
  44964. currently available, these will be ignored.
  44965. If the set of mappings being loaded was a set of differences (using createXml (true)),
  44966. then this will call resetToDefaultMappings() and then merge the saved mappings
  44967. on top. If the saved set was created with createXml (false), then this method
  44968. will first clear all existing mappings and load the saved ones as a complete set.
  44969. @returns true if it manages to load the XML correctly
  44970. @see createXml
  44971. */
  44972. bool restoreFromXml (const XmlElement& xmlVersion);
  44973. /** Creates an XML representation of the current mappings.
  44974. This will produce a lump of XML that can be later reloaded using
  44975. restoreFromXml() to recreate the current mapping state.
  44976. The object that is returned must be deleted by the caller.
  44977. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  44978. will be saved into the XML. If it's true, then the XML will
  44979. only store the differences between the current mappings and
  44980. the default mappings you'd get from calling resetToDefaultMappings().
  44981. The advantage of saving a set of differences from the default is that
  44982. if you change the default mappings (in a new version of your app, for
  44983. example), then these will be merged into a user's saved preferences.
  44984. @see restoreFromXml
  44985. */
  44986. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  44987. /** @internal */
  44988. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  44989. /** @internal */
  44990. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  44991. /** @internal */
  44992. void globalFocusChanged (Component* focusedComponent);
  44993. private:
  44994. ApplicationCommandManager* commandManager;
  44995. struct CommandMapping
  44996. {
  44997. CommandID commandID;
  44998. Array <KeyPress> keypresses;
  44999. bool wantsKeyUpDownCallbacks;
  45000. };
  45001. OwnedArray <CommandMapping> mappings;
  45002. struct KeyPressTime
  45003. {
  45004. KeyPress key;
  45005. uint32 timeWhenPressed;
  45006. };
  45007. OwnedArray <KeyPressTime> keysDown;
  45008. void handleMessage (const Message& message);
  45009. void invokeCommand (const CommandID commandID,
  45010. const KeyPress& keyPress,
  45011. const bool isKeyDown,
  45012. const int millisecsSinceKeyPressed,
  45013. Component* const originatingComponent) const;
  45014. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  45015. JUCE_LEAK_DETECTOR (KeyPressMappingSet);
  45016. };
  45017. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  45018. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  45019. /**
  45020. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  45021. object.
  45022. @see KeyPressMappingSet
  45023. */
  45024. class JUCE_API KeyMappingEditorComponent : public Component
  45025. {
  45026. public:
  45027. /** Creates a KeyMappingEditorComponent.
  45028. @param mappingSet this is the set of mappings to display and edit. Make sure the
  45029. mappings object is not deleted before this component!
  45030. @param showResetToDefaultButton if true, then at the bottom of the list, the
  45031. component will include a 'reset to defaults' button.
  45032. */
  45033. KeyMappingEditorComponent (KeyPressMappingSet& mappingSet,
  45034. bool showResetToDefaultButton);
  45035. /** Destructor. */
  45036. virtual ~KeyMappingEditorComponent();
  45037. /** Sets up the colours to use for parts of the component.
  45038. @param mainBackground colour to use for most of the background
  45039. @param textColour colour to use for the text
  45040. */
  45041. void setColours (const Colour& mainBackground,
  45042. const Colour& textColour);
  45043. /** Returns the KeyPressMappingSet that this component is acting upon. */
  45044. KeyPressMappingSet& getMappings() const noexcept { return mappings; }
  45045. /** Can be overridden if some commands need to be excluded from the list.
  45046. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  45047. method to decide what to return, but you can override it to handle special cases.
  45048. */
  45049. virtual bool shouldCommandBeIncluded (CommandID commandID);
  45050. /** Can be overridden to indicate that some commands are shown as read-only.
  45051. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  45052. method to decide what to return, but you can override it to handle special cases.
  45053. */
  45054. virtual bool isCommandReadOnly (CommandID commandID);
  45055. /** This can be overridden to let you change the format of the string used
  45056. to describe a keypress.
  45057. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  45058. keys that are triggered by something else externally. If you override the
  45059. method, be sure to let the base class's method handle keys you're not
  45060. interested in.
  45061. */
  45062. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  45063. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  45064. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45065. methods.
  45066. To change the colours of the menu that pops up
  45067. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45068. */
  45069. enum ColourIds
  45070. {
  45071. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  45072. textColourId = 0x100ad01, /**< The colour for the text. */
  45073. };
  45074. /** @internal */
  45075. void parentHierarchyChanged();
  45076. /** @internal */
  45077. void resized();
  45078. private:
  45079. KeyPressMappingSet& mappings;
  45080. TreeView tree;
  45081. TextButton resetButton;
  45082. class TopLevelItem;
  45083. class ChangeKeyButton;
  45084. class MappingItem;
  45085. class CategoryItem;
  45086. class ItemComponent;
  45087. friend class TopLevelItem;
  45088. friend class OwnedArray <ChangeKeyButton>;
  45089. friend class ScopedPointer<TopLevelItem>;
  45090. ScopedPointer<TopLevelItem> treeItem;
  45091. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KeyMappingEditorComponent);
  45092. };
  45093. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  45094. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  45095. #endif
  45096. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  45097. #endif
  45098. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  45099. #endif
  45100. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  45101. #endif
  45102. #ifndef __JUCE_TEXTEDITORKEYMAPPER_JUCEHEADER__
  45103. /*** Start of inlined file: juce_TextEditorKeyMapper.h ***/
  45104. #ifndef __JUCE_TEXTEDITORKEYMAPPER_JUCEHEADER__
  45105. #define __JUCE_TEXTEDITORKEYMAPPER_JUCEHEADER__
  45106. /** This class is used to invoke a range of text-editor navigation methods on
  45107. an object, based upon a keypress event.
  45108. It's currently used internally by the TextEditor and CodeEditorComponent.
  45109. */
  45110. template <class CallbackClass>
  45111. struct TextEditorKeyMapper
  45112. {
  45113. /** Checks the keypress and invokes one of a range of navigation functions that
  45114. the target class must implement, based on the key event.
  45115. */
  45116. static bool invokeKeyFunction (CallbackClass& target, const KeyPress& key)
  45117. {
  45118. const bool isShiftDown = key.getModifiers().isShiftDown();
  45119. const bool ctrlOrAltDown = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  45120. if (key == KeyPress (KeyPress::downKey, ModifierKeys::ctrlModifier, 0)
  45121. && target.scrollUp())
  45122. return true;
  45123. if (key == KeyPress (KeyPress::upKey, ModifierKeys::ctrlModifier, 0)
  45124. && target.scrollDown())
  45125. return true;
  45126. #if JUCE_MAC
  45127. if (key.getModifiers().isCommandDown())
  45128. {
  45129. if (key.isKeyCode (KeyPress::upKey))
  45130. return target.moveCaretToTop (isShiftDown);
  45131. if (key.isKeyCode (KeyPress::downKey))
  45132. return target.moveCaretToEnd (isShiftDown);
  45133. if (key.isKeyCode (KeyPress::leftKey))
  45134. return target.moveCaretToStartOfLine (isShiftDown);
  45135. if (key.isKeyCode (KeyPress::rightKey))
  45136. return target.moveCaretToEndOfLine (isShiftDown);
  45137. }
  45138. #endif
  45139. if (key.isKeyCode (KeyPress::upKey))
  45140. return target.moveCaretUp (isShiftDown);
  45141. if (key.isKeyCode (KeyPress::downKey))
  45142. return target.moveCaretDown (isShiftDown);
  45143. if (key.isKeyCode (KeyPress::leftKey))
  45144. return target.moveCaretLeft (ctrlOrAltDown, isShiftDown);
  45145. if (key.isKeyCode (KeyPress::rightKey))
  45146. return target.moveCaretRight (ctrlOrAltDown, isShiftDown);
  45147. if (key.isKeyCode (KeyPress::pageUpKey))
  45148. return target.pageUp (isShiftDown);
  45149. if (key.isKeyCode (KeyPress::pageDownKey))
  45150. return target.pageDown (isShiftDown);
  45151. if (key.isKeyCode (KeyPress::homeKey))
  45152. return ctrlOrAltDown ? target.moveCaretToTop (isShiftDown)
  45153. : target.moveCaretToStartOfLine (isShiftDown);
  45154. if (key.isKeyCode (KeyPress::endKey))
  45155. return ctrlOrAltDown ? target.moveCaretToEnd (isShiftDown)
  45156. : target.moveCaretToEndOfLine (isShiftDown);
  45157. if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  45158. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  45159. return target.copyToClipboard();
  45160. if (key == KeyPress ('x', ModifierKeys::commandModifier, 0)
  45161. || key == KeyPress (KeyPress::deleteKey, ModifierKeys::shiftModifier, 0))
  45162. return target.cutToClipboard();
  45163. if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  45164. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  45165. return target.pasteFromClipboard();
  45166. if (key.isKeyCode (KeyPress::backspaceKey))
  45167. return target.deleteBackwards (ctrlOrAltDown);
  45168. if (key.isKeyCode (KeyPress::deleteKey))
  45169. return target.deleteForwards (ctrlOrAltDown);
  45170. if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  45171. return target.selectAll();
  45172. if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  45173. return target.undo();
  45174. if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  45175. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  45176. return target.redo();
  45177. return false;
  45178. }
  45179. };
  45180. #endif // __JUCE_TEXTEDITORKEYMAPPER_JUCEHEADER__
  45181. /*** End of inlined file: juce_TextEditorKeyMapper.h ***/
  45182. #endif
  45183. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  45184. #endif
  45185. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  45186. #endif
  45187. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  45188. #endif
  45189. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  45190. #endif
  45191. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  45192. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  45193. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  45194. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  45195. /** An object that watches for any movement of a component or any of its parent components.
  45196. This makes it easy to check when a component is moved relative to its top-level
  45197. peer window. The normal Component::moved() method is only called when a component
  45198. moves relative to its immediate parent, and sometimes you want to know if any of
  45199. components higher up the tree have moved (which of course will affect the overall
  45200. position of all their sub-components).
  45201. It also includes a callback that lets you know when the top-level peer is changed.
  45202. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  45203. because they need to keep their custom windows in the right place and respond to
  45204. changes in the peer.
  45205. */
  45206. class JUCE_API ComponentMovementWatcher : public ComponentListener
  45207. {
  45208. public:
  45209. /** Creates a ComponentMovementWatcher to watch a given target component. */
  45210. ComponentMovementWatcher (Component* component);
  45211. /** Destructor. */
  45212. ~ComponentMovementWatcher();
  45213. /** This callback happens when the component that is being watched is moved
  45214. relative to its top-level peer window, or when it is resized. */
  45215. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  45216. /** This callback happens when the component's top-level peer is changed. */
  45217. virtual void componentPeerChanged() = 0;
  45218. /** This callback happens when the component's visibility state changes, possibly due to
  45219. one of its parents being made visible or invisible.
  45220. */
  45221. virtual void componentVisibilityChanged() = 0;
  45222. /** @internal */
  45223. void componentParentHierarchyChanged (Component& component);
  45224. /** @internal */
  45225. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  45226. /** @internal */
  45227. void componentBeingDeleted (Component& component);
  45228. /** @internal */
  45229. void componentVisibilityChanged (Component& component);
  45230. private:
  45231. WeakReference<Component> component;
  45232. uint32 lastPeerID;
  45233. Array <Component*> registeredParentComps;
  45234. bool reentrant, wasShowing;
  45235. Rectangle<int> lastBounds;
  45236. void unregister();
  45237. void registerWithParentComps();
  45238. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentMovementWatcher);
  45239. };
  45240. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  45241. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  45242. #endif
  45243. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  45244. /*** Start of inlined file: juce_GroupComponent.h ***/
  45245. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  45246. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  45247. /**
  45248. A component that draws an outline around itself and has an optional title at
  45249. the top, for drawing an outline around a group of controls.
  45250. */
  45251. class JUCE_API GroupComponent : public Component
  45252. {
  45253. public:
  45254. /** Creates a GroupComponent.
  45255. @param componentName the name to give the component
  45256. @param labelText the text to show at the top of the outline
  45257. */
  45258. GroupComponent (const String& componentName = String::empty,
  45259. const String& labelText = String::empty);
  45260. /** Destructor. */
  45261. ~GroupComponent();
  45262. /** Changes the text that's shown at the top of the component. */
  45263. void setText (const String& newText);
  45264. /** Returns the currently displayed text label. */
  45265. String getText() const;
  45266. /** Sets the positioning of the text label.
  45267. (The default is Justification::left)
  45268. @see getTextLabelPosition
  45269. */
  45270. void setTextLabelPosition (const Justification& justification);
  45271. /** Returns the current text label position.
  45272. @see setTextLabelPosition
  45273. */
  45274. const Justification getTextLabelPosition() const noexcept { return justification; }
  45275. /** A set of colour IDs to use to change the colour of various aspects of the component.
  45276. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45277. methods.
  45278. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45279. */
  45280. enum ColourIds
  45281. {
  45282. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  45283. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  45284. };
  45285. /** @internal */
  45286. void paint (Graphics& g);
  45287. /** @internal */
  45288. void enablementChanged();
  45289. /** @internal */
  45290. void colourChanged();
  45291. private:
  45292. String text;
  45293. Justification justification;
  45294. JUCE_DECLARE_NON_COPYABLE (GroupComponent);
  45295. };
  45296. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  45297. /*** End of inlined file: juce_GroupComponent.h ***/
  45298. #endif
  45299. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  45300. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  45301. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  45302. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  45303. /*** Start of inlined file: juce_TabbedComponent.h ***/
  45304. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  45305. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  45306. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  45307. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  45308. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  45309. class TabbedButtonBar;
  45310. /** In a TabbedButtonBar, this component is used for each of the buttons.
  45311. If you want to create a TabbedButtonBar with custom tab components, derive
  45312. your component from this class, and override the TabbedButtonBar::createTabButton()
  45313. method to create it instead of the default one.
  45314. @see TabbedButtonBar
  45315. */
  45316. class JUCE_API TabBarButton : public Button
  45317. {
  45318. public:
  45319. /** Creates the tab button. */
  45320. TabBarButton (const String& name, TabbedButtonBar& ownerBar);
  45321. /** Destructor. */
  45322. ~TabBarButton();
  45323. /** Chooses the best length for the tab, given the specified depth.
  45324. If the tab is horizontal, this should return its width, and the depth
  45325. specifies its height. If it's vertical, it should return the height, and
  45326. the depth is actually its width.
  45327. */
  45328. virtual int getBestTabLength (int depth);
  45329. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  45330. void clicked (const ModifierKeys& mods);
  45331. bool hitTest (int x, int y);
  45332. protected:
  45333. friend class TabbedButtonBar;
  45334. TabbedButtonBar& owner;
  45335. int overlapPixels;
  45336. DropShadowEffect shadow;
  45337. /** Returns an area of the component that's safe to draw in.
  45338. This deals with the orientation of the tabs, which affects which side is
  45339. touching the tabbed box's content component.
  45340. */
  45341. const Rectangle<int> getActiveArea();
  45342. /** Returns this tab's index in its tab bar. */
  45343. int getIndex() const;
  45344. private:
  45345. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabBarButton);
  45346. };
  45347. /**
  45348. A vertical or horizontal bar containing tabs that you can select.
  45349. You can use one of these to generate things like a dialog box that has
  45350. tabbed pages you can flip between. Attach a ChangeListener to the
  45351. button bar to be told when the user changes the page.
  45352. An easier method than doing this is to use a TabbedComponent, which
  45353. contains its own TabbedButtonBar and which takes care of the layout
  45354. and other housekeeping.
  45355. @see TabbedComponent
  45356. */
  45357. class JUCE_API TabbedButtonBar : public Component,
  45358. public ChangeBroadcaster
  45359. {
  45360. public:
  45361. /** The placement of the tab-bar
  45362. @see setOrientation, getOrientation
  45363. */
  45364. enum Orientation
  45365. {
  45366. TabsAtTop,
  45367. TabsAtBottom,
  45368. TabsAtLeft,
  45369. TabsAtRight
  45370. };
  45371. /** Creates a TabbedButtonBar with a given placement.
  45372. You can change the orientation later if you need to.
  45373. */
  45374. TabbedButtonBar (Orientation orientation);
  45375. /** Destructor. */
  45376. ~TabbedButtonBar();
  45377. /** Changes the bar's orientation.
  45378. This won't change the bar's actual size - you'll need to do that yourself,
  45379. but this determines which direction the tabs go in, and which side they're
  45380. stuck to.
  45381. */
  45382. void setOrientation (Orientation orientation);
  45383. /** Returns the current orientation.
  45384. @see setOrientation
  45385. */
  45386. Orientation getOrientation() const noexcept { return orientation; }
  45387. /** Changes the minimum scale factor to which the tabs can be compressed when trying to
  45388. fit a lot of tabs on-screen.
  45389. */
  45390. void setMinimumTabScaleFactor (double newMinimumScale);
  45391. /** Deletes all the tabs from the bar.
  45392. @see addTab
  45393. */
  45394. void clearTabs();
  45395. /** Adds a tab to the bar.
  45396. Tabs are added in left-to-right reading order.
  45397. If this is the first tab added, it'll also be automatically selected.
  45398. */
  45399. void addTab (const String& tabName,
  45400. const Colour& tabBackgroundColour,
  45401. int insertIndex = -1);
  45402. /** Changes the name of one of the tabs. */
  45403. void setTabName (int tabIndex,
  45404. const String& newName);
  45405. /** Gets rid of one of the tabs. */
  45406. void removeTab (int tabIndex);
  45407. /** Moves a tab to a new index in the list.
  45408. Pass -1 as the index to move it to the end of the list.
  45409. */
  45410. void moveTab (int currentIndex, int newIndex);
  45411. /** Returns the number of tabs in the bar. */
  45412. int getNumTabs() const;
  45413. /** Returns a list of all the tab names in the bar. */
  45414. StringArray getTabNames() const;
  45415. /** Changes the currently selected tab.
  45416. This will send a change message and cause a synchronous callback to
  45417. the currentTabChanged() method. (But if the given tab is already selected,
  45418. nothing will be done).
  45419. To deselect all the tabs, use an index of -1.
  45420. */
  45421. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  45422. /** Returns the name of the currently selected tab.
  45423. This could be an empty string if none are selected.
  45424. */
  45425. String getCurrentTabName() const;
  45426. /** Returns the index of the currently selected tab.
  45427. This could return -1 if none are selected.
  45428. */
  45429. int getCurrentTabIndex() const noexcept { return currentTabIndex; }
  45430. /** Returns the button for a specific tab.
  45431. The button that is returned may be deleted later by this component, so don't hang
  45432. on to the pointer that is returned. A null pointer may be returned if the index is
  45433. out of range.
  45434. */
  45435. TabBarButton* getTabButton (int index) const;
  45436. /** Returns the index of a TabBarButton if it belongs to this bar. */
  45437. int indexOfTabButton (const TabBarButton* button) const;
  45438. /** Callback method to indicate the selected tab has been changed.
  45439. @see setCurrentTabIndex
  45440. */
  45441. virtual void currentTabChanged (int newCurrentTabIndex,
  45442. const String& newCurrentTabName);
  45443. /** Callback method to indicate that the user has right-clicked on a tab.
  45444. (Or ctrl-clicked on the Mac)
  45445. */
  45446. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  45447. /** Returns the colour of a tab.
  45448. This is the colour that was specified in addTab().
  45449. */
  45450. const Colour getTabBackgroundColour (int tabIndex);
  45451. /** Changes the background colour of a tab.
  45452. @see addTab, getTabBackgroundColour
  45453. */
  45454. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  45455. /** A set of colour IDs to use to change the colour of various aspects of the component.
  45456. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45457. methods.
  45458. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45459. */
  45460. enum ColourIds
  45461. {
  45462. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  45463. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  45464. the look and feel will choose an appropriate colour. */
  45465. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  45466. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  45467. this isn't specified, the look and feel will choose an appropriate
  45468. colour. */
  45469. };
  45470. /** @internal */
  45471. void resized();
  45472. /** @internal */
  45473. void lookAndFeelChanged();
  45474. protected:
  45475. /** This creates one of the tabs.
  45476. If you need to use custom tab components, you can override this method and
  45477. return your own class instead of the default.
  45478. */
  45479. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  45480. private:
  45481. Orientation orientation;
  45482. struct TabInfo
  45483. {
  45484. ScopedPointer<TabBarButton> component;
  45485. String name;
  45486. Colour colour;
  45487. };
  45488. OwnedArray <TabInfo> tabs;
  45489. double minimumScale;
  45490. int currentTabIndex;
  45491. class BehindFrontTabComp;
  45492. friend class BehindFrontTabComp;
  45493. friend class ScopedPointer<BehindFrontTabComp>;
  45494. ScopedPointer<BehindFrontTabComp> behindFrontTab;
  45495. ScopedPointer<Button> extraTabsButton;
  45496. void showExtraItemsMenu();
  45497. static void extraItemsMenuCallback (int, TabbedButtonBar*);
  45498. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedButtonBar);
  45499. };
  45500. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  45501. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  45502. /**
  45503. A component with a TabbedButtonBar along one of its sides.
  45504. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  45505. with addTab(), and this will take care of showing the pages for you when the
  45506. user clicks on a different tab.
  45507. @see TabbedButtonBar
  45508. */
  45509. class JUCE_API TabbedComponent : public Component
  45510. {
  45511. public:
  45512. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  45513. Once created, add some tabs with the addTab() method.
  45514. */
  45515. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  45516. /** Destructor. */
  45517. ~TabbedComponent();
  45518. /** Changes the placement of the tabs.
  45519. This will rearrange the layout to place the tabs along the appropriate
  45520. side of this component, and will shift the content component accordingly.
  45521. @see TabbedButtonBar::setOrientation
  45522. */
  45523. void setOrientation (TabbedButtonBar::Orientation orientation);
  45524. /** Returns the current tab placement.
  45525. @see setOrientation, TabbedButtonBar::getOrientation
  45526. */
  45527. TabbedButtonBar::Orientation getOrientation() const noexcept;
  45528. /** Specifies how many pixels wide or high the tab-bar should be.
  45529. If the tabs are placed along the top or bottom, this specified the height
  45530. of the bar; if they're along the left or right edges, it'll be the width
  45531. of the bar.
  45532. */
  45533. void setTabBarDepth (int newDepth);
  45534. /** Returns the current thickness of the tab bar.
  45535. @see setTabBarDepth
  45536. */
  45537. int getTabBarDepth() const noexcept { return tabDepth; }
  45538. /** Specifies the thickness of an outline that should be drawn around the content component.
  45539. If this thickness is > 0, a line will be drawn around the three sides of the content
  45540. component which don't touch the tab-bar, and the content component will be inset by this amount.
  45541. To set the colour of the line, use setColour (outlineColourId, ...).
  45542. */
  45543. void setOutline (int newThickness);
  45544. /** Specifies a gap to leave around the edge of the content component.
  45545. Each edge of the content component will be indented by the given number of pixels.
  45546. */
  45547. void setIndent (int indentThickness);
  45548. /** Removes all the tabs from the bar.
  45549. @see TabbedButtonBar::clearTabs
  45550. */
  45551. void clearTabs();
  45552. /** Adds a tab to the tab-bar.
  45553. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  45554. is true, it will be deleted when the tab is removed or when this object is
  45555. deleted.
  45556. @see TabbedButtonBar::addTab
  45557. */
  45558. void addTab (const String& tabName,
  45559. const Colour& tabBackgroundColour,
  45560. Component* contentComponent,
  45561. bool deleteComponentWhenNotNeeded,
  45562. int insertIndex = -1);
  45563. /** Changes the name of one of the tabs. */
  45564. void setTabName (int tabIndex, const String& newName);
  45565. /** Gets rid of one of the tabs. */
  45566. void removeTab (int tabIndex);
  45567. /** Returns the number of tabs in the bar. */
  45568. int getNumTabs() const;
  45569. /** Returns a list of all the tab names in the bar. */
  45570. StringArray getTabNames() const;
  45571. /** Returns the content component that was added for the given index.
  45572. Be sure not to use or delete the components that are returned, as this may interfere
  45573. with the TabbedComponent's use of them.
  45574. */
  45575. Component* getTabContentComponent (int tabIndex) const noexcept;
  45576. /** Returns the colour of one of the tabs. */
  45577. const Colour getTabBackgroundColour (int tabIndex) const noexcept;
  45578. /** Changes the background colour of one of the tabs. */
  45579. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  45580. /** Changes the currently-selected tab.
  45581. To deselect all the tabs, pass -1 as the index.
  45582. @see TabbedButtonBar::setCurrentTabIndex
  45583. */
  45584. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  45585. /** Returns the index of the currently selected tab.
  45586. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  45587. */
  45588. int getCurrentTabIndex() const;
  45589. /** Returns the name of the currently selected tab.
  45590. @see addTab, TabbedButtonBar::getCurrentTabName()
  45591. */
  45592. String getCurrentTabName() const;
  45593. /** Returns the current component that's filling the panel.
  45594. This will return 0 if there isn't one.
  45595. */
  45596. Component* getCurrentContentComponent() const noexcept { return panelComponent; }
  45597. /** Callback method to indicate the selected tab has been changed.
  45598. @see setCurrentTabIndex
  45599. */
  45600. virtual void currentTabChanged (int newCurrentTabIndex,
  45601. const String& newCurrentTabName);
  45602. /** Callback method to indicate that the user has right-clicked on a tab.
  45603. (Or ctrl-clicked on the Mac)
  45604. */
  45605. virtual void popupMenuClickOnTab (int tabIndex,
  45606. const String& tabName);
  45607. /** Returns the tab button bar component that is being used.
  45608. */
  45609. TabbedButtonBar& getTabbedButtonBar() const noexcept { return *tabs; }
  45610. /** A set of colour IDs to use to change the colour of various aspects of the component.
  45611. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45612. methods.
  45613. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45614. */
  45615. enum ColourIds
  45616. {
  45617. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  45618. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  45619. (See setOutline) */
  45620. };
  45621. /** @internal */
  45622. void paint (Graphics& g);
  45623. /** @internal */
  45624. void resized();
  45625. /** @internal */
  45626. void lookAndFeelChanged();
  45627. protected:
  45628. /** This creates one of the tab buttons.
  45629. If you need to use custom tab components, you can override this method and
  45630. return your own class instead of the default.
  45631. */
  45632. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  45633. /** @internal */
  45634. ScopedPointer<TabbedButtonBar> tabs;
  45635. private:
  45636. Array <WeakReference<Component> > contentComponents;
  45637. WeakReference<Component> panelComponent;
  45638. int tabDepth;
  45639. int outlineThickness, edgeIndent;
  45640. class ButtonBar;
  45641. friend class ButtonBar;
  45642. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  45643. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedComponent);
  45644. };
  45645. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  45646. /*** End of inlined file: juce_TabbedComponent.h ***/
  45647. /*** Start of inlined file: juce_DocumentWindow.h ***/
  45648. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  45649. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  45650. /*** Start of inlined file: juce_MenuBarModel.h ***/
  45651. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  45652. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  45653. /**
  45654. A class for controlling MenuBar components.
  45655. This class is used to tell a MenuBar what menus to show, and to respond
  45656. to a menu being selected.
  45657. @see MenuBarModel::Listener, MenuBarComponent, PopupMenu
  45658. */
  45659. class JUCE_API MenuBarModel : private AsyncUpdater,
  45660. private ApplicationCommandManagerListener
  45661. {
  45662. public:
  45663. MenuBarModel() noexcept;
  45664. /** Destructor. */
  45665. virtual ~MenuBarModel();
  45666. /** Call this when some of your menu items have changed.
  45667. This method will cause a callback to any MenuBarListener objects that
  45668. are registered with this model.
  45669. If this model is displaying items from an ApplicationCommandManager, you
  45670. can use the setApplicationCommandManagerToWatch() method to cause
  45671. change messages to be sent automatically when the ApplicationCommandManager
  45672. is changed.
  45673. @see addListener, removeListener, MenuBarListener
  45674. */
  45675. void menuItemsChanged();
  45676. /** Tells the menu bar to listen to the specified command manager, and to update
  45677. itself when the commands change.
  45678. This will also allow it to flash a menu name when a command from that menu
  45679. is invoked using a keystroke.
  45680. */
  45681. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) noexcept;
  45682. /** A class to receive callbacks when a MenuBarModel changes.
  45683. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  45684. */
  45685. class JUCE_API Listener
  45686. {
  45687. public:
  45688. /** Destructor. */
  45689. virtual ~Listener() {}
  45690. /** This callback is made when items are changed in the menu bar model.
  45691. */
  45692. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  45693. /** This callback is made when an application command is invoked that
  45694. is represented by one of the items in the menu bar model.
  45695. */
  45696. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  45697. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  45698. };
  45699. /** Registers a listener for callbacks when the menu items in this model change.
  45700. The listener object will get callbacks when this object's menuItemsChanged()
  45701. method is called.
  45702. @see removeListener
  45703. */
  45704. void addListener (Listener* listenerToAdd) noexcept;
  45705. /** Removes a listener.
  45706. @see addListener
  45707. */
  45708. void removeListener (Listener* listenerToRemove) noexcept;
  45709. /** This method must return a list of the names of the menus. */
  45710. virtual const StringArray getMenuBarNames() = 0;
  45711. /** This should return the popup menu to display for a given top-level menu.
  45712. @param topLevelMenuIndex the index of the top-level menu to show
  45713. @param menuName the name of the top-level menu item to show
  45714. */
  45715. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  45716. const String& menuName) = 0;
  45717. /** This is called when a menu item has been clicked on.
  45718. @param menuItemID the item ID of the PopupMenu item that was selected
  45719. @param topLevelMenuIndex the index of the top-level menu from which the item was
  45720. chosen (just in case you've used duplicate ID numbers
  45721. on more than one of the popup menus)
  45722. */
  45723. virtual void menuItemSelected (int menuItemID,
  45724. int topLevelMenuIndex) = 0;
  45725. #if JUCE_MAC || DOXYGEN
  45726. /** MAC ONLY - Sets the model that is currently being shown as the main
  45727. menu bar at the top of the screen on the Mac.
  45728. You can pass 0 to stop the current model being displayed. Be careful
  45729. not to delete a model while it is being used.
  45730. An optional extra menu can be specified, containing items to add to the top of
  45731. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  45732. an apple, it's the one next to it, with your application's name at the top
  45733. and the services menu etc on it). When one of these items is selected, the
  45734. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  45735. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  45736. object then newMenuBarModel must be non-null.
  45737. */
  45738. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  45739. const PopupMenu* extraAppleMenuItems = nullptr);
  45740. /** MAC ONLY - Returns the menu model that is currently being shown as
  45741. the main menu bar.
  45742. */
  45743. static MenuBarModel* getMacMainMenu();
  45744. #endif
  45745. /** @internal */
  45746. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  45747. /** @internal */
  45748. void applicationCommandListChanged();
  45749. /** @internal */
  45750. void handleAsyncUpdate();
  45751. private:
  45752. ApplicationCommandManager* manager;
  45753. ListenerList <Listener> listeners;
  45754. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarModel);
  45755. };
  45756. /** This typedef is just for compatibility with old code - newer code should use the MenuBarModel::Listener class directly. */
  45757. typedef MenuBarModel::Listener MenuBarModelListener;
  45758. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  45759. /*** End of inlined file: juce_MenuBarModel.h ***/
  45760. /**
  45761. A resizable window with a title bar and maximise, minimise and close buttons.
  45762. This subclass of ResizableWindow creates a fairly standard type of window with
  45763. a title bar and various buttons. The name of the component is shown in the
  45764. title bar, and an icon can optionally be specified with setIcon().
  45765. All the methods available to a ResizableWindow are also available to this,
  45766. so it can easily be made resizable, minimised, maximised, etc.
  45767. It's not advisable to add child components directly to a DocumentWindow: put them
  45768. inside your content component instead. And overriding methods like resized(), moved(), etc
  45769. is also not recommended - instead override these methods for your content component.
  45770. (If for some obscure reason you do need to override these methods, always remember to
  45771. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  45772. decorations correctly).
  45773. You can also automatically add a menu bar to the window, using the setMenuBar()
  45774. method.
  45775. @see ResizableWindow, DialogWindow
  45776. */
  45777. class JUCE_API DocumentWindow : public ResizableWindow
  45778. {
  45779. public:
  45780. /** The set of available button-types that can be put on the title bar.
  45781. @see setTitleBarButtonsRequired
  45782. */
  45783. enum TitleBarButtons
  45784. {
  45785. minimiseButton = 1,
  45786. maximiseButton = 2,
  45787. closeButton = 4,
  45788. /** A combination of all the buttons above. */
  45789. allButtons = 7
  45790. };
  45791. /** Creates a DocumentWindow.
  45792. @param name the name to give the component - this is also
  45793. the title shown at the top of the window. To change
  45794. this later, use setName()
  45795. @param backgroundColour the colour to use for filling the window's background.
  45796. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  45797. should be shown on the title bar. This value is a bitwise
  45798. combination of values from the TitleBarButtons enum. Note
  45799. that it can be "allButtons" to get them all. You
  45800. can change this later with the setTitleBarButtonsRequired()
  45801. method, which can also specify where they are positioned.
  45802. @param addToDesktop if true, the window will be automatically added to the
  45803. desktop; if false, you can use it as a child component
  45804. @see TitleBarButtons
  45805. */
  45806. DocumentWindow (const String& name,
  45807. const Colour& backgroundColour,
  45808. int requiredButtons,
  45809. bool addToDesktop = true);
  45810. /** Destructor.
  45811. If a content component has been set with setContentOwned(), it will be deleted.
  45812. */
  45813. ~DocumentWindow();
  45814. /** Changes the component's name.
  45815. (This is overridden from Component::setName() to cause a repaint, as
  45816. the name is what gets drawn across the window's title bar).
  45817. */
  45818. void setName (const String& newName);
  45819. /** Sets an icon to show in the title bar, next to the title.
  45820. A copy is made internally of the image, so the caller can delete the
  45821. image after calling this. If 0 is passed-in, any existing icon will be
  45822. removed.
  45823. */
  45824. void setIcon (const Image& imageToUse);
  45825. /** Changes the height of the title-bar. */
  45826. void setTitleBarHeight (int newHeight);
  45827. /** Returns the current title bar height. */
  45828. int getTitleBarHeight() const;
  45829. /** Changes the set of title-bar buttons being shown.
  45830. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  45831. should be shown on the title bar. This value is a bitwise
  45832. combination of values from the TitleBarButtons enum. Note
  45833. that it can be "allButtons" to get them all.
  45834. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  45835. left side of the bar; if false, they'll be placed at the right
  45836. */
  45837. void setTitleBarButtonsRequired (int requiredButtons,
  45838. bool positionTitleBarButtonsOnLeft);
  45839. /** Sets whether the title should be centred within the window.
  45840. If true, the title text is shown in the middle of the title-bar; if false,
  45841. it'll be shown at the left of the bar.
  45842. */
  45843. void setTitleBarTextCentred (bool textShouldBeCentred);
  45844. /** Creates a menu inside this window.
  45845. @param menuBarModel this specifies a MenuBarModel that should be used to
  45846. generate the contents of a menu bar that will be placed
  45847. just below the title bar, and just above any content
  45848. component. If this value is zero, any existing menu bar
  45849. will be removed from the component; if non-zero, one will
  45850. be added if it's required.
  45851. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  45852. or less to use the look-and-feel's default size.
  45853. */
  45854. void setMenuBar (MenuBarModel* menuBarModel,
  45855. int menuBarHeight = 0);
  45856. /** Returns the current menu bar component, or null if there isn't one.
  45857. This is probably a MenuBarComponent, unless a custom one has been set using
  45858. setMenuBarComponent().
  45859. */
  45860. Component* getMenuBarComponent() const noexcept;
  45861. /** Replaces the current menu bar with a custom component.
  45862. The component will be owned and deleted by the document window.
  45863. */
  45864. void setMenuBarComponent (Component* newMenuBarComponent);
  45865. /** This method is called when the user tries to close the window.
  45866. This is triggered by the user clicking the close button, or using some other
  45867. OS-specific key shortcut or OS menu for getting rid of a window.
  45868. If the window is just a pop-up, you should override this closeButtonPressed()
  45869. method and make it delete the window in whatever way is appropriate for your
  45870. app. E.g. you might just want to call "delete this".
  45871. If your app is centred around this window such that the whole app should quit when
  45872. the window is closed, then you will probably want to use this method as an opportunity
  45873. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  45874. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  45875. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  45876. or closing it via the taskbar icon on Windows).
  45877. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  45878. redirects it to call this method, so any methods of closing the window that are
  45879. caught by userTriedToCloseWindow() will also end up here).
  45880. */
  45881. virtual void closeButtonPressed();
  45882. /** Callback that is triggered when the minimise button is pressed.
  45883. The default implementation of this calls ResizableWindow::setMinimised(), but
  45884. you can override it to do more customised behaviour.
  45885. */
  45886. virtual void minimiseButtonPressed();
  45887. /** Callback that is triggered when the maximise button is pressed, or when the
  45888. title-bar is double-clicked.
  45889. The default implementation of this calls ResizableWindow::setFullScreen(), but
  45890. you can override it to do more customised behaviour.
  45891. */
  45892. virtual void maximiseButtonPressed();
  45893. /** Returns the close button, (or 0 if there isn't one). */
  45894. Button* getCloseButton() const noexcept;
  45895. /** Returns the minimise button, (or 0 if there isn't one). */
  45896. Button* getMinimiseButton() const noexcept;
  45897. /** Returns the maximise button, (or 0 if there isn't one). */
  45898. Button* getMaximiseButton() const noexcept;
  45899. /** A set of colour IDs to use to change the colour of various aspects of the window.
  45900. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45901. methods.
  45902. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45903. */
  45904. enum ColourIds
  45905. {
  45906. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  45907. and feel class how this is used. */
  45908. };
  45909. #ifndef DOXYGEN
  45910. /** @internal */
  45911. void paint (Graphics& g);
  45912. /** @internal */
  45913. void resized();
  45914. /** @internal */
  45915. void lookAndFeelChanged();
  45916. /** @internal */
  45917. const BorderSize<int> getBorderThickness();
  45918. /** @internal */
  45919. const BorderSize<int> getContentComponentBorder();
  45920. /** @internal */
  45921. void mouseDoubleClick (const MouseEvent& e);
  45922. /** @internal */
  45923. void userTriedToCloseWindow();
  45924. /** @internal */
  45925. void activeWindowStatusChanged();
  45926. /** @internal */
  45927. int getDesktopWindowStyleFlags() const;
  45928. /** @internal */
  45929. void parentHierarchyChanged();
  45930. /** @internal */
  45931. const Rectangle<int> getTitleBarArea();
  45932. #endif
  45933. private:
  45934. int titleBarHeight, menuBarHeight, requiredButtons;
  45935. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  45936. ScopedPointer <Button> titleBarButtons [3];
  45937. Image titleBarIcon;
  45938. ScopedPointer <Component> menuBar;
  45939. MenuBarModel* menuBarModel;
  45940. class ButtonListenerProxy;
  45941. friend class ScopedPointer <ButtonListenerProxy>;
  45942. ScopedPointer <ButtonListenerProxy> buttonListener;
  45943. void repaintTitleBar();
  45944. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DocumentWindow);
  45945. };
  45946. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  45947. /*** End of inlined file: juce_DocumentWindow.h ***/
  45948. class MultiDocumentPanel;
  45949. class MDITabbedComponentInternal;
  45950. /**
  45951. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  45952. component.
  45953. It's like a normal DocumentWindow but has some extra functionality to make sure
  45954. everything works nicely inside a MultiDocumentPanel.
  45955. @see MultiDocumentPanel
  45956. */
  45957. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  45958. {
  45959. public:
  45960. /**
  45961. */
  45962. MultiDocumentPanelWindow (const Colour& backgroundColour);
  45963. /** Destructor. */
  45964. ~MultiDocumentPanelWindow();
  45965. /** @internal */
  45966. void maximiseButtonPressed();
  45967. /** @internal */
  45968. void closeButtonPressed();
  45969. /** @internal */
  45970. void activeWindowStatusChanged();
  45971. /** @internal */
  45972. void broughtToFront();
  45973. private:
  45974. void updateOrder();
  45975. MultiDocumentPanel* getOwner() const noexcept;
  45976. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanelWindow);
  45977. };
  45978. /**
  45979. A component that contains a set of other components either in floating windows
  45980. or tabs.
  45981. This acts as a panel that can be used to hold a set of open document windows, with
  45982. different layout modes.
  45983. Use addDocument() and closeDocument() to add or remove components from the
  45984. panel - never use any of the Component methods to access the panel's child
  45985. components directly, as these are managed internally.
  45986. */
  45987. class JUCE_API MultiDocumentPanel : public Component,
  45988. private ComponentListener
  45989. {
  45990. public:
  45991. /** Creates an empty panel.
  45992. Use addDocument() and closeDocument() to add or remove components from the
  45993. panel - never use any of the Component methods to access the panel's child
  45994. components directly, as these are managed internally.
  45995. */
  45996. MultiDocumentPanel();
  45997. /** Destructor.
  45998. When deleted, this will call closeAllDocuments (false) to make sure all its
  45999. components are deleted. If you need to make sure all documents are saved
  46000. before closing, then you should call closeAllDocuments (true) and check that
  46001. it returns true before deleting the panel.
  46002. */
  46003. ~MultiDocumentPanel();
  46004. /** Tries to close all the documents.
  46005. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  46006. be called for each open document, and any of these calls fails, this method
  46007. will stop and return false, leaving some documents still open.
  46008. If checkItsOkToCloseFirst is false, then all documents will be closed
  46009. unconditionally.
  46010. @see closeDocument
  46011. */
  46012. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  46013. /** Adds a document component to the panel.
  46014. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  46015. this will fail and return false. (If it does fail, the component passed-in will not be
  46016. deleted, even if deleteWhenRemoved was set to true).
  46017. The MultiDocumentPanel will deal with creating a window border to go around your component,
  46018. so just pass in the bare content component here, no need to give it a ResizableWindow
  46019. or DocumentWindow.
  46020. @param component the component to add
  46021. @param backgroundColour the background colour to use to fill the component's
  46022. window or tab
  46023. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  46024. or closeAllDocuments(), then it will be deleted. If false, then
  46025. the caller must handle the component's deletion
  46026. */
  46027. bool addDocument (Component* component,
  46028. const Colour& backgroundColour,
  46029. bool deleteWhenRemoved);
  46030. /** Closes one of the documents.
  46031. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  46032. be called, and if it fails, this method will return false without closing the
  46033. document.
  46034. If checkItsOkToCloseFirst is false, then the documents will be closed
  46035. unconditionally.
  46036. The component will be deleted if the deleteWhenRemoved parameter was set to
  46037. true when it was added with addDocument.
  46038. @see addDocument, closeAllDocuments
  46039. */
  46040. bool closeDocument (Component* component,
  46041. bool checkItsOkToCloseFirst);
  46042. /** Returns the number of open document windows.
  46043. @see getDocument
  46044. */
  46045. int getNumDocuments() const noexcept;
  46046. /** Returns one of the open documents.
  46047. The order of the documents in this array may change when they are added, removed
  46048. or moved around.
  46049. @see getNumDocuments
  46050. */
  46051. Component* getDocument (int index) const noexcept;
  46052. /** Returns the document component that is currently focused or on top.
  46053. If currently using floating windows, then this will be the component in the currently
  46054. active window, or the top component if none are active.
  46055. If it's currently in tabbed mode, then it'll return the component in the active tab.
  46056. @see setActiveDocument
  46057. */
  46058. Component* getActiveDocument() const noexcept;
  46059. /** Makes one of the components active and brings it to the top.
  46060. @see getActiveDocument
  46061. */
  46062. void setActiveDocument (Component* component);
  46063. /** Callback which gets invoked when the currently-active document changes. */
  46064. virtual void activeDocumentChanged();
  46065. /** Sets a limit on how many windows can be open at once.
  46066. If this is zero or less there's no limit (the default). addDocument() will fail
  46067. if this number is exceeded.
  46068. */
  46069. void setMaximumNumDocuments (int maximumNumDocuments);
  46070. /** Sets an option to make the document fullscreen if there's only one document open.
  46071. If set to true, then if there's only one document, it'll fill the whole of this
  46072. component without tabs or a window border. If false, then tabs or a window
  46073. will always be shown, even if there's only one document. If there's more than
  46074. one document open, then this option makes no difference.
  46075. */
  46076. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  46077. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  46078. */
  46079. bool isFullscreenWhenOneDocument() const noexcept;
  46080. /** The different layout modes available. */
  46081. enum LayoutMode
  46082. {
  46083. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  46084. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  46085. };
  46086. /** Changes the panel's mode.
  46087. @see LayoutMode, getLayoutMode
  46088. */
  46089. void setLayoutMode (LayoutMode newLayoutMode);
  46090. /** Returns the current layout mode. */
  46091. LayoutMode getLayoutMode() const noexcept { return mode; }
  46092. /** Sets the background colour for the whole panel.
  46093. Each document has its own background colour, but this is the one used to fill the areas
  46094. behind them.
  46095. */
  46096. void setBackgroundColour (const Colour& newBackgroundColour);
  46097. /** Returns the current background colour.
  46098. @see setBackgroundColour
  46099. */
  46100. const Colour& getBackgroundColour() const noexcept { return backgroundColour; }
  46101. /** A subclass must override this to say whether its currently ok for a document
  46102. to be closed.
  46103. This method is called by closeDocument() and closeAllDocuments() to indicate that
  46104. a document should be saved if possible, ready for it to be closed.
  46105. If this method returns true, then it means the document is ok and can be closed.
  46106. If it returns false, then it means that the closeDocument() method should stop
  46107. and not close.
  46108. Normally, you'd use this method to ask the user if they want to save any changes,
  46109. then return true if the save operation went ok. If the user cancelled the save
  46110. operation you could return false here to abort the close operation.
  46111. If your component is based on the FileBasedDocument class, then you'd probably want
  46112. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  46113. FileBasedDocument::savedOk
  46114. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  46115. */
  46116. virtual bool tryToCloseDocument (Component* component) = 0;
  46117. /** Creates a new window to be used for a document.
  46118. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  46119. but you might want to override it to return a custom component.
  46120. */
  46121. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  46122. /** @internal */
  46123. void paint (Graphics& g);
  46124. /** @internal */
  46125. void resized();
  46126. /** @internal */
  46127. void componentNameChanged (Component&);
  46128. private:
  46129. LayoutMode mode;
  46130. Array <Component*> components;
  46131. ScopedPointer<TabbedComponent> tabComponent;
  46132. Colour backgroundColour;
  46133. int maximumNumDocuments, numDocsBeforeTabsUsed;
  46134. friend class MultiDocumentPanelWindow;
  46135. friend class MDITabbedComponentInternal;
  46136. Component* getContainerComp (Component* c) const;
  46137. void updateOrder();
  46138. void addWindow (Component* component);
  46139. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanel);
  46140. };
  46141. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  46142. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  46143. #endif
  46144. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  46145. #endif
  46146. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  46147. #endif
  46148. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  46149. /*** Start of inlined file: juce_ResizableEdgeComponent.h ***/
  46150. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  46151. #define __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  46152. /**
  46153. A component that resizes its parent component when dragged.
  46154. This component forms a bar along one edge of a component, allowing it to
  46155. be dragged by that edges to resize it.
  46156. To use it, just add it to your component, positioning it along the appropriate
  46157. edge. Make sure you reposition the resizer component each time the parent's size
  46158. changes, to keep it in the correct position.
  46159. @see ResizbleBorderComponent, ResizableCornerComponent
  46160. */
  46161. class JUCE_API ResizableEdgeComponent : public Component
  46162. {
  46163. public:
  46164. enum Edge
  46165. {
  46166. leftEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's left-hand edge. */
  46167. rightEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's right-hand edge. */
  46168. topEdge, /**< Indicates a horizontal bar that can be dragged up/down to move the top of the component. */
  46169. bottomEdge /**< Indicates a horizontal bar that can be dragged up/down to move the bottom of the component. */
  46170. };
  46171. /** Creates a resizer bar.
  46172. Pass in the target component which you want to be resized when this one is
  46173. dragged. The target component will usually be this component's parent, but this
  46174. isn't mandatory.
  46175. Remember that when the target component is resized, it'll need to move and
  46176. resize this component to keep it in place, as this won't happen automatically.
  46177. If the constrainer parameter is non-zero, then this object will be used to enforce
  46178. limits on the size and position that the component can be stretched to. Make sure
  46179. that the constrainer isn't deleted while still in use by this object.
  46180. @see ComponentBoundsConstrainer
  46181. */
  46182. ResizableEdgeComponent (Component* componentToResize,
  46183. ComponentBoundsConstrainer* constrainer,
  46184. Edge edgeToResize);
  46185. /** Destructor. */
  46186. ~ResizableEdgeComponent();
  46187. bool isVertical() const noexcept;
  46188. protected:
  46189. /** @internal */
  46190. void paint (Graphics& g);
  46191. /** @internal */
  46192. void mouseDown (const MouseEvent& e);
  46193. /** @internal */
  46194. void mouseDrag (const MouseEvent& e);
  46195. /** @internal */
  46196. void mouseUp (const MouseEvent& e);
  46197. private:
  46198. WeakReference<Component> component;
  46199. ComponentBoundsConstrainer* constrainer;
  46200. Rectangle<int> originalBounds;
  46201. const Edge edge;
  46202. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableEdgeComponent);
  46203. };
  46204. #endif // __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  46205. /*** End of inlined file: juce_ResizableEdgeComponent.h ***/
  46206. #endif
  46207. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  46208. #endif
  46209. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  46210. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  46211. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  46212. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  46213. /**
  46214. For laying out a set of components, where the components have preferred sizes
  46215. and size limits, but where they are allowed to stretch to fill the available
  46216. space.
  46217. For example, if you have a component containing several other components, and
  46218. each one should be given a share of the total size, you could use one of these
  46219. to resize the child components when the parent component is resized. Then
  46220. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  46221. A StretchableLayoutManager operates only in one dimension, so if you have a set
  46222. of components stacked vertically on top of each other, you'd use one to manage their
  46223. heights. To build up complex arrangements of components, e.g. for applications
  46224. with multiple nested panels, you would use more than one StretchableLayoutManager.
  46225. E.g. by using two (one vertical, one horizontal), you could create a resizable
  46226. spreadsheet-style table.
  46227. E.g.
  46228. @code
  46229. class MyComp : public Component
  46230. {
  46231. StretchableLayoutManager myLayout;
  46232. MyComp()
  46233. {
  46234. myLayout.setItemLayout (0, // for item 0
  46235. 50, 100, // must be between 50 and 100 pixels in size
  46236. -0.6); // and its preferred size is 60% of the total available space
  46237. myLayout.setItemLayout (1, // for item 1
  46238. -0.2, -0.6, // size must be between 20% and 60% of the available space
  46239. 50); // and its preferred size is 50 pixels
  46240. }
  46241. void resized()
  46242. {
  46243. // make a list of two of our child components that we want to reposition
  46244. Component* comps[] = { myComp1, myComp2 };
  46245. // this will position the 2 components, one above the other, to fit
  46246. // vertically into the rectangle provided.
  46247. myLayout.layOutComponents (comps, 2,
  46248. 0, 0, getWidth(), getHeight(),
  46249. true);
  46250. }
  46251. };
  46252. @endcode
  46253. @see StretchableLayoutResizerBar
  46254. */
  46255. class JUCE_API StretchableLayoutManager
  46256. {
  46257. public:
  46258. /** Creates an empty layout.
  46259. You'll need to add some item properties to the layout before it can be used
  46260. to resize things - see setItemLayout().
  46261. */
  46262. StretchableLayoutManager();
  46263. /** Destructor. */
  46264. ~StretchableLayoutManager();
  46265. /** For a numbered item, this sets its size limits and preferred size.
  46266. @param itemIndex the index of the item to change.
  46267. @param minimumSize the minimum size that this item is allowed to be - a positive number
  46268. indicates an absolute size in pixels. A negative number indicates a
  46269. proportion of the available space (e.g -0.5 is 50%)
  46270. @param maximumSize the maximum size that this item is allowed to be - a positive number
  46271. indicates an absolute size in pixels. A negative number indicates a
  46272. proportion of the available space
  46273. @param preferredSize the size that this item would like to be, if there's enough room. A
  46274. positive number indicates an absolute size in pixels. A negative number
  46275. indicates a proportion of the available space
  46276. @see getItemLayout
  46277. */
  46278. void setItemLayout (int itemIndex,
  46279. double minimumSize,
  46280. double maximumSize,
  46281. double preferredSize);
  46282. /** For a numbered item, this returns its size limits and preferred size.
  46283. @param itemIndex the index of the item.
  46284. @param minimumSize the minimum size that this item is allowed to be - a positive number
  46285. indicates an absolute size in pixels. A negative number indicates a
  46286. proportion of the available space (e.g -0.5 is 50%)
  46287. @param maximumSize the maximum size that this item is allowed to be - a positive number
  46288. indicates an absolute size in pixels. A negative number indicates a
  46289. proportion of the available space
  46290. @param preferredSize the size that this item would like to be, if there's enough room. A
  46291. positive number indicates an absolute size in pixels. A negative number
  46292. indicates a proportion of the available space
  46293. @returns false if the item's properties hadn't been set
  46294. @see setItemLayout
  46295. */
  46296. bool getItemLayout (int itemIndex,
  46297. double& minimumSize,
  46298. double& maximumSize,
  46299. double& preferredSize) const;
  46300. /** Clears all the properties that have been set with setItemLayout() and resets
  46301. this object to its initial state.
  46302. */
  46303. void clearAllItems();
  46304. /** Takes a set of components that correspond to the layout's items, and positions
  46305. them to fill a space.
  46306. This will try to give each item its preferred size, whether that's a relative size
  46307. or an absolute one.
  46308. @param components an array of components that correspond to each of the
  46309. numbered items that the StretchableLayoutManager object
  46310. has been told about with setItemLayout()
  46311. @param numComponents the number of components in the array that is passed-in. This
  46312. should be the same as the number of items this object has been
  46313. told about.
  46314. @param x the left of the rectangle in which the components should
  46315. be laid out
  46316. @param y the top of the rectangle in which the components should
  46317. be laid out
  46318. @param width the width of the rectangle in which the components should
  46319. be laid out
  46320. @param height the height of the rectangle in which the components should
  46321. be laid out
  46322. @param vertically if true, the components will be positioned in a vertical stack,
  46323. so that they fill the height of the rectangle. If false, they
  46324. will be placed side-by-side in a horizontal line, filling the
  46325. available width
  46326. @param resizeOtherDimension if true, this means that the components will have their
  46327. other dimension resized to fit the space - i.e. if the 'vertically'
  46328. parameter is true, their x-positions and widths are adjusted to fit
  46329. the x and width parameters; if 'vertically' is false, their y-positions
  46330. and heights are adjusted to fit the y and height parameters.
  46331. */
  46332. void layOutComponents (Component** components,
  46333. int numComponents,
  46334. int x, int y, int width, int height,
  46335. bool vertically,
  46336. bool resizeOtherDimension);
  46337. /** Returns the current position of one of the items.
  46338. This is only a valid call after layOutComponents() has been called, as it
  46339. returns the last position that this item was placed at. If the layout was
  46340. vertical, the value returned will be the y position of the top of the item,
  46341. relative to the top of the rectangle in which the items were placed (so for
  46342. example, item 0 will always have position of 0, even in the rectangle passed
  46343. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  46344. the position returned is the item's left-hand position, again relative to the
  46345. x position of the rectangle used.
  46346. @see getItemCurrentSize, setItemPosition
  46347. */
  46348. int getItemCurrentPosition (int itemIndex) const;
  46349. /** Returns the current size of one of the items.
  46350. This is only meaningful after layOutComponents() has been called, as it
  46351. returns the last size that this item was given. If the layout was done
  46352. vertically, it'll return the item's height in pixels; if it was horizontal,
  46353. it'll return its width.
  46354. @see getItemCurrentRelativeSize
  46355. */
  46356. int getItemCurrentAbsoluteSize (int itemIndex) const;
  46357. /** Returns the current size of one of the items.
  46358. This is only meaningful after layOutComponents() has been called, as it
  46359. returns the last size that this item was given. If the layout was done
  46360. vertically, it'll return a negative value representing the item's height relative
  46361. to the last size used for laying the components out; if the layout was done
  46362. horizontally it'll be the proportion of its width.
  46363. @see getItemCurrentAbsoluteSize
  46364. */
  46365. double getItemCurrentRelativeSize (int itemIndex) const;
  46366. /** Moves one of the items, shifting along any other items as necessary in
  46367. order to get it to the desired position.
  46368. Calling this method will also update the preferred sizes of the items it
  46369. shuffles along, so that they reflect their new positions.
  46370. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  46371. about when it's dragged).
  46372. @param itemIndex the item to move
  46373. @param newPosition the absolute position that you'd like this item to move
  46374. to. The item might not be able to always reach exactly this position,
  46375. because other items may have minimum sizes that constrain how
  46376. far it can go
  46377. */
  46378. void setItemPosition (int itemIndex,
  46379. int newPosition);
  46380. private:
  46381. struct ItemLayoutProperties
  46382. {
  46383. int itemIndex;
  46384. int currentSize;
  46385. double minSize, maxSize, preferredSize;
  46386. };
  46387. OwnedArray <ItemLayoutProperties> items;
  46388. int totalSize;
  46389. static int sizeToRealSize (double size, int totalSpace);
  46390. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  46391. void setTotalSize (int newTotalSize);
  46392. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  46393. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  46394. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  46395. void updatePrefSizesToMatchCurrentPositions();
  46396. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutManager);
  46397. };
  46398. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  46399. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  46400. #endif
  46401. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  46402. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  46403. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  46404. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  46405. /**
  46406. A component that acts as one of the vertical or horizontal bars you see being
  46407. used to resize panels in a window.
  46408. One of these acts with a StretchableLayoutManager to resize the other components.
  46409. @see StretchableLayoutManager
  46410. */
  46411. class JUCE_API StretchableLayoutResizerBar : public Component
  46412. {
  46413. public:
  46414. /** Creates a resizer bar for use on a specified layout.
  46415. @param layoutToUse the layout that will be affected when this bar
  46416. is dragged
  46417. @param itemIndexInLayout the item index in the layout that corresponds to
  46418. this bar component. You'll need to set up the item
  46419. properties in a suitable way for a divider bar, e.g.
  46420. for an 8-pixel wide bar which, you could call
  46421. myLayout->setItemLayout (barIndex, 8, 8, 8)
  46422. @param isBarVertical true if it's an upright bar that you drag left and
  46423. right; false for a horizontal one that you drag up and
  46424. down
  46425. */
  46426. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  46427. int itemIndexInLayout,
  46428. bool isBarVertical);
  46429. /** Destructor. */
  46430. ~StretchableLayoutResizerBar();
  46431. /** This is called when the bar is dragged.
  46432. This method must update the positions of any components whose position is
  46433. determined by the StretchableLayoutManager, because they might have just
  46434. moved.
  46435. The default implementation calls the resized() method of this component's
  46436. parent component, because that's often where you're likely to apply the
  46437. layout, but it can be overridden for more specific needs.
  46438. */
  46439. virtual void hasBeenMoved();
  46440. /** @internal */
  46441. void paint (Graphics& g);
  46442. /** @internal */
  46443. void mouseDown (const MouseEvent& e);
  46444. /** @internal */
  46445. void mouseDrag (const MouseEvent& e);
  46446. private:
  46447. StretchableLayoutManager* layout;
  46448. int itemIndex, mouseDownPos;
  46449. bool isVertical;
  46450. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutResizerBar);
  46451. };
  46452. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  46453. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  46454. #endif
  46455. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  46456. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  46457. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  46458. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  46459. /**
  46460. A utility class for fitting a set of objects whose sizes can vary between
  46461. a minimum and maximum size, into a space.
  46462. This is a trickier algorithm than it would first seem, so I've put it in this
  46463. class to allow it to be shared by various bits of code.
  46464. To use it, create one of these objects, call addItem() to add the list of items
  46465. you need, then call resizeToFit(), which will change all their sizes. You can
  46466. then retrieve the new sizes with getItemSize() and getNumItems().
  46467. It's currently used by the TableHeaderComponent for stretching out the table
  46468. headings to fill the table's width.
  46469. */
  46470. class StretchableObjectResizer
  46471. {
  46472. public:
  46473. /** Creates an empty object resizer. */
  46474. StretchableObjectResizer();
  46475. /** Destructor. */
  46476. ~StretchableObjectResizer();
  46477. /** Adds an item to the list.
  46478. The order parameter lets you specify groups of items that are resized first when some
  46479. space needs to be found. Those items with an order of 0 will be the first ones to be
  46480. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  46481. will then try resizing the items with an order of 1, then 2, and so on.
  46482. */
  46483. void addItem (double currentSize,
  46484. double minSize,
  46485. double maxSize,
  46486. int order = 0);
  46487. /** Resizes all the items to fit this amount of space.
  46488. This will attempt to fit them in without exceeding each item's miniumum and
  46489. maximum sizes. In cases where none of the items can be expanded or enlarged any
  46490. further, the final size may be greater or less than the size passed in.
  46491. After calling this method, you can retrieve the new sizes with the getItemSize()
  46492. method.
  46493. */
  46494. void resizeToFit (double targetSize);
  46495. /** Returns the number of items that have been added. */
  46496. int getNumItems() const noexcept { return items.size(); }
  46497. /** Returns the size of one of the items. */
  46498. double getItemSize (int index) const noexcept;
  46499. private:
  46500. struct Item
  46501. {
  46502. double size;
  46503. double minSize;
  46504. double maxSize;
  46505. int order;
  46506. };
  46507. OwnedArray <Item> items;
  46508. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableObjectResizer);
  46509. };
  46510. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  46511. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  46512. #endif
  46513. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  46514. #endif
  46515. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  46516. #endif
  46517. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  46518. #endif
  46519. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  46520. /*** Start of inlined file: juce_LookAndFeel.h ***/
  46521. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  46522. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  46523. class ToggleButton;
  46524. class TextButton;
  46525. class AlertWindow;
  46526. class TextLayout;
  46527. class ScrollBar;
  46528. class BubbleComponent;
  46529. class ComboBox;
  46530. class Button;
  46531. class FilenameComponent;
  46532. class DocumentWindow;
  46533. class ResizableWindow;
  46534. class GroupComponent;
  46535. class MenuBarComponent;
  46536. class DropShadower;
  46537. class GlyphArrangement;
  46538. class PropertyComponent;
  46539. class TableHeaderComponent;
  46540. class Toolbar;
  46541. class ToolbarItemComponent;
  46542. class PopupMenu;
  46543. class ProgressBar;
  46544. class FileBrowserComponent;
  46545. class DirectoryContentsDisplayComponent;
  46546. class FilePreviewComponent;
  46547. class ImageButton;
  46548. class CallOutBox;
  46549. class Drawable;
  46550. class CaretComponent;
  46551. /**
  46552. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  46553. can be used to apply different 'skins' to the application.
  46554. */
  46555. class JUCE_API LookAndFeel
  46556. {
  46557. public:
  46558. /** Creates the default JUCE look and feel. */
  46559. LookAndFeel();
  46560. /** Destructor. */
  46561. virtual ~LookAndFeel();
  46562. /** Returns the current default look-and-feel for a component to use when it
  46563. hasn't got one explicitly set.
  46564. @see setDefaultLookAndFeel
  46565. */
  46566. static LookAndFeel& getDefaultLookAndFeel() noexcept;
  46567. /** Changes the default look-and-feel.
  46568. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  46569. set to null, it will revert to using the default one. The
  46570. object passed-in must be deleted by the caller when
  46571. it's no longer needed.
  46572. @see getDefaultLookAndFeel
  46573. */
  46574. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) noexcept;
  46575. /** Looks for a colour that has been registered with the given colour ID number.
  46576. If a colour has been set for this ID number using setColour(), then it is
  46577. returned. If none has been set, it will just return Colours::black.
  46578. The colour IDs for various purposes are stored as enums in the components that
  46579. they are relevent to - for an example, see Slider::ColourIds,
  46580. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  46581. If you're looking up a colour for use in drawing a component, it's usually
  46582. best not to call this directly, but to use the Component::findColour() method
  46583. instead. That will first check whether a suitable colour has been registered
  46584. directly with the component, and will fall-back on calling the component's
  46585. LookAndFeel's findColour() method if none is found.
  46586. @see setColour, Component::findColour, Component::setColour
  46587. */
  46588. const Colour findColour (int colourId) const noexcept;
  46589. /** Registers a colour to be used for a particular purpose.
  46590. For more details, see the comments for findColour().
  46591. @see findColour, Component::findColour, Component::setColour
  46592. */
  46593. void setColour (int colourId, const Colour& colour) noexcept;
  46594. /** Returns true if the specified colour ID has been explicitly set using the
  46595. setColour() method.
  46596. */
  46597. bool isColourSpecified (int colourId) const noexcept;
  46598. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  46599. /** Allows you to change the default sans-serif font.
  46600. If you need to supply your own Typeface object for any of the default fonts, rather
  46601. than just supplying the name (e.g. if you want to use an embedded font), then
  46602. you should instead override getTypefaceForFont() to create and return the typeface.
  46603. */
  46604. void setDefaultSansSerifTypefaceName (const String& newName);
  46605. /** Override this to get the chance to swap a component's mouse cursor for a
  46606. customised one.
  46607. */
  46608. virtual const MouseCursor getMouseCursorFor (Component& component);
  46609. /** Draws the lozenge-shaped background for a standard button. */
  46610. virtual void drawButtonBackground (Graphics& g,
  46611. Button& button,
  46612. const Colour& backgroundColour,
  46613. bool isMouseOverButton,
  46614. bool isButtonDown);
  46615. virtual const Font getFontForTextButton (TextButton& button);
  46616. /** Draws the text for a TextButton. */
  46617. virtual void drawButtonText (Graphics& g,
  46618. TextButton& button,
  46619. bool isMouseOverButton,
  46620. bool isButtonDown);
  46621. /** Draws the contents of a standard ToggleButton. */
  46622. virtual void drawToggleButton (Graphics& g,
  46623. ToggleButton& button,
  46624. bool isMouseOverButton,
  46625. bool isButtonDown);
  46626. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  46627. virtual void drawTickBox (Graphics& g,
  46628. Component& component,
  46629. float x, float y, float w, float h,
  46630. bool ticked,
  46631. bool isEnabled,
  46632. bool isMouseOverButton,
  46633. bool isButtonDown);
  46634. /* AlertWindow handling..
  46635. */
  46636. virtual AlertWindow* createAlertWindow (const String& title,
  46637. const String& message,
  46638. const String& button1,
  46639. const String& button2,
  46640. const String& button3,
  46641. AlertWindow::AlertIconType iconType,
  46642. int numButtons,
  46643. Component* associatedComponent);
  46644. virtual void drawAlertBox (Graphics& g,
  46645. AlertWindow& alert,
  46646. const Rectangle<int>& textArea,
  46647. TextLayout& textLayout);
  46648. virtual int getAlertBoxWindowFlags();
  46649. virtual int getAlertWindowButtonHeight();
  46650. virtual const Font getAlertWindowMessageFont();
  46651. virtual const Font getAlertWindowFont();
  46652. void setUsingNativeAlertWindows (bool shouldUseNativeAlerts);
  46653. bool isUsingNativeAlertWindows();
  46654. /** Draws a progress bar.
  46655. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  46656. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  46657. isn't known). It can use the current time as a basis for playing an animation.
  46658. (Used by progress bars in AlertWindow).
  46659. */
  46660. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  46661. int width, int height,
  46662. double progress, const String& textToShow);
  46663. // Draws a small image that spins to indicate that something's happening..
  46664. // This method should use the current time to animate itself, so just keep
  46665. // repainting it every so often.
  46666. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  46667. int x, int y, int w, int h);
  46668. /** Draws one of the buttons on a scrollbar.
  46669. @param g the context to draw into
  46670. @param scrollbar the bar itself
  46671. @param width the width of the button
  46672. @param height the height of the button
  46673. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  46674. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  46675. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  46676. @param isButtonDown whether the mouse button's held down
  46677. */
  46678. virtual void drawScrollbarButton (Graphics& g,
  46679. ScrollBar& scrollbar,
  46680. int width, int height,
  46681. int buttonDirection,
  46682. bool isScrollbarVertical,
  46683. bool isMouseOverButton,
  46684. bool isButtonDown);
  46685. /** Draws the thumb area of a scrollbar.
  46686. @param g the context to draw into
  46687. @param scrollbar the bar itself
  46688. @param x the x position of the left edge of the thumb area to draw in
  46689. @param y the y position of the top edge of the thumb area to draw in
  46690. @param width the width of the thumb area to draw in
  46691. @param height the height of the thumb area to draw in
  46692. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  46693. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  46694. thumb, or its x position for horizontal bars
  46695. @param thumbSize for vertical bars, the height of the thumb, or its width for
  46696. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  46697. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  46698. currently dragging the thumb
  46699. @param isMouseDown whether the mouse is currently dragging the scrollbar
  46700. */
  46701. virtual void drawScrollbar (Graphics& g,
  46702. ScrollBar& scrollbar,
  46703. int x, int y,
  46704. int width, int height,
  46705. bool isScrollbarVertical,
  46706. int thumbStartPosition,
  46707. int thumbSize,
  46708. bool isMouseOver,
  46709. bool isMouseDown);
  46710. /** Returns the component effect to use for a scrollbar */
  46711. virtual ImageEffectFilter* getScrollbarEffect();
  46712. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  46713. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  46714. /** Returns the default thickness to use for a scrollbar. */
  46715. virtual int getDefaultScrollbarWidth();
  46716. /** Returns the length in pixels to use for a scrollbar button. */
  46717. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  46718. /** Returns a tick shape for use in yes/no boxes, etc. */
  46719. virtual const Path getTickShape (float height);
  46720. /** Returns a cross shape for use in yes/no boxes, etc. */
  46721. virtual const Path getCrossShape (float height);
  46722. /** Draws the + or - box in a treeview. */
  46723. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  46724. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  46725. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  46726. virtual CaretComponent* createCaretComponent (Component* keyFocusOwner);
  46727. // These return a pointer to an internally cached drawable - make sure you don't keep
  46728. // a copy of this pointer anywhere, as it may become invalid in the future.
  46729. virtual const Drawable* getDefaultFolderImage();
  46730. virtual const Drawable* getDefaultDocumentFileImage();
  46731. virtual void createFileChooserHeaderText (const String& title,
  46732. const String& instructions,
  46733. GlyphArrangement& destArrangement,
  46734. int width);
  46735. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  46736. const String& filename, Image* icon,
  46737. const String& fileSizeDescription,
  46738. const String& fileTimeDescription,
  46739. bool isDirectory,
  46740. bool isItemSelected,
  46741. int itemIndex,
  46742. DirectoryContentsDisplayComponent& component);
  46743. virtual Button* createFileBrowserGoUpButton();
  46744. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  46745. DirectoryContentsDisplayComponent* fileListComponent,
  46746. FilePreviewComponent* previewComp,
  46747. ComboBox* currentPathBox,
  46748. TextEditor* filenameBox,
  46749. Button* goUpButton);
  46750. virtual void drawBubble (Graphics& g,
  46751. float tipX, float tipY,
  46752. float boxX, float boxY, float boxW, float boxH);
  46753. /** Fills the background of a popup menu component. */
  46754. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  46755. /** Draws one of the items in a popup menu. */
  46756. virtual void drawPopupMenuItem (Graphics& g,
  46757. int width, int height,
  46758. bool isSeparator,
  46759. bool isActive,
  46760. bool isHighlighted,
  46761. bool isTicked,
  46762. bool hasSubMenu,
  46763. const String& text,
  46764. const String& shortcutKeyText,
  46765. Image* image,
  46766. const Colour* const textColour);
  46767. /** Returns the size and style of font to use in popup menus. */
  46768. virtual const Font getPopupMenuFont();
  46769. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  46770. int width, int height,
  46771. bool isScrollUpArrow);
  46772. /** Finds the best size for an item in a popup menu. */
  46773. virtual void getIdealPopupMenuItemSize (const String& text,
  46774. bool isSeparator,
  46775. int standardMenuItemHeight,
  46776. int& idealWidth,
  46777. int& idealHeight);
  46778. virtual int getMenuWindowFlags();
  46779. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  46780. bool isMouseOverBar,
  46781. MenuBarComponent& menuBar);
  46782. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  46783. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  46784. virtual void drawMenuBarItem (Graphics& g,
  46785. int width, int height,
  46786. int itemIndex,
  46787. const String& itemText,
  46788. bool isMouseOverItem,
  46789. bool isMenuOpen,
  46790. bool isMouseOverBar,
  46791. MenuBarComponent& menuBar);
  46792. virtual void drawComboBox (Graphics& g, int width, int height,
  46793. bool isButtonDown,
  46794. int buttonX, int buttonY,
  46795. int buttonW, int buttonH,
  46796. ComboBox& box);
  46797. virtual const Font getComboBoxFont (ComboBox& box);
  46798. virtual Label* createComboBoxTextBox (ComboBox& box);
  46799. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  46800. virtual void drawLabel (Graphics& g, Label& label);
  46801. virtual void drawLinearSlider (Graphics& g,
  46802. int x, int y,
  46803. int width, int height,
  46804. float sliderPos,
  46805. float minSliderPos,
  46806. float maxSliderPos,
  46807. const Slider::SliderStyle style,
  46808. Slider& slider);
  46809. virtual void drawLinearSliderBackground (Graphics& g,
  46810. int x, int y,
  46811. int width, int height,
  46812. float sliderPos,
  46813. float minSliderPos,
  46814. float maxSliderPos,
  46815. const Slider::SliderStyle style,
  46816. Slider& slider);
  46817. virtual void drawLinearSliderThumb (Graphics& g,
  46818. int x, int y,
  46819. int width, int height,
  46820. float sliderPos,
  46821. float minSliderPos,
  46822. float maxSliderPos,
  46823. const Slider::SliderStyle style,
  46824. Slider& slider);
  46825. virtual int getSliderThumbRadius (Slider& slider);
  46826. virtual void drawRotarySlider (Graphics& g,
  46827. int x, int y,
  46828. int width, int height,
  46829. float sliderPosProportional,
  46830. float rotaryStartAngle,
  46831. float rotaryEndAngle,
  46832. Slider& slider);
  46833. virtual Button* createSliderButton (bool isIncrement);
  46834. virtual Label* createSliderTextBox (Slider& slider);
  46835. virtual ImageEffectFilter* getSliderEffect();
  46836. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  46837. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  46838. virtual Button* createFilenameComponentBrowseButton (const String& text);
  46839. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  46840. ComboBox* filenameBox, Button* browseButton);
  46841. virtual void drawCornerResizer (Graphics& g,
  46842. int w, int h,
  46843. bool isMouseOver,
  46844. bool isMouseDragging);
  46845. virtual void drawResizableFrame (Graphics& g,
  46846. int w, int h,
  46847. const BorderSize<int>& borders);
  46848. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  46849. const BorderSize<int>& border,
  46850. ResizableWindow& window);
  46851. virtual void drawResizableWindowBorder (Graphics& g,
  46852. int w, int h,
  46853. const BorderSize<int>& border,
  46854. ResizableWindow& window);
  46855. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  46856. Graphics& g, int w, int h,
  46857. int titleSpaceX, int titleSpaceW,
  46858. const Image* icon,
  46859. bool drawTitleTextOnLeft);
  46860. virtual Button* createDocumentWindowButton (int buttonType);
  46861. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  46862. int titleBarX, int titleBarY,
  46863. int titleBarW, int titleBarH,
  46864. Button* minimiseButton,
  46865. Button* maximiseButton,
  46866. Button* closeButton,
  46867. bool positionTitleBarButtonsOnLeft);
  46868. virtual int getDefaultMenuBarHeight();
  46869. virtual DropShadower* createDropShadowerForComponent (Component* component);
  46870. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  46871. int w, int h,
  46872. bool isVerticalBar,
  46873. bool isMouseOver,
  46874. bool isMouseDragging);
  46875. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  46876. const String& text,
  46877. const Justification& position,
  46878. GroupComponent& group);
  46879. virtual void createTabButtonShape (Path& p,
  46880. int width, int height,
  46881. int tabIndex,
  46882. const String& text,
  46883. Button& button,
  46884. TabbedButtonBar::Orientation orientation,
  46885. bool isMouseOver,
  46886. bool isMouseDown,
  46887. bool isFrontTab);
  46888. virtual void fillTabButtonShape (Graphics& g,
  46889. const Path& path,
  46890. const Colour& preferredBackgroundColour,
  46891. int tabIndex,
  46892. const String& text,
  46893. Button& button,
  46894. TabbedButtonBar::Orientation orientation,
  46895. bool isMouseOver,
  46896. bool isMouseDown,
  46897. bool isFrontTab);
  46898. virtual void drawTabButtonText (Graphics& g,
  46899. int x, int y, int w, int h,
  46900. const Colour& preferredBackgroundColour,
  46901. int tabIndex,
  46902. const String& text,
  46903. Button& button,
  46904. TabbedButtonBar::Orientation orientation,
  46905. bool isMouseOver,
  46906. bool isMouseDown,
  46907. bool isFrontTab);
  46908. virtual int getTabButtonOverlap (int tabDepth);
  46909. virtual int getTabButtonSpaceAroundImage();
  46910. virtual int getTabButtonBestWidth (int tabIndex,
  46911. const String& text,
  46912. int tabDepth,
  46913. Button& button);
  46914. virtual void drawTabButton (Graphics& g,
  46915. int w, int h,
  46916. const Colour& preferredColour,
  46917. int tabIndex,
  46918. const String& text,
  46919. Button& button,
  46920. TabbedButtonBar::Orientation orientation,
  46921. bool isMouseOver,
  46922. bool isMouseDown,
  46923. bool isFrontTab);
  46924. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  46925. int w, int h,
  46926. TabbedButtonBar& tabBar,
  46927. TabbedButtonBar::Orientation orientation);
  46928. virtual Button* createTabBarExtrasButton();
  46929. virtual void drawImageButton (Graphics& g, Image* image,
  46930. int imageX, int imageY, int imageW, int imageH,
  46931. const Colour& overlayColour,
  46932. float imageOpacity,
  46933. ImageButton& button);
  46934. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  46935. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  46936. int width, int height,
  46937. bool isMouseOver, bool isMouseDown,
  46938. int columnFlags);
  46939. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  46940. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  46941. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  46942. bool isMouseOver, bool isMouseDown,
  46943. ToolbarItemComponent& component);
  46944. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  46945. const String& text, ToolbarItemComponent& component);
  46946. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  46947. bool isOpen, int width, int height);
  46948. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  46949. PropertyComponent& component);
  46950. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  46951. PropertyComponent& component);
  46952. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  46953. virtual void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
  46954. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  46955. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  46956. /**
  46957. */
  46958. virtual void playAlertSound();
  46959. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  46960. static void drawGlassSphere (Graphics& g,
  46961. float x, float y,
  46962. float diameter,
  46963. const Colour& colour,
  46964. float outlineThickness) noexcept;
  46965. static void drawGlassPointer (Graphics& g,
  46966. float x, float y,
  46967. float diameter,
  46968. const Colour& colour, float outlineThickness,
  46969. int direction) noexcept;
  46970. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  46971. static void drawGlassLozenge (Graphics& g,
  46972. float x, float y,
  46973. float width, float height,
  46974. const Colour& colour,
  46975. float outlineThickness,
  46976. float cornerSize,
  46977. bool flatOnLeft, bool flatOnRight,
  46978. bool flatOnTop, bool flatOnBottom) noexcept;
  46979. static Drawable* loadDrawableFromData (const void* data, size_t numBytes);
  46980. private:
  46981. friend class WeakReference<LookAndFeel>;
  46982. WeakReference<LookAndFeel>::Master weakReferenceMaster;
  46983. const WeakReference<LookAndFeel>::SharedRef& getWeakReference();
  46984. Array <int> colourIds;
  46985. Array <Colour> colours;
  46986. // default typeface names
  46987. String defaultSans, defaultSerif, defaultFixed;
  46988. ScopedPointer<Drawable> folderImage, documentImage;
  46989. bool useNativeAlertWindows;
  46990. void drawShinyButtonShape (Graphics& g,
  46991. float x, float y, float w, float h, float maxCornerSize,
  46992. const Colour& baseColour,
  46993. float strokeWidth,
  46994. bool flatOnLeft,
  46995. bool flatOnRight,
  46996. bool flatOnTop,
  46997. bool flatOnBottom) noexcept;
  46998. // This has been deprecated - see the new parameter list..
  46999. virtual int drawFileBrowserRow (Graphics&, int, int, const String&, Image*, const String&, const String&, bool, bool, int) { return 0; }
  47000. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LookAndFeel);
  47001. };
  47002. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  47003. /*** End of inlined file: juce_LookAndFeel.h ***/
  47004. #endif
  47005. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  47006. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  47007. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  47008. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  47009. /**
  47010. The original Juce look-and-feel.
  47011. */
  47012. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  47013. {
  47014. public:
  47015. /** Creates the default JUCE look and feel. */
  47016. OldSchoolLookAndFeel();
  47017. /** Destructor. */
  47018. virtual ~OldSchoolLookAndFeel();
  47019. /** Draws the lozenge-shaped background for a standard button. */
  47020. virtual void drawButtonBackground (Graphics& g,
  47021. Button& button,
  47022. const Colour& backgroundColour,
  47023. bool isMouseOverButton,
  47024. bool isButtonDown);
  47025. /** Draws the contents of a standard ToggleButton. */
  47026. virtual void drawToggleButton (Graphics& g,
  47027. ToggleButton& button,
  47028. bool isMouseOverButton,
  47029. bool isButtonDown);
  47030. virtual void drawTickBox (Graphics& g,
  47031. Component& component,
  47032. float x, float y, float w, float h,
  47033. bool ticked,
  47034. bool isEnabled,
  47035. bool isMouseOverButton,
  47036. bool isButtonDown);
  47037. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  47038. int width, int height,
  47039. double progress, const String& textToShow);
  47040. virtual void drawScrollbarButton (Graphics& g,
  47041. ScrollBar& scrollbar,
  47042. int width, int height,
  47043. int buttonDirection,
  47044. bool isScrollbarVertical,
  47045. bool isMouseOverButton,
  47046. bool isButtonDown);
  47047. virtual void drawScrollbar (Graphics& g,
  47048. ScrollBar& scrollbar,
  47049. int x, int y,
  47050. int width, int height,
  47051. bool isScrollbarVertical,
  47052. int thumbStartPosition,
  47053. int thumbSize,
  47054. bool isMouseOver,
  47055. bool isMouseDown);
  47056. virtual ImageEffectFilter* getScrollbarEffect();
  47057. virtual void drawTextEditorOutline (Graphics& g,
  47058. int width, int height,
  47059. TextEditor& textEditor);
  47060. /** Fills the background of a popup menu component. */
  47061. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  47062. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  47063. bool isMouseOverBar,
  47064. MenuBarComponent& menuBar);
  47065. virtual void drawComboBox (Graphics& g, int width, int height,
  47066. bool isButtonDown,
  47067. int buttonX, int buttonY,
  47068. int buttonW, int buttonH,
  47069. ComboBox& box);
  47070. virtual const Font getComboBoxFont (ComboBox& box);
  47071. virtual void drawLinearSlider (Graphics& g,
  47072. int x, int y,
  47073. int width, int height,
  47074. float sliderPos,
  47075. float minSliderPos,
  47076. float maxSliderPos,
  47077. const Slider::SliderStyle style,
  47078. Slider& slider);
  47079. virtual int getSliderThumbRadius (Slider& slider);
  47080. virtual Button* createSliderButton (bool isIncrement);
  47081. virtual ImageEffectFilter* getSliderEffect();
  47082. virtual void drawCornerResizer (Graphics& g,
  47083. int w, int h,
  47084. bool isMouseOver,
  47085. bool isMouseDragging);
  47086. virtual Button* createDocumentWindowButton (int buttonType);
  47087. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  47088. int titleBarX, int titleBarY,
  47089. int titleBarW, int titleBarH,
  47090. Button* minimiseButton,
  47091. Button* maximiseButton,
  47092. Button* closeButton,
  47093. bool positionTitleBarButtonsOnLeft);
  47094. private:
  47095. DropShadowEffect scrollbarShadow;
  47096. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OldSchoolLookAndFeel);
  47097. };
  47098. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  47099. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  47100. #endif
  47101. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  47102. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  47103. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  47104. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  47105. /**
  47106. A menu bar component.
  47107. @see MenuBarModel
  47108. */
  47109. class JUCE_API MenuBarComponent : public Component,
  47110. private MenuBarModel::Listener,
  47111. private Timer
  47112. {
  47113. public:
  47114. /** Creates a menu bar.
  47115. @param model the model object to use to control this bar. You can
  47116. pass 0 into this if you like, and set the model later
  47117. using the setModel() method
  47118. */
  47119. MenuBarComponent (MenuBarModel* model);
  47120. /** Destructor. */
  47121. ~MenuBarComponent();
  47122. /** Changes the model object to use to control the bar.
  47123. This can be a null pointer, in which case the bar will be empty. Don't delete the object
  47124. that is passed-in while it's still being used by this MenuBar.
  47125. */
  47126. void setModel (MenuBarModel* newModel);
  47127. /** Returns the current menu bar model being used.
  47128. */
  47129. MenuBarModel* getModel() const noexcept;
  47130. /** Pops up one of the menu items.
  47131. This lets you manually open one of the menus - it could be triggered by a
  47132. key shortcut, for example.
  47133. */
  47134. void showMenu (int menuIndex);
  47135. /** @internal */
  47136. void paint (Graphics& g);
  47137. /** @internal */
  47138. void resized();
  47139. /** @internal */
  47140. void mouseEnter (const MouseEvent& e);
  47141. /** @internal */
  47142. void mouseExit (const MouseEvent& e);
  47143. /** @internal */
  47144. void mouseDown (const MouseEvent& e);
  47145. /** @internal */
  47146. void mouseDrag (const MouseEvent& e);
  47147. /** @internal */
  47148. void mouseUp (const MouseEvent& e);
  47149. /** @internal */
  47150. void mouseMove (const MouseEvent& e);
  47151. /** @internal */
  47152. void handleCommandMessage (int commandId);
  47153. /** @internal */
  47154. bool keyPressed (const KeyPress& key);
  47155. /** @internal */
  47156. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  47157. /** @internal */
  47158. void menuCommandInvoked (MenuBarModel* menuBarModel,
  47159. const ApplicationCommandTarget::InvocationInfo& info);
  47160. private:
  47161. MenuBarModel* model;
  47162. StringArray menuNames;
  47163. Array <int> xPositions;
  47164. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked;
  47165. int lastMouseX, lastMouseY;
  47166. int getItemAt (int x, int y);
  47167. void setItemUnderMouse (int index);
  47168. void setOpenItem (int index);
  47169. void updateItemUnderMouse (int x, int y);
  47170. void timerCallback();
  47171. void repaintMenuItem (int index);
  47172. void menuDismissed (int topLevelIndex, int itemId);
  47173. static void menuBarMenuDismissedCallback (int, MenuBarComponent*, int);
  47174. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarComponent);
  47175. };
  47176. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  47177. /*** End of inlined file: juce_MenuBarComponent.h ***/
  47178. #endif
  47179. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  47180. #endif
  47181. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  47182. #endif
  47183. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  47184. #endif
  47185. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  47186. #endif
  47187. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  47188. #endif
  47189. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  47190. #endif
  47191. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  47192. /*** Start of inlined file: juce_LassoComponent.h ***/
  47193. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  47194. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  47195. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  47196. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  47197. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  47198. /** Manages a list of selectable items.
  47199. Use one of these to keep a track of things that the user has highlighted, like
  47200. icons or things in a list.
  47201. The class is templated so that you can use it to hold either a set of pointers
  47202. to objects, or a set of ID numbers or handles, for cases where each item may
  47203. not always have a corresponding object.
  47204. To be informed when items are selected/deselected, register a ChangeListener with
  47205. this object.
  47206. @see SelectableObject
  47207. */
  47208. template <class SelectableItemType>
  47209. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  47210. {
  47211. public:
  47212. typedef SelectableItemType ItemType;
  47213. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  47214. /** Creates an empty set. */
  47215. SelectedItemSet()
  47216. {
  47217. }
  47218. /** Creates a set based on an array of items. */
  47219. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  47220. : selectedItems (items)
  47221. {
  47222. }
  47223. /** Creates a copy of another set. */
  47224. SelectedItemSet (const SelectedItemSet& other)
  47225. : selectedItems (other.selectedItems)
  47226. {
  47227. }
  47228. /** Creates a copy of another set. */
  47229. SelectedItemSet& operator= (const SelectedItemSet& other)
  47230. {
  47231. if (selectedItems != other.selectedItems)
  47232. {
  47233. selectedItems = other.selectedItems;
  47234. changed();
  47235. }
  47236. return *this;
  47237. }
  47238. /** Clears any other currently selected items, and selects this item.
  47239. If this item is already the only thing selected, no change notification
  47240. will be sent out.
  47241. @see addToSelection, addToSelectionBasedOnModifiers
  47242. */
  47243. void selectOnly (ParameterType item)
  47244. {
  47245. if (isSelected (item))
  47246. {
  47247. for (int i = selectedItems.size(); --i >= 0;)
  47248. {
  47249. if (selectedItems.getUnchecked(i) != item)
  47250. {
  47251. deselect (selectedItems.getUnchecked(i));
  47252. i = jmin (i, selectedItems.size());
  47253. }
  47254. }
  47255. }
  47256. else
  47257. {
  47258. deselectAll();
  47259. changed();
  47260. selectedItems.add (item);
  47261. itemSelected (item);
  47262. }
  47263. }
  47264. /** Selects an item.
  47265. If the item is already selected, no change notification will be sent out.
  47266. @see selectOnly, addToSelectionBasedOnModifiers
  47267. */
  47268. void addToSelection (ParameterType item)
  47269. {
  47270. if (! isSelected (item))
  47271. {
  47272. changed();
  47273. selectedItems.add (item);
  47274. itemSelected (item);
  47275. }
  47276. }
  47277. /** Selects or deselects an item.
  47278. This will use the modifier keys to decide whether to deselect other items
  47279. first.
  47280. So if the shift key is held down, the item will be added without deselecting
  47281. anything (same as calling addToSelection() )
  47282. If no modifiers are down, the current selection will be cleared first (same
  47283. as calling selectOnly() )
  47284. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  47285. so it'll be added to the set unless it's already there, in which case it'll be
  47286. deselected.
  47287. If the items that you're selecting can also be dragged, you may need to use the
  47288. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  47289. subtleties of this kind of usage.
  47290. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  47291. */
  47292. void addToSelectionBasedOnModifiers (ParameterType item,
  47293. const ModifierKeys& modifiers)
  47294. {
  47295. if (modifiers.isShiftDown())
  47296. {
  47297. addToSelection (item);
  47298. }
  47299. else if (modifiers.isCommandDown())
  47300. {
  47301. if (isSelected (item))
  47302. deselect (item);
  47303. else
  47304. addToSelection (item);
  47305. }
  47306. else
  47307. {
  47308. selectOnly (item);
  47309. }
  47310. }
  47311. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  47312. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  47313. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  47314. makes it easy to handle multiple-selection of sets of objects that can also
  47315. be dragged.
  47316. For example, if you have several items already selected, and you click on
  47317. one of them (without dragging), then you'd expect this to deselect the other, and
  47318. just select the item you clicked on. But if you had clicked on this item and
  47319. dragged it, you'd have expected them all to stay selected.
  47320. When you call this method, you'll need to store the boolean result, because the
  47321. addToSelectionOnMouseUp() method will need to be know this value.
  47322. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  47323. */
  47324. bool addToSelectionOnMouseDown (ParameterType item,
  47325. const ModifierKeys& modifiers)
  47326. {
  47327. if (isSelected (item))
  47328. {
  47329. return ! modifiers.isPopupMenu();
  47330. }
  47331. else
  47332. {
  47333. addToSelectionBasedOnModifiers (item, modifiers);
  47334. return false;
  47335. }
  47336. }
  47337. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  47338. Call this during a mouseUp callback, when you have previously called the
  47339. addToSelectionOnMouseDown() method during your mouseDown event.
  47340. See addToSelectionOnMouseDown() for more info
  47341. @param item the item to select (or deselect)
  47342. @param modifiers the modifiers from the mouse-up event
  47343. @param wasItemDragged true if your item was dragged during the mouse click
  47344. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  47345. back from the addToSelectionOnMouseDown() call that you
  47346. should have made during the matching mouseDown event
  47347. */
  47348. void addToSelectionOnMouseUp (ParameterType item,
  47349. const ModifierKeys& modifiers,
  47350. const bool wasItemDragged,
  47351. const bool resultOfMouseDownSelectMethod)
  47352. {
  47353. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  47354. addToSelectionBasedOnModifiers (item, modifiers);
  47355. }
  47356. /** Deselects an item. */
  47357. void deselect (ParameterType item)
  47358. {
  47359. const int i = selectedItems.indexOf (item);
  47360. if (i >= 0)
  47361. {
  47362. changed();
  47363. itemDeselected (selectedItems.remove (i));
  47364. }
  47365. }
  47366. /** Deselects all items. */
  47367. void deselectAll()
  47368. {
  47369. if (selectedItems.size() > 0)
  47370. {
  47371. changed();
  47372. for (int i = selectedItems.size(); --i >= 0;)
  47373. {
  47374. itemDeselected (selectedItems.remove (i));
  47375. i = jmin (i, selectedItems.size());
  47376. }
  47377. }
  47378. }
  47379. /** Returns the number of currently selected items.
  47380. @see getSelectedItem
  47381. */
  47382. int getNumSelected() const noexcept
  47383. {
  47384. return selectedItems.size();
  47385. }
  47386. /** Returns one of the currently selected items.
  47387. Returns 0 if the index is out-of-range.
  47388. @see getNumSelected
  47389. */
  47390. SelectableItemType getSelectedItem (const int index) const noexcept
  47391. {
  47392. return selectedItems [index];
  47393. }
  47394. /** True if this item is currently selected. */
  47395. bool isSelected (ParameterType item) const noexcept
  47396. {
  47397. return selectedItems.contains (item);
  47398. }
  47399. const Array <SelectableItemType>& getItemArray() const noexcept { return selectedItems; }
  47400. /** Can be overridden to do special handling when an item is selected.
  47401. For example, if the item is an object, you might want to call it and tell
  47402. it that it's being selected.
  47403. */
  47404. virtual void itemSelected (SelectableItemType item) { (void) item; }
  47405. /** Can be overridden to do special handling when an item is deselected.
  47406. For example, if the item is an object, you might want to call it and tell
  47407. it that it's being deselected.
  47408. */
  47409. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  47410. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  47411. */
  47412. void changed (const bool synchronous = false)
  47413. {
  47414. if (synchronous)
  47415. sendSynchronousChangeMessage();
  47416. else
  47417. sendChangeMessage();
  47418. }
  47419. private:
  47420. Array <SelectableItemType> selectedItems;
  47421. JUCE_LEAK_DETECTOR (SelectedItemSet <SelectableItemType>);
  47422. };
  47423. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  47424. /*** End of inlined file: juce_SelectedItemSet.h ***/
  47425. /**
  47426. A class used by the LassoComponent to manage the things that it selects.
  47427. This allows the LassoComponent to find out which items are within the lasso,
  47428. and to change the list of selected items.
  47429. @see LassoComponent, SelectedItemSet
  47430. */
  47431. template <class SelectableItemType>
  47432. class LassoSource
  47433. {
  47434. public:
  47435. /** Destructor. */
  47436. virtual ~LassoSource() {}
  47437. /** Returns the set of items that lie within a given lassoable region.
  47438. Your implementation of this method must find all the relevent items that lie
  47439. within the given rectangle. and add them to the itemsFound array.
  47440. The co-ordinates are relative to the top-left of the lasso component's parent
  47441. component. (i.e. they are the same as the size and position of the lasso
  47442. component itself).
  47443. */
  47444. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  47445. const Rectangle<int>& area) = 0;
  47446. /** Returns the SelectedItemSet that the lasso should update.
  47447. This set will be continuously updated by the LassoComponent as it gets
  47448. dragged around, so make sure that you've got a ChangeListener attached to
  47449. the set so that your UI objects will know when the selection changes and
  47450. be able to update themselves appropriately.
  47451. */
  47452. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  47453. };
  47454. /**
  47455. A component that acts as a rectangular selection region, which you drag with
  47456. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  47457. To use one of these:
  47458. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  47459. component, and call its beginLasso() method, giving it a
  47460. suitable LassoSource object that it can use to find out which items are in
  47461. the active area.
  47462. - Each time your parent component gets a mouseDrag event, call dragLasso()
  47463. to update the lasso's position - it will use its LassoSource to calculate and
  47464. update the current selection.
  47465. - After the drag has finished and you get a mouseUp callback, you should call
  47466. endLasso() to clean up. This will make the lasso component invisible, and you
  47467. can remove it from the parent component, or delete it.
  47468. The class takes into account the modifier keys that are being held down while
  47469. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  47470. be added to the original selection; if ctrl or command is pressed, they will be
  47471. xor'ed with any previously selected items.
  47472. @see LassoSource, SelectedItemSet
  47473. */
  47474. template <class SelectableItemType>
  47475. class LassoComponent : public Component
  47476. {
  47477. public:
  47478. /** Creates a Lasso component.
  47479. The fill colour is used to fill the lasso'ed rectangle, and the outline
  47480. colour is used to draw a line around its edge.
  47481. */
  47482. explicit LassoComponent (const int outlineThickness_ = 1)
  47483. : source (nullptr),
  47484. outlineThickness (outlineThickness_)
  47485. {
  47486. }
  47487. /** Destructor. */
  47488. ~LassoComponent()
  47489. {
  47490. }
  47491. /** Call this in your mouseDown event, to initialise a drag.
  47492. Pass in a suitable LassoSource object which the lasso will use to find
  47493. the items and change the selection.
  47494. After using this method to initialise the lasso, repeatedly call dragLasso()
  47495. in your component's mouseDrag callback.
  47496. @see dragLasso, endLasso, LassoSource
  47497. */
  47498. void beginLasso (const MouseEvent& e,
  47499. LassoSource <SelectableItemType>* const lassoSource)
  47500. {
  47501. jassert (source == nullptr); // this suggests that you didn't call endLasso() after the last drag...
  47502. jassert (lassoSource != nullptr); // the source can't be null!
  47503. jassert (getParentComponent() != nullptr); // you need to add this to a parent component for it to work!
  47504. source = lassoSource;
  47505. if (lassoSource != nullptr)
  47506. originalSelection = lassoSource->getLassoSelection().getItemArray();
  47507. setSize (0, 0);
  47508. dragStartPos = e.getMouseDownPosition();
  47509. }
  47510. /** Call this in your mouseDrag event, to update the lasso's position.
  47511. This must be repeatedly calling when the mouse is dragged, after you've
  47512. first initialised the lasso with beginLasso().
  47513. This method takes into account the modifier keys that are being held down, so
  47514. if shift is pressed, then the lassoed items will be added to any that were
  47515. previously selected; if ctrl or command is pressed, then they will be xor'ed
  47516. with previously selected items.
  47517. @see beginLasso, endLasso
  47518. */
  47519. void dragLasso (const MouseEvent& e)
  47520. {
  47521. if (source != nullptr)
  47522. {
  47523. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  47524. setVisible (true);
  47525. Array <SelectableItemType> itemsInLasso;
  47526. source->findLassoItemsInArea (itemsInLasso, getBounds());
  47527. if (e.mods.isShiftDown())
  47528. {
  47529. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  47530. itemsInLasso.addArray (originalSelection);
  47531. }
  47532. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  47533. {
  47534. Array <SelectableItemType> originalMinusNew (originalSelection);
  47535. originalMinusNew.removeValuesIn (itemsInLasso);
  47536. itemsInLasso.removeValuesIn (originalSelection);
  47537. itemsInLasso.addArray (originalMinusNew);
  47538. }
  47539. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  47540. }
  47541. }
  47542. /** Call this in your mouseUp event, after the lasso has been dragged.
  47543. @see beginLasso, dragLasso
  47544. */
  47545. void endLasso()
  47546. {
  47547. source = nullptr;
  47548. originalSelection.clear();
  47549. setVisible (false);
  47550. }
  47551. /** A set of colour IDs to use to change the colour of various aspects of the label.
  47552. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  47553. methods.
  47554. Note that you can also use the constants from TextEditor::ColourIds to change the
  47555. colour of the text editor that is opened when a label is editable.
  47556. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  47557. */
  47558. enum ColourIds
  47559. {
  47560. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  47561. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  47562. };
  47563. /** @internal */
  47564. void paint (Graphics& g)
  47565. {
  47566. g.fillAll (findColour (lassoFillColourId));
  47567. g.setColour (findColour (lassoOutlineColourId));
  47568. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  47569. // this suggests that you've left a lasso comp lying around after the
  47570. // mouse drag has finished.. Be careful to call endLasso() when you get a
  47571. // mouse-up event.
  47572. jassert (isMouseButtonDownAnywhere());
  47573. }
  47574. /** @internal */
  47575. bool hitTest (int, int) { return false; }
  47576. private:
  47577. Array <SelectableItemType> originalSelection;
  47578. LassoSource <SelectableItemType>* source;
  47579. int outlineThickness;
  47580. Point<int> dragStartPos;
  47581. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LassoComponent);
  47582. };
  47583. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  47584. /*** End of inlined file: juce_LassoComponent.h ***/
  47585. #endif
  47586. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  47587. #endif
  47588. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  47589. #endif
  47590. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  47591. /*** Start of inlined file: juce_MouseInputSource.h ***/
  47592. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  47593. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  47594. class MouseInputSourceInternal;
  47595. /**
  47596. Represents a linear source of mouse events from a mouse device or individual finger
  47597. in a multi-touch environment.
  47598. Each MouseEvent object contains a reference to the MouseInputSource that generated
  47599. it. In an environment with a single mouse for input, all events will come from the
  47600. same source, but in a multi-touch system, there may be multiple MouseInputSource
  47601. obects active, each representing a stream of events coming from a particular finger.
  47602. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  47603. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  47604. the only events that can happen between a mouseDown and its corresponding mouseUp are
  47605. mouseDrags, etc.
  47606. When there are multiple touches arriving from multiple MouseInputSources, their
  47607. event streams may arrive in an interleaved order, so you should use the getIndex()
  47608. method to find out which finger each event came from.
  47609. @see MouseEvent
  47610. */
  47611. class JUCE_API MouseInputSource
  47612. {
  47613. public:
  47614. /** Creates a MouseInputSource.
  47615. You should never actually create a MouseInputSource in your own code - the
  47616. library takes care of managing these objects.
  47617. */
  47618. MouseInputSource (int index, bool isMouseDevice);
  47619. /** Destructor. */
  47620. ~MouseInputSource();
  47621. /** Returns true if this object represents a normal desk-based mouse device. */
  47622. bool isMouse() const;
  47623. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  47624. bool isTouch() const;
  47625. /** Returns true if this source has an on-screen pointer that can hover over
  47626. items without clicking them.
  47627. */
  47628. bool canHover() const;
  47629. /** Returns true if this source may have a scroll wheel. */
  47630. bool hasMouseWheel() const;
  47631. /** Returns this source's index in the global list of possible sources.
  47632. If the system only has a single mouse, there will only be a single MouseInputSource
  47633. with an index of 0.
  47634. If the system supports multi-touch input, then the index will represent a finger
  47635. number, starting from 0. When the first touch event begins, it will have finger
  47636. number 0, and then if a second touch happens while the first is still down, it
  47637. will have index 1, etc.
  47638. */
  47639. int getIndex() const;
  47640. /** Returns true if this device is currently being pressed. */
  47641. bool isDragging() const;
  47642. /** Returns the last-known screen position of this source. */
  47643. const Point<int> getScreenPosition() const;
  47644. /** Returns a set of modifiers that indicate which buttons are currently
  47645. held down on this device.
  47646. */
  47647. const ModifierKeys getCurrentModifiers() const;
  47648. /** Returns the component that was last known to be under this pointer. */
  47649. Component* getComponentUnderMouse() const;
  47650. /** Tells the device to dispatch a mouse-move or mouse-drag event.
  47651. This is asynchronous - the event will occur on the message thread.
  47652. */
  47653. void triggerFakeMove() const;
  47654. /** Returns the number of clicks that should be counted as belonging to the
  47655. current mouse event.
  47656. So the mouse is currently down and it's the second click of a double-click, this
  47657. will return 2.
  47658. */
  47659. int getNumberOfMultipleClicks() const noexcept;
  47660. /** Returns the time at which the last mouse-down occurred. */
  47661. Time getLastMouseDownTime() const noexcept;
  47662. /** Returns the screen position at which the last mouse-down occurred. */
  47663. Point<int> getLastMouseDownPosition() const noexcept;
  47664. /** Returns true if this mouse is currently down, and if it has been dragged more
  47665. than a couple of pixels from the place it was pressed.
  47666. */
  47667. bool hasMouseMovedSignificantlySincePressed() const noexcept;
  47668. /** Returns true if this input source uses a visible mouse cursor. */
  47669. bool hasMouseCursor() const noexcept;
  47670. /** Changes the mouse cursor, (if there is one). */
  47671. void showMouseCursor (const MouseCursor& cursor);
  47672. /** Hides the mouse cursor (if there is one). */
  47673. void hideCursor();
  47674. /** Un-hides the mouse cursor if it was hidden by hideCursor(). */
  47675. void revealCursor();
  47676. /** Forces an update of the mouse cursor for whatever component it's currently over. */
  47677. void forceMouseCursorUpdate();
  47678. /** Returns true if this mouse can be moved indefinitely in any direction without running out of space. */
  47679. bool canDoUnboundedMovement() const noexcept;
  47680. /** Allows the mouse to move beyond the edges of the screen.
  47681. Calling this method when the mouse button is currently pressed will remove the cursor
  47682. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  47683. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  47684. can be used for things like custom slider controls or dragging objects around, where
  47685. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  47686. The unbounded mode is automatically turned off when the mouse button is released, or
  47687. it can be turned off explicitly by calling this method again.
  47688. @param isEnabled whether to turn this mode on or off
  47689. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  47690. hidden; if true, it will only be hidden when it
  47691. is moved beyond the edge of the screen
  47692. */
  47693. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  47694. /** @internal */
  47695. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  47696. /** @internal */
  47697. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  47698. private:
  47699. friend class Desktop;
  47700. friend class ComponentPeer;
  47701. friend class MouseInputSourceInternal;
  47702. ScopedPointer<MouseInputSourceInternal> pimpl;
  47703. static const Point<int> getCurrentMousePosition();
  47704. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseInputSource);
  47705. };
  47706. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  47707. /*** End of inlined file: juce_MouseInputSource.h ***/
  47708. #endif
  47709. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  47710. #endif
  47711. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  47712. #endif
  47713. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  47714. #endif
  47715. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  47716. #endif
  47717. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  47718. #endif
  47719. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47720. /*** Start of inlined file: juce_RelativeParallelogram.h ***/
  47721. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47722. #define __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47723. /**
  47724. A parallelogram defined by three RelativePoint positions.
  47725. @see RelativePoint, RelativeCoordinate
  47726. */
  47727. class JUCE_API RelativeParallelogram
  47728. {
  47729. public:
  47730. RelativeParallelogram();
  47731. RelativeParallelogram (const Rectangle<float>& simpleRectangle);
  47732. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  47733. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  47734. ~RelativeParallelogram();
  47735. void resolveThreePoints (Point<float>* points, Expression::Scope* scope) const;
  47736. void resolveFourCorners (Point<float>* points, Expression::Scope* scope) const;
  47737. const Rectangle<float> getBounds (Expression::Scope* scope) const;
  47738. void getPath (Path& path, Expression::Scope* scope) const;
  47739. const AffineTransform resetToPerpendicular (Expression::Scope* scope);
  47740. bool isDynamic() const;
  47741. bool operator== (const RelativeParallelogram& other) const noexcept;
  47742. bool operator!= (const RelativeParallelogram& other) const noexcept;
  47743. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) noexcept;
  47744. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) noexcept;
  47745. static const Rectangle<float> getBoundingBox (const Point<float>* parallelogramCorners) noexcept;
  47746. RelativePoint topLeft, topRight, bottomLeft;
  47747. };
  47748. #endif // __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  47749. /*** End of inlined file: juce_RelativeParallelogram.h ***/
  47750. #endif
  47751. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  47752. #endif
  47753. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47754. /*** Start of inlined file: juce_RelativePointPath.h ***/
  47755. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47756. #define __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47757. class DrawablePath;
  47758. /**
  47759. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  47760. One of these paths can be converted into a Path object for drawing and manipulation, but
  47761. unlike a Path, its points can be dynamic instead of just fixed.
  47762. @see RelativePoint, RelativeCoordinate
  47763. */
  47764. class JUCE_API RelativePointPath
  47765. {
  47766. public:
  47767. RelativePointPath();
  47768. RelativePointPath (const RelativePointPath& other);
  47769. explicit RelativePointPath (const Path& path);
  47770. ~RelativePointPath();
  47771. bool operator== (const RelativePointPath& other) const noexcept;
  47772. bool operator!= (const RelativePointPath& other) const noexcept;
  47773. /** Resolves this points in this path and adds them to a normal Path object. */
  47774. void createPath (Path& path, Expression::Scope* scope) const;
  47775. /** Returns true if the path contains any non-fixed points. */
  47776. bool containsAnyDynamicPoints() const;
  47777. /** Quickly swaps the contents of this path with another. */
  47778. void swapWith (RelativePointPath& other) noexcept;
  47779. /** The types of element that may be contained in this path.
  47780. @see RelativePointPath::ElementBase
  47781. */
  47782. enum ElementType
  47783. {
  47784. nullElement,
  47785. startSubPathElement,
  47786. closeSubPathElement,
  47787. lineToElement,
  47788. quadraticToElement,
  47789. cubicToElement
  47790. };
  47791. /** Base class for the elements that make up a RelativePointPath.
  47792. */
  47793. class JUCE_API ElementBase
  47794. {
  47795. public:
  47796. ElementBase (ElementType type);
  47797. virtual ~ElementBase() {}
  47798. virtual ValueTree createTree() const = 0;
  47799. virtual void addToPath (Path& path, Expression::Scope*) const = 0;
  47800. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  47801. virtual ElementBase* clone() const = 0;
  47802. bool isDynamic();
  47803. const ElementType type;
  47804. private:
  47805. JUCE_DECLARE_NON_COPYABLE (ElementBase);
  47806. };
  47807. class JUCE_API StartSubPath : public ElementBase
  47808. {
  47809. public:
  47810. StartSubPath (const RelativePoint& pos);
  47811. ValueTree createTree() const;
  47812. void addToPath (Path& path, Expression::Scope*) const;
  47813. RelativePoint* getControlPoints (int& numPoints);
  47814. ElementBase* clone() const;
  47815. RelativePoint startPos;
  47816. private:
  47817. JUCE_DECLARE_NON_COPYABLE (StartSubPath);
  47818. };
  47819. class JUCE_API CloseSubPath : public ElementBase
  47820. {
  47821. public:
  47822. CloseSubPath();
  47823. ValueTree createTree() const;
  47824. void addToPath (Path& path, Expression::Scope*) const;
  47825. RelativePoint* getControlPoints (int& numPoints);
  47826. ElementBase* clone() const;
  47827. private:
  47828. JUCE_DECLARE_NON_COPYABLE (CloseSubPath);
  47829. };
  47830. class JUCE_API LineTo : public ElementBase
  47831. {
  47832. public:
  47833. LineTo (const RelativePoint& endPoint);
  47834. ValueTree createTree() const;
  47835. void addToPath (Path& path, Expression::Scope*) const;
  47836. RelativePoint* getControlPoints (int& numPoints);
  47837. ElementBase* clone() const;
  47838. RelativePoint endPoint;
  47839. private:
  47840. JUCE_DECLARE_NON_COPYABLE (LineTo);
  47841. };
  47842. class JUCE_API QuadraticTo : public ElementBase
  47843. {
  47844. public:
  47845. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  47846. ValueTree createTree() const;
  47847. void addToPath (Path& path, Expression::Scope*) const;
  47848. RelativePoint* getControlPoints (int& numPoints);
  47849. ElementBase* clone() const;
  47850. RelativePoint controlPoints[2];
  47851. private:
  47852. JUCE_DECLARE_NON_COPYABLE (QuadraticTo);
  47853. };
  47854. class JUCE_API CubicTo : public ElementBase
  47855. {
  47856. public:
  47857. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  47858. ValueTree createTree() const;
  47859. void addToPath (Path& path, Expression::Scope*) const;
  47860. RelativePoint* getControlPoints (int& numPoints);
  47861. ElementBase* clone() const;
  47862. RelativePoint controlPoints[3];
  47863. private:
  47864. JUCE_DECLARE_NON_COPYABLE (CubicTo);
  47865. };
  47866. void addElement (ElementBase* newElement);
  47867. OwnedArray <ElementBase> elements;
  47868. bool usesNonZeroWinding;
  47869. private:
  47870. class Positioner;
  47871. friend class Positioner;
  47872. bool containsDynamicPoints;
  47873. void applyTo (DrawablePath& path) const;
  47874. RelativePointPath& operator= (const RelativePointPath&);
  47875. JUCE_LEAK_DETECTOR (RelativePointPath);
  47876. };
  47877. #endif // __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  47878. /*** End of inlined file: juce_RelativePointPath.h ***/
  47879. #endif
  47880. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47881. /*** Start of inlined file: juce_RelativeRectangle.h ***/
  47882. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47883. #define __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47884. class Component;
  47885. /**
  47886. An rectangle stored as a set of RelativeCoordinate values.
  47887. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  47888. @see RelativeCoordinate, RelativePoint
  47889. */
  47890. class JUCE_API RelativeRectangle
  47891. {
  47892. public:
  47893. /** Creates a zero-size rectangle at the origin. */
  47894. RelativeRectangle();
  47895. /** Creates an absolute rectangle, relative to the origin. */
  47896. explicit RelativeRectangle (const Rectangle<float>& rect);
  47897. /** Creates a rectangle from four coordinates. */
  47898. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  47899. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  47900. /** Creates a rectangle from a stringified representation.
  47901. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  47902. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  47903. RelativeCoordinate class.
  47904. @see toString
  47905. */
  47906. explicit RelativeRectangle (const String& stringVersion);
  47907. bool operator== (const RelativeRectangle& other) const noexcept;
  47908. bool operator!= (const RelativeRectangle& other) const noexcept;
  47909. /** Calculates the absolute position of this rectangle.
  47910. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  47911. be needed to calculate the result.
  47912. */
  47913. const Rectangle<float> resolve (const Expression::Scope* scope) const;
  47914. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  47915. Calling this will leave any anchor points unchanged, but will set any absolute
  47916. or relative positions to whatever values are necessary to make the resultant position
  47917. match the position that is provided.
  47918. */
  47919. void moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope);
  47920. /** Returns true if this rectangle depends on any external symbols for its position.
  47921. Coordinates that refer to symbols based on "this" are assumed not to be dynamic.
  47922. */
  47923. bool isDynamic() const;
  47924. /** Returns a string which represents this point.
  47925. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  47926. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  47927. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  47928. */
  47929. String toString() const;
  47930. /** Renames a symbol if it is used by any of the coordinates.
  47931. This calls Expression::withRenamedSymbol() on the rectangle's coordinates.
  47932. */
  47933. void renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope);
  47934. /** Creates and sets an appropriate Component::Positioner object for the given component, which will
  47935. keep it positioned with this rectangle.
  47936. */
  47937. void applyToComponent (Component& component) const;
  47938. // The actual rectangle coords...
  47939. RelativeCoordinate left, right, top, bottom;
  47940. };
  47941. #endif // __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47942. /*** End of inlined file: juce_RelativeRectangle.h ***/
  47943. #endif
  47944. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47945. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  47946. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47947. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47948. /**
  47949. A PropertyComponent that contains an on/off toggle button.
  47950. This type of property component can be used if you have a boolean value to
  47951. toggle on/off.
  47952. @see PropertyComponent
  47953. */
  47954. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  47955. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  47956. {
  47957. protected:
  47958. /** Creates a button component.
  47959. If you use this constructor, you must override the getState() and setState()
  47960. methods.
  47961. @param propertyName the property name to be passed to the PropertyComponent
  47962. @param buttonTextWhenTrue the text shown in the button when the value is true
  47963. @param buttonTextWhenFalse the text shown in the button when the value is false
  47964. */
  47965. BooleanPropertyComponent (const String& propertyName,
  47966. const String& buttonTextWhenTrue,
  47967. const String& buttonTextWhenFalse);
  47968. public:
  47969. /** Creates a button component.
  47970. @param valueToControl a Value object that this property should refer to.
  47971. @param propertyName the property name to be passed to the PropertyComponent
  47972. @param buttonText the text shown in the ToggleButton component
  47973. */
  47974. BooleanPropertyComponent (const Value& valueToControl,
  47975. const String& propertyName,
  47976. const String& buttonText);
  47977. /** Destructor. */
  47978. ~BooleanPropertyComponent();
  47979. /** Called to change the state of the boolean value. */
  47980. virtual void setState (bool newState);
  47981. /** Must return the current value of the property. */
  47982. virtual bool getState() const;
  47983. /** @internal */
  47984. void paint (Graphics& g);
  47985. /** @internal */
  47986. void refresh();
  47987. /** @internal */
  47988. void buttonClicked (Button*);
  47989. private:
  47990. ToggleButton button;
  47991. String onText, offText;
  47992. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BooleanPropertyComponent);
  47993. };
  47994. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47995. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  47996. #endif
  47997. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47998. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  47999. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  48000. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  48001. /**
  48002. A PropertyComponent that contains a button.
  48003. This type of property component can be used if you need a button to trigger some
  48004. kind of action.
  48005. @see PropertyComponent
  48006. */
  48007. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  48008. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  48009. {
  48010. public:
  48011. /** Creates a button component.
  48012. @param propertyName the property name to be passed to the PropertyComponent
  48013. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  48014. */
  48015. ButtonPropertyComponent (const String& propertyName,
  48016. bool triggerOnMouseDown);
  48017. /** Destructor. */
  48018. ~ButtonPropertyComponent();
  48019. /** Called when the user clicks the button.
  48020. */
  48021. virtual void buttonClicked() = 0;
  48022. /** Returns the string that should be displayed in the button.
  48023. If you need to change this string, call refresh() to update the component.
  48024. */
  48025. virtual const String getButtonText() const = 0;
  48026. /** @internal */
  48027. void refresh();
  48028. /** @internal */
  48029. void buttonClicked (Button*);
  48030. private:
  48031. TextButton button;
  48032. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonPropertyComponent);
  48033. };
  48034. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  48035. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  48036. #endif
  48037. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  48038. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  48039. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  48040. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  48041. /**
  48042. A PropertyComponent that shows its value as a combo box.
  48043. This type of property component contains a list of options and has a
  48044. combo box to choose one.
  48045. Your subclass's constructor must add some strings to the choices StringArray
  48046. and these are shown in the list.
  48047. The getIndex() method will be called to find out which option is the currently
  48048. selected one. If you call refresh() it will call getIndex() to check whether
  48049. the value has changed, and will update the combo box if needed.
  48050. If the user selects a different item from the list, setIndex() will be
  48051. called to let your class process this.
  48052. @see PropertyComponent, PropertyPanel
  48053. */
  48054. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  48055. private ComboBoxListener // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  48056. {
  48057. protected:
  48058. /** Creates the component.
  48059. Your subclass's constructor must add a list of options to the choices
  48060. member variable.
  48061. */
  48062. ChoicePropertyComponent (const String& propertyName);
  48063. public:
  48064. /** Creates the component.
  48065. @param valueToControl the value that the combo box will read and control
  48066. @param propertyName the name of the property
  48067. @param choices the list of possible values that the drop-down list will contain
  48068. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  48069. These are the values that will be read and written to the
  48070. valueToControl value. This array must contain the same number of items
  48071. as the choices array
  48072. */
  48073. ChoicePropertyComponent (const Value& valueToControl,
  48074. const String& propertyName,
  48075. const StringArray& choices,
  48076. const Array <var>& correspondingValues);
  48077. /** Destructor. */
  48078. ~ChoicePropertyComponent();
  48079. /** Called when the user selects an item from the combo box.
  48080. Your subclass must use this callback to update the value that this component
  48081. represents. The index is the index of the chosen item in the choices
  48082. StringArray.
  48083. */
  48084. virtual void setIndex (int newIndex);
  48085. /** Returns the index of the item that should currently be shown.
  48086. This is the index of the item in the choices StringArray that will be
  48087. shown.
  48088. */
  48089. virtual int getIndex() const;
  48090. /** Returns the list of options. */
  48091. const StringArray& getChoices() const;
  48092. /** @internal */
  48093. void refresh();
  48094. /** @internal */
  48095. void comboBoxChanged (ComboBox*);
  48096. protected:
  48097. /** The list of options that will be shown in the combo box.
  48098. Your subclass must populate this array in its constructor. If any empty
  48099. strings are added, these will be replaced with horizontal separators (see
  48100. ComboBox::addSeparator() for more info).
  48101. */
  48102. StringArray choices;
  48103. private:
  48104. ComboBox comboBox;
  48105. bool isCustomClass;
  48106. class RemapperValueSource;
  48107. void createComboBox();
  48108. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChoicePropertyComponent);
  48109. };
  48110. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  48111. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  48112. #endif
  48113. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  48114. #endif
  48115. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  48116. #endif
  48117. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  48118. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  48119. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  48120. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  48121. /**
  48122. A PropertyComponent that shows its value as a slider.
  48123. @see PropertyComponent, Slider
  48124. */
  48125. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  48126. private SliderListener // (can't use Slider::Listener due to idiotic VC2005 bug)
  48127. {
  48128. protected:
  48129. /** Creates the property component.
  48130. The ranges, interval and skew factor are passed to the Slider component.
  48131. If you need to customise the slider in other ways, your constructor can
  48132. access the slider member variable and change it directly.
  48133. */
  48134. SliderPropertyComponent (const String& propertyName,
  48135. double rangeMin,
  48136. double rangeMax,
  48137. double interval,
  48138. double skewFactor = 1.0);
  48139. public:
  48140. /** Creates the property component.
  48141. The ranges, interval and skew factor are passed to the Slider component.
  48142. If you need to customise the slider in other ways, your constructor can
  48143. access the slider member variable and change it directly.
  48144. */
  48145. SliderPropertyComponent (const Value& valueToControl,
  48146. const String& propertyName,
  48147. double rangeMin,
  48148. double rangeMax,
  48149. double interval,
  48150. double skewFactor = 1.0);
  48151. /** Destructor. */
  48152. ~SliderPropertyComponent();
  48153. /** Called when the user moves the slider to change its value.
  48154. Your subclass must use this method to update whatever item this property
  48155. represents.
  48156. */
  48157. virtual void setValue (double newValue);
  48158. /** Returns the value that the slider should show. */
  48159. virtual double getValue() const;
  48160. /** @internal */
  48161. void refresh();
  48162. /** @internal */
  48163. void sliderValueChanged (Slider*);
  48164. protected:
  48165. /** The slider component being used in this component.
  48166. Your subclass has access to this in case it needs to customise it in some way.
  48167. */
  48168. Slider slider;
  48169. private:
  48170. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPropertyComponent);
  48171. };
  48172. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  48173. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  48174. #endif
  48175. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  48176. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  48177. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  48178. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  48179. /**
  48180. A PropertyComponent that shows its value as editable text.
  48181. @see PropertyComponent
  48182. */
  48183. class JUCE_API TextPropertyComponent : public PropertyComponent
  48184. {
  48185. protected:
  48186. /** Creates a text property component.
  48187. The maxNumChars is used to set the length of string allowable, and isMultiLine
  48188. sets whether the text editor allows carriage returns.
  48189. @see TextEditor
  48190. */
  48191. TextPropertyComponent (const String& propertyName,
  48192. int maxNumChars,
  48193. bool isMultiLine);
  48194. public:
  48195. /** Creates a text property component.
  48196. The maxNumChars is used to set the length of string allowable, and isMultiLine
  48197. sets whether the text editor allows carriage returns.
  48198. @see TextEditor
  48199. */
  48200. TextPropertyComponent (const Value& valueToControl,
  48201. const String& propertyName,
  48202. int maxNumChars,
  48203. bool isMultiLine);
  48204. /** Destructor. */
  48205. ~TextPropertyComponent();
  48206. /** Called when the user edits the text.
  48207. Your subclass must use this callback to change the value of whatever item
  48208. this property component represents.
  48209. */
  48210. virtual void setText (const String& newText);
  48211. /** Returns the text that should be shown in the text editor.
  48212. */
  48213. virtual const String getText() const;
  48214. /** @internal */
  48215. void refresh();
  48216. /** @internal */
  48217. void textWasEdited();
  48218. private:
  48219. ScopedPointer<Label> textEditor;
  48220. void createEditor (int maxNumChars, bool isMultiLine);
  48221. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextPropertyComponent);
  48222. };
  48223. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  48224. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  48225. #endif
  48226. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  48227. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  48228. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  48229. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  48230. #if JUCE_WINDOWS || DOXYGEN
  48231. /**
  48232. A Windows-specific class that can create and embed an ActiveX control inside
  48233. itself.
  48234. To use it, create one of these, put it in place and make sure it's visible in a
  48235. window, then use createControl() to instantiate an ActiveX control. The control
  48236. will then be moved and resized to follow the movements of this component.
  48237. Of course, since the control is a heavyweight window, it'll obliterate any
  48238. juce components that may overlap this component, but that's life.
  48239. */
  48240. class JUCE_API ActiveXControlComponent : public Component
  48241. {
  48242. public:
  48243. /** Create an initially-empty container. */
  48244. ActiveXControlComponent();
  48245. /** Destructor. */
  48246. ~ActiveXControlComponent();
  48247. /** Tries to create an ActiveX control and embed it in this peer.
  48248. The peer controlIID is a pointer to an IID structure - it's treated
  48249. as a void* because when including the Juce headers, you might not always
  48250. have included windows.h first, in which case IID wouldn't be defined.
  48251. e.g. @code
  48252. const IID myIID = __uuidof (QTControl);
  48253. myControlComp->createControl (&myIID);
  48254. @endcode
  48255. */
  48256. bool createControl (const void* controlIID);
  48257. /** Deletes the ActiveX control, if one has been created.
  48258. */
  48259. void deleteControl();
  48260. /** Returns true if a control is currently in use. */
  48261. bool isControlOpen() const noexcept { return control != nullptr; }
  48262. /** Does a QueryInterface call on the embedded control object.
  48263. This allows you to cast the control to whatever type of COM object you need.
  48264. The iid parameter is a pointer to an IID structure - it's treated
  48265. as a void* because when including the Juce headers, you might not always
  48266. have included windows.h first, in which case IID wouldn't be defined, but
  48267. you should just pass a pointer to an IID.
  48268. e.g. @code
  48269. const IID iid = __uuidof (IOleWindow);
  48270. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  48271. if (oleWindow != nullptr)
  48272. {
  48273. HWND hwnd;
  48274. oleWindow->GetWindow (&hwnd);
  48275. ...
  48276. oleWindow->Release();
  48277. }
  48278. @endcode
  48279. */
  48280. void* queryInterface (const void* iid) const;
  48281. /** Set this to false to stop mouse events being allowed through to the control.
  48282. */
  48283. void setMouseEventsAllowed (bool eventsCanReachControl);
  48284. /** Returns true if mouse events are allowed to get through to the control.
  48285. */
  48286. bool areMouseEventsAllowed() const noexcept { return mouseEventsAllowed; }
  48287. /** @internal */
  48288. void paint (Graphics& g);
  48289. /** @internal */
  48290. void* originalWndProc;
  48291. private:
  48292. class Pimpl;
  48293. friend class Pimpl;
  48294. friend class ScopedPointer <Pimpl>;
  48295. ScopedPointer <Pimpl> control;
  48296. bool mouseEventsAllowed;
  48297. void setControlBounds (const Rectangle<int>& bounds) const;
  48298. void setControlVisible (bool b) const;
  48299. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ActiveXControlComponent);
  48300. };
  48301. #endif
  48302. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  48303. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  48304. #endif
  48305. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  48306. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  48307. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  48308. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  48309. /**
  48310. A component containing controls to let the user change the audio settings of
  48311. an AudioDeviceManager object.
  48312. Very easy to use - just create one of these and show it to the user.
  48313. @see AudioDeviceManager
  48314. */
  48315. class JUCE_API AudioDeviceSelectorComponent : public Component,
  48316. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  48317. public ButtonListener,
  48318. public ChangeListener
  48319. {
  48320. public:
  48321. /** Creates the component.
  48322. If your app needs only output channels, you might ask for a maximum of 0 input
  48323. channels, and the component won't display any options for choosing the input
  48324. channels. And likewise if you're doing an input-only app.
  48325. @param deviceManager the device manager that this component should control
  48326. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  48327. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  48328. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  48329. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  48330. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  48331. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  48332. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  48333. treated as a set of separate mono channels.
  48334. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  48335. are shown, with an "advanced" button that shows the rest of them
  48336. */
  48337. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  48338. const int minAudioInputChannels,
  48339. const int maxAudioInputChannels,
  48340. const int minAudioOutputChannels,
  48341. const int maxAudioOutputChannels,
  48342. const bool showMidiInputOptions,
  48343. const bool showMidiOutputSelector,
  48344. const bool showChannelsAsStereoPairs,
  48345. const bool hideAdvancedOptionsWithButton);
  48346. /** Destructor */
  48347. ~AudioDeviceSelectorComponent();
  48348. /** @internal */
  48349. void resized();
  48350. /** @internal */
  48351. void comboBoxChanged (ComboBox*);
  48352. /** @internal */
  48353. void buttonClicked (Button*);
  48354. /** @internal */
  48355. void changeListenerCallback (ChangeBroadcaster*);
  48356. /** @internal */
  48357. void childBoundsChanged (Component*);
  48358. private:
  48359. AudioDeviceManager& deviceManager;
  48360. ScopedPointer<ComboBox> deviceTypeDropDown;
  48361. ScopedPointer<Label> deviceTypeDropDownLabel;
  48362. ScopedPointer<Component> audioDeviceSettingsComp;
  48363. String audioDeviceSettingsCompType;
  48364. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  48365. const bool showChannelsAsStereoPairs;
  48366. const bool hideAdvancedOptionsWithButton;
  48367. class MidiInputSelectorComponentListBox;
  48368. friend class ScopedPointer<MidiInputSelectorComponentListBox>;
  48369. ScopedPointer<MidiInputSelectorComponentListBox> midiInputsList;
  48370. ScopedPointer<ComboBox> midiOutputSelector;
  48371. ScopedPointer<Label> midiInputsLabel, midiOutputLabel;
  48372. void updateAllControls();
  48373. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceSelectorComponent);
  48374. };
  48375. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  48376. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  48377. #endif
  48378. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  48379. /*** Start of inlined file: juce_BubbleComponent.h ***/
  48380. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  48381. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  48382. /**
  48383. A component for showing a message or other graphics inside a speech-bubble-shaped
  48384. outline, pointing at a location on the screen.
  48385. This is a base class that just draws and positions the bubble shape, but leaves
  48386. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  48387. that draws a text message.
  48388. To use it, create your subclass, then either add it to a parent component or
  48389. put it on the desktop with addToDesktop (0), use setPosition() to
  48390. resize and position it, then make it visible.
  48391. @see BubbleMessageComponent
  48392. */
  48393. class JUCE_API BubbleComponent : public Component
  48394. {
  48395. protected:
  48396. /** Creates a BubbleComponent.
  48397. Your subclass will need to implement the getContentSize() and paintContent()
  48398. methods to draw the bubble's contents.
  48399. */
  48400. BubbleComponent();
  48401. public:
  48402. /** Destructor. */
  48403. ~BubbleComponent();
  48404. /** A list of permitted placements for the bubble, relative to the co-ordinates
  48405. at which it should be pointing.
  48406. @see setAllowedPlacement
  48407. */
  48408. enum BubblePlacement
  48409. {
  48410. above = 1,
  48411. below = 2,
  48412. left = 4,
  48413. right = 8
  48414. };
  48415. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  48416. point at which it's pointing.
  48417. By default when setPosition() is called, the bubble will place itself either
  48418. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  48419. the values in BubblePlacement to restrict this choice.
  48420. E.g. if you only want your bubble to appear above or below the target area,
  48421. use setAllowedPlacement (above | below);
  48422. @see BubblePlacement
  48423. */
  48424. void setAllowedPlacement (int newPlacement);
  48425. /** Moves and resizes the bubble to point at a given component.
  48426. This will resize the bubble to fit its content, then find a position for it
  48427. so that it's next to, but doesn't overlap the given component.
  48428. It'll put itself either above, below, or to the side of the component depending
  48429. on where there's the most space, honouring any restrictions that were set
  48430. with setAllowedPlacement().
  48431. */
  48432. void setPosition (Component* componentToPointTo);
  48433. /** Moves and resizes the bubble to point at a given point.
  48434. This will resize the bubble to fit its content, then position it
  48435. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  48436. are relative to either the bubble component's parent component if it has one, or
  48437. they are screen co-ordinates if not.
  48438. It'll put itself either above, below, or to the side of this point, depending
  48439. on where there's the most space, honouring any restrictions that were set
  48440. with setAllowedPlacement().
  48441. */
  48442. void setPosition (int arrowTipX,
  48443. int arrowTipY);
  48444. /** Moves and resizes the bubble to point at a given rectangle.
  48445. This will resize the bubble to fit its content, then find a position for it
  48446. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  48447. co-ordinates are relative to either the bubble component's parent component
  48448. if it has one, or they are screen co-ordinates if not.
  48449. It'll put itself either above, below, or to the side of the component depending
  48450. on where there's the most space, honouring any restrictions that were set
  48451. with setAllowedPlacement().
  48452. */
  48453. void setPosition (const Rectangle<int>& rectangleToPointTo);
  48454. protected:
  48455. /** Subclasses should override this to return the size of the content they
  48456. want to draw inside the bubble.
  48457. */
  48458. virtual void getContentSize (int& width, int& height) = 0;
  48459. /** Subclasses should override this to draw their bubble's contents.
  48460. The graphics object's clip region and the dimensions passed in here are
  48461. set up to paint just the rectangle inside the bubble.
  48462. */
  48463. virtual void paintContent (Graphics& g, int width, int height) = 0;
  48464. public:
  48465. /** @internal */
  48466. void paint (Graphics& g);
  48467. private:
  48468. Rectangle<int> content;
  48469. int side, allowablePlacements;
  48470. float arrowTipX, arrowTipY;
  48471. DropShadowEffect shadow;
  48472. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleComponent);
  48473. };
  48474. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  48475. /*** End of inlined file: juce_BubbleComponent.h ***/
  48476. #endif
  48477. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  48478. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  48479. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  48480. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  48481. /**
  48482. A speech-bubble component that displays a short message.
  48483. This can be used to show a message with the tail of the speech bubble
  48484. pointing to a particular component or location on the screen.
  48485. @see BubbleComponent
  48486. */
  48487. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  48488. private Timer
  48489. {
  48490. public:
  48491. /** Creates a bubble component.
  48492. After creating one a BubbleComponent, do the following:
  48493. - add it to an appropriate parent component, or put it on the
  48494. desktop with Component::addToDesktop (0).
  48495. - use the showAt() method to show a message.
  48496. - it will make itself invisible after it times-out (and can optionally
  48497. also delete itself), or you can reuse it somewhere else by calling
  48498. showAt() again.
  48499. */
  48500. BubbleMessageComponent (int fadeOutLengthMs = 150);
  48501. /** Destructor. */
  48502. ~BubbleMessageComponent();
  48503. /** Shows a message bubble at a particular position.
  48504. This shows the bubble with its stem pointing to the given location
  48505. (co-ordinates being relative to its parent component).
  48506. For details about exactly how it decides where to position itself, see
  48507. BubbleComponent::updatePosition().
  48508. @param x the x co-ordinate of end of the bubble's tail
  48509. @param y the y co-ordinate of end of the bubble's tail
  48510. @param message the text to display
  48511. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  48512. from its parent compnent. If this is 0 or less, it
  48513. will stay there until manually removed.
  48514. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  48515. mouse button is pressed (anywhere on the screen)
  48516. @param deleteSelfAfterUse if true, then the component will delete itself after
  48517. it becomes invisible
  48518. */
  48519. void showAt (int x, int y,
  48520. const String& message,
  48521. int numMillisecondsBeforeRemoving,
  48522. bool removeWhenMouseClicked = true,
  48523. bool deleteSelfAfterUse = false);
  48524. /** Shows a message bubble next to a particular component.
  48525. This shows the bubble with its stem pointing at the given component.
  48526. For details about exactly how it decides where to position itself, see
  48527. BubbleComponent::updatePosition().
  48528. @param component the component that you want to point at
  48529. @param message the text to display
  48530. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  48531. from its parent compnent. If this is 0 or less, it
  48532. will stay there until manually removed.
  48533. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  48534. mouse button is pressed (anywhere on the screen)
  48535. @param deleteSelfAfterUse if true, then the component will delete itself after
  48536. it becomes invisible
  48537. */
  48538. void showAt (Component* component,
  48539. const String& message,
  48540. int numMillisecondsBeforeRemoving,
  48541. bool removeWhenMouseClicked = true,
  48542. bool deleteSelfAfterUse = false);
  48543. /** @internal */
  48544. void getContentSize (int& w, int& h);
  48545. /** @internal */
  48546. void paintContent (Graphics& g, int w, int h);
  48547. /** @internal */
  48548. void timerCallback();
  48549. private:
  48550. int fadeOutLength, mouseClickCounter;
  48551. TextLayout textLayout;
  48552. int64 expiryTime;
  48553. bool deleteAfterUse;
  48554. void init (int numMillisecondsBeforeRemoving,
  48555. bool removeWhenMouseClicked,
  48556. bool deleteSelfAfterUse);
  48557. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleMessageComponent);
  48558. };
  48559. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  48560. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  48561. #endif
  48562. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  48563. /*** Start of inlined file: juce_ColourSelector.h ***/
  48564. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  48565. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  48566. /**
  48567. A component that lets the user choose a colour.
  48568. This shows RGB sliders and a colourspace that the user can pick colours from.
  48569. This class is also a ChangeBroadcaster, so listeners can register to be told
  48570. when the colour changes.
  48571. */
  48572. class JUCE_API ColourSelector : public Component,
  48573. public ChangeBroadcaster,
  48574. protected SliderListener
  48575. {
  48576. public:
  48577. /** Options for the type of selector to show. These are passed into the constructor. */
  48578. enum ColourSelectorOptions
  48579. {
  48580. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  48581. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  48582. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  48583. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  48584. };
  48585. /** Creates a ColourSelector object.
  48586. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  48587. which of the selector's features should be visible.
  48588. The edgeGap value specifies the amount of space to leave around the edge.
  48589. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  48590. colourspace and hue selector components.
  48591. */
  48592. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  48593. int edgeGap = 4,
  48594. int gapAroundColourSpaceComponent = 7);
  48595. /** Destructor. */
  48596. ~ColourSelector();
  48597. /** Returns the colour that the user has currently selected.
  48598. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  48599. register to be told when the colour changes.
  48600. @see setCurrentColour
  48601. */
  48602. const Colour getCurrentColour() const;
  48603. /** Changes the colour that is currently being shown.
  48604. */
  48605. void setCurrentColour (const Colour& newColour);
  48606. /** Tells the selector how many preset colour swatches you want to have on the component.
  48607. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  48608. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  48609. their values.
  48610. */
  48611. virtual int getNumSwatches() const;
  48612. /** Called by the selector to find out the colour of one of the swatches.
  48613. Your subclass should return the colour of the swatch with the given index.
  48614. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  48615. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  48616. their values.
  48617. */
  48618. virtual const Colour getSwatchColour (int index) const;
  48619. /** Called by the selector when the user puts a new colour into one of the swatches.
  48620. Your subclass should change the colour of the swatch with the given index.
  48621. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  48622. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  48623. their values.
  48624. */
  48625. virtual void setSwatchColour (int index, const Colour& newColour) const;
  48626. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  48627. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  48628. methods.
  48629. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  48630. */
  48631. enum ColourIds
  48632. {
  48633. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  48634. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  48635. };
  48636. private:
  48637. class ColourSpaceView;
  48638. class HueSelectorComp;
  48639. class SwatchComponent;
  48640. friend class ColourSpaceView;
  48641. friend class ScopedPointer<ColourSpaceView>;
  48642. friend class HueSelectorComp;
  48643. friend class ScopedPointer<HueSelectorComp>;
  48644. Colour colour;
  48645. float h, s, v;
  48646. ScopedPointer<Slider> sliders[4];
  48647. ScopedPointer<ColourSpaceView> colourSpace;
  48648. ScopedPointer<HueSelectorComp> hueSelector;
  48649. OwnedArray <SwatchComponent> swatchComponents;
  48650. const int flags;
  48651. int edgeGap;
  48652. Rectangle<int> previewArea;
  48653. void setHue (float newH);
  48654. void setSV (float newS, float newV);
  48655. void updateHSV();
  48656. void update();
  48657. void sliderValueChanged (Slider*);
  48658. void paint (Graphics& g);
  48659. void resized();
  48660. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ColourSelector);
  48661. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  48662. // This constructor is here temporarily to prevent old code compiling, because the parameters
  48663. // have changed - if you get an error here, update your code to use the new constructor instead..
  48664. ColourSelector (bool);
  48665. #endif
  48666. };
  48667. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  48668. /*** End of inlined file: juce_ColourSelector.h ***/
  48669. #endif
  48670. #ifndef __JUCE_DIRECTSHOWCOMPONENT_JUCEHEADER__
  48671. /*** Start of inlined file: juce_DirectShowComponent.h ***/
  48672. #ifndef __JUCE_DIRECTSHOWCOMPONENT_JUCEHEADER__
  48673. #define __JUCE_DIRECTSHOWCOMPONENT_JUCEHEADER__
  48674. #if JUCE_DIRECTSHOW || DOXYGEN
  48675. /**
  48676. A window that can play back a DirectShow video.
  48677. @note Controller is not implemented
  48678. */
  48679. class JUCE_API DirectShowComponent : public Component
  48680. {
  48681. public:
  48682. /** DirectShow video renderer type.
  48683. See MSDN for adivce about choosing the right renderer.
  48684. */
  48685. enum VideoRendererType
  48686. {
  48687. dshowDefault, /**< VMR7 for Windows XP, EVR for Windows Vista and later */
  48688. dshowVMR7, /**< Video Mixing Renderer 7 */
  48689. dshowEVR /**< Enhanced Video Renderer */
  48690. };
  48691. /** Creates a DirectShowComponent, initially blank.
  48692. Use the loadMovie() method to load a video once you've added the
  48693. component to a window, (or put it on the desktop as a heavyweight window).
  48694. Loading a video when the component isn't visible can cause problems, as
  48695. DirectShow needs a window handle to initialise properly.
  48696. @see VideoRendererType
  48697. */
  48698. DirectShowComponent (VideoRendererType type = dshowDefault);
  48699. /** Destructor. */
  48700. ~DirectShowComponent();
  48701. /** Returns true if DirectShow is installed and working on this machine. */
  48702. static bool isDirectShowAvailable();
  48703. /** Tries to load a DirectShow video from a file or URL into the player.
  48704. It's best to call this function once you've added the component to a window,
  48705. (or put it on the desktop as a heavyweight window). Loading a video when the
  48706. component isn't visible can cause problems, because DirectShow needs a window
  48707. handle to do its stuff.
  48708. @param fileOrURLPath the file or URL path to open
  48709. @returns true if the video opens successfully
  48710. */
  48711. bool loadMovie (const String& fileOrURLPath);
  48712. /** Tries to load a DirectShow video from a file into the player.
  48713. It's best to call this function once you've added the component to a window,
  48714. (or put it on the desktop as a heavyweight window). Loading a video when the
  48715. component isn't visible can cause problems, because DirectShow needs a window
  48716. handle to do its stuff.
  48717. @param videoFile the video file to open
  48718. @returns true if the video opens successfully
  48719. */
  48720. bool loadMovie (const File& videoFile);
  48721. /** Tries to load a DirectShow video from a URL 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 video when the
  48724. component isn't visible can cause problems, because DirectShow needs a window
  48725. handle to do its stuff.
  48726. @param videoURL the video URL to open
  48727. @returns true if the video opens successfully
  48728. */
  48729. bool loadMovie (const URL& videoURL);
  48730. /** Closes the video, if one is open. */
  48731. void closeMovie();
  48732. /** Returns the file path or URL from which the video file was loaded.
  48733. If there isn't one, this returns an empty string.
  48734. */
  48735. File getCurrentMoviePath() const;
  48736. /** Returns true if there's currently a video open. */
  48737. bool isMovieOpen() const;
  48738. /** Returns the length of the video, in seconds. */
  48739. double getMovieDuration() const;
  48740. /** Returns the video's natural size, in pixels.
  48741. You can use this to resize the component to show the video at its preferred
  48742. scale.
  48743. If no video is loaded, the size returned will be 0 x 0.
  48744. */
  48745. void getMovieNormalSize (int& width, int& height) const;
  48746. /** This will position the component within a given area, keeping its aspect
  48747. ratio correct according to the video's normal size.
  48748. The component will be made as large as it can go within the space, and will
  48749. be aligned according to the justification value if this means there are gaps at
  48750. the top or sides.
  48751. @note Not implemented
  48752. */
  48753. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  48754. const RectanglePlacement& placement);
  48755. /** Starts the video playing. */
  48756. void play();
  48757. /** Stops the video playing. */
  48758. void stop();
  48759. /** Returns true if the video is currently playing. */
  48760. bool isPlaying() const;
  48761. /** Moves the video's position back to the start. */
  48762. void goToStart();
  48763. /** Sets the video's position to a given time. */
  48764. void setPosition (double seconds);
  48765. /** Returns the current play position of the video. */
  48766. double getPosition() const;
  48767. /** Changes the video playback rate.
  48768. A value of 1 is normal speed, greater values play it proportionately faster,
  48769. smaller values play it slower.
  48770. */
  48771. void setSpeed (float newSpeed);
  48772. /** Changes the video's playback volume.
  48773. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  48774. */
  48775. void setMovieVolume (float newVolume);
  48776. /** Returns the video's playback volume.
  48777. @returns the volume in the range 0 (silent) to 1.0 (full)
  48778. */
  48779. float getMovieVolume() const;
  48780. /** Tells the video whether it should loop. */
  48781. void setLooping (bool shouldLoop);
  48782. /** Returns true if the video is currently looping.
  48783. @see setLooping
  48784. */
  48785. bool isLooping() const;
  48786. /** @internal */
  48787. void paint (Graphics& g);
  48788. private:
  48789. String videoPath;
  48790. bool videoLoaded, looping;
  48791. class DirectShowContext;
  48792. friend class DirectShowContext;
  48793. friend class ScopedPointer <DirectShowContext>;
  48794. ScopedPointer <DirectShowContext> context;
  48795. class DirectShowComponentWatcher;
  48796. friend class DirectShowComponentWatcher;
  48797. friend class ScopedPointer <DirectShowComponentWatcher>;
  48798. ScopedPointer <DirectShowComponentWatcher> componentWatcher;
  48799. bool needToUpdateViewport, needToRecreateNativeWindow;
  48800. void updateContextPosition();
  48801. void showContext (bool shouldBeVisible);
  48802. void recreateNativeWindowAsync();
  48803. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectShowComponent);
  48804. };
  48805. #endif
  48806. #endif // __JUCE_DIRECTSHOWCOMPONENT_JUCEHEADER__
  48807. /*** End of inlined file: juce_DirectShowComponent.h ***/
  48808. #endif
  48809. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  48810. #endif
  48811. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48812. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  48813. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48814. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48815. /**
  48816. A component that displays a piano keyboard, whose notes can be clicked on.
  48817. This component will mimic a physical midi keyboard, showing the current state of
  48818. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  48819. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  48820. Another feature is that the computer keyboard can also be used to play notes. By
  48821. default it maps the top two rows of a standard querty keyboard to the notes, but
  48822. these can be remapped if needed. It will only respond to keypresses when it has
  48823. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  48824. The component is also a ChangeBroadcaster, so if you want to be informed when the
  48825. keyboard is scrolled, you can register a ChangeListener for callbacks.
  48826. @see MidiKeyboardState
  48827. */
  48828. class JUCE_API MidiKeyboardComponent : public Component,
  48829. public MidiKeyboardStateListener,
  48830. public ChangeBroadcaster,
  48831. private Timer,
  48832. private AsyncUpdater
  48833. {
  48834. public:
  48835. /** The direction of the keyboard.
  48836. @see setOrientation
  48837. */
  48838. enum Orientation
  48839. {
  48840. horizontalKeyboard,
  48841. verticalKeyboardFacingLeft,
  48842. verticalKeyboardFacingRight,
  48843. };
  48844. /** Creates a MidiKeyboardComponent.
  48845. @param state the midi keyboard model that this component will represent
  48846. @param orientation whether the keyboard is horizonal or vertical
  48847. */
  48848. MidiKeyboardComponent (MidiKeyboardState& state,
  48849. Orientation orientation);
  48850. /** Destructor. */
  48851. ~MidiKeyboardComponent();
  48852. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  48853. on the component.
  48854. Values are 0 to 1.0, where 1.0 is the heaviest.
  48855. @see setMidiChannel
  48856. */
  48857. void setVelocity (float velocity, bool useMousePositionForVelocity);
  48858. /** Changes the midi channel number that will be used for events triggered by clicking
  48859. on the component.
  48860. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  48861. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  48862. Although this is the channel used for outgoing events, the component can display
  48863. incoming events from more than one channel - see setMidiChannelsToDisplay()
  48864. @see setVelocity
  48865. */
  48866. void setMidiChannel (int midiChannelNumber);
  48867. /** Returns the midi channel that the keyboard is using for midi messages.
  48868. @see setMidiChannel
  48869. */
  48870. int getMidiChannel() const noexcept { return midiChannel; }
  48871. /** Sets a mask to indicate which incoming midi channels should be represented by
  48872. key movements.
  48873. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  48874. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  48875. in this mask, the on-screen keys will also go down.
  48876. By default, this mask is set to 0xffff (all channels displayed).
  48877. @see setMidiChannel
  48878. */
  48879. void setMidiChannelsToDisplay (int midiChannelMask);
  48880. /** Returns the current set of midi channels represented by the component.
  48881. This is the value that was set with setMidiChannelsToDisplay().
  48882. */
  48883. int getMidiChannelsToDisplay() const noexcept { return midiInChannelMask; }
  48884. /** Changes the width used to draw the white keys. */
  48885. void setKeyWidth (float widthInPixels);
  48886. /** Returns the width that was set by setKeyWidth(). */
  48887. float getKeyWidth() const noexcept { return keyWidth; }
  48888. /** Changes the keyboard's current direction. */
  48889. void setOrientation (Orientation newOrientation);
  48890. /** Returns the keyboard's current direction. */
  48891. const Orientation getOrientation() const noexcept { return orientation; }
  48892. /** Sets the range of midi notes that the keyboard will be limited to.
  48893. By default the range is 0 to 127 (inclusive), but you can limit this if you
  48894. only want a restricted set of the keys to be shown.
  48895. Note that the values here are inclusive and must be between 0 and 127.
  48896. */
  48897. void setAvailableRange (int lowestNote,
  48898. int highestNote);
  48899. /** Returns the first note in the available range.
  48900. @see setAvailableRange
  48901. */
  48902. int getRangeStart() const noexcept { return rangeStart; }
  48903. /** Returns the last note in the available range.
  48904. @see setAvailableRange
  48905. */
  48906. int getRangeEnd() const noexcept { return rangeEnd; }
  48907. /** If the keyboard extends beyond the size of the component, this will scroll
  48908. it to show the given key at the start.
  48909. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  48910. base class to send a callback to any ChangeListeners that have been registered.
  48911. */
  48912. void setLowestVisibleKey (int noteNumber);
  48913. /** Returns the number of the first key shown in the component.
  48914. @see setLowestVisibleKey
  48915. */
  48916. int getLowestVisibleKey() const noexcept { return firstKey; }
  48917. /** Returns the length of the black notes.
  48918. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  48919. */
  48920. int getBlackNoteLength() const noexcept { return blackNoteLength; }
  48921. /** If set to true, then scroll buttons will appear at either end of the keyboard
  48922. if there are too many notes to fit them all in the component at once.
  48923. */
  48924. void setScrollButtonsVisible (bool canScroll);
  48925. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  48926. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  48927. methods.
  48928. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  48929. */
  48930. enum ColourIds
  48931. {
  48932. whiteNoteColourId = 0x1005000,
  48933. blackNoteColourId = 0x1005001,
  48934. keySeparatorLineColourId = 0x1005002,
  48935. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  48936. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  48937. textLabelColourId = 0x1005005,
  48938. upDownButtonBackgroundColourId = 0x1005006,
  48939. upDownButtonArrowColourId = 0x1005007
  48940. };
  48941. /** Returns the position within the component of the left-hand edge of a key.
  48942. Depending on the keyboard's orientation, this may be a horizontal or vertical
  48943. distance, in either direction.
  48944. */
  48945. int getKeyStartPosition (const int midiNoteNumber) const;
  48946. /** Deletes all key-mappings.
  48947. @see setKeyPressForNote
  48948. */
  48949. void clearKeyMappings();
  48950. /** Maps a key-press to a given note.
  48951. @param key the key that should trigger the note
  48952. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  48953. be. The actual midi note that gets played will be
  48954. this value + (12 * the current base octave). To change
  48955. the base octave, see setKeyPressBaseOctave()
  48956. */
  48957. void setKeyPressForNote (const KeyPress& key,
  48958. int midiNoteOffsetFromC);
  48959. /** Removes any key-mappings for a given note.
  48960. For a description of what the note number means, see setKeyPressForNote().
  48961. */
  48962. void removeKeyPressForNote (int midiNoteOffsetFromC);
  48963. /** Changes the base note above which key-press-triggered notes are played.
  48964. The set of key-mappings that trigger notes can be moved up and down to cover
  48965. the entire scale using this method.
  48966. The value passed in is an octave number between 0 and 10 (inclusive), and
  48967. indicates which C is the base note to which the key-mapped notes are
  48968. relative.
  48969. */
  48970. void setKeyPressBaseOctave (int newOctaveNumber);
  48971. /** This sets the octave number which is shown as the octave number for middle C.
  48972. This affects only the default implementation of getWhiteNoteText(), which
  48973. passes this octave number to MidiMessage::getMidiNoteName() in order to
  48974. get the note text. See MidiMessage::getMidiNoteName() for more info about
  48975. the parameter.
  48976. By default this value is set to 3.
  48977. @see getOctaveForMiddleC
  48978. */
  48979. void setOctaveForMiddleC (int octaveNumForMiddleC);
  48980. /** This returns the value set by setOctaveForMiddleC().
  48981. @see setOctaveForMiddleC
  48982. */
  48983. int getOctaveForMiddleC() const noexcept { return octaveNumForMiddleC; }
  48984. /** @internal */
  48985. void paint (Graphics& g);
  48986. /** @internal */
  48987. void resized();
  48988. /** @internal */
  48989. void mouseMove (const MouseEvent& e);
  48990. /** @internal */
  48991. void mouseDrag (const MouseEvent& e);
  48992. /** @internal */
  48993. void mouseDown (const MouseEvent& e);
  48994. /** @internal */
  48995. void mouseUp (const MouseEvent& e);
  48996. /** @internal */
  48997. void mouseEnter (const MouseEvent& e);
  48998. /** @internal */
  48999. void mouseExit (const MouseEvent& e);
  49000. /** @internal */
  49001. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  49002. /** @internal */
  49003. void timerCallback();
  49004. /** @internal */
  49005. bool keyStateChanged (bool isKeyDown);
  49006. /** @internal */
  49007. void focusLost (FocusChangeType cause);
  49008. /** @internal */
  49009. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  49010. /** @internal */
  49011. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  49012. /** @internal */
  49013. void handleAsyncUpdate();
  49014. /** @internal */
  49015. void colourChanged();
  49016. protected:
  49017. /** Draws a white note in the given rectangle.
  49018. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  49019. currently pressed down.
  49020. When doing this, be sure to note the keyboard's orientation.
  49021. */
  49022. virtual void drawWhiteNote (int midiNoteNumber,
  49023. Graphics& g,
  49024. int x, int y, int w, int h,
  49025. bool isDown, bool isOver,
  49026. const Colour& lineColour,
  49027. const Colour& textColour);
  49028. /** Draws a black note in the given rectangle.
  49029. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  49030. currently pressed down.
  49031. When doing this, be sure to note the keyboard's orientation.
  49032. */
  49033. virtual void drawBlackNote (int midiNoteNumber,
  49034. Graphics& g,
  49035. int x, int y, int w, int h,
  49036. bool isDown, bool isOver,
  49037. const Colour& noteFillColour);
  49038. /** Allows text to be drawn on the white notes.
  49039. By default this is used to label the C in each octave, but could be used for other things.
  49040. @see setOctaveForMiddleC
  49041. */
  49042. virtual const String getWhiteNoteText (const int midiNoteNumber);
  49043. /** Draws the up and down buttons that change the base note. */
  49044. virtual void drawUpDownButton (Graphics& g, int w, int h,
  49045. const bool isMouseOver,
  49046. const bool isButtonPressed,
  49047. const bool movesOctavesUp);
  49048. /** Callback when the mouse is clicked on a key.
  49049. You could use this to do things like handle right-clicks on keys, etc.
  49050. Return true if you want the click to trigger the note, or false if you
  49051. want to handle it yourself and not have the note played.
  49052. @see mouseDraggedToKey
  49053. */
  49054. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  49055. /** Callback when the mouse is dragged from one key onto another.
  49056. @see mouseDownOnKey
  49057. */
  49058. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  49059. /** Calculates the positon of a given midi-note.
  49060. This can be overridden to create layouts with custom key-widths.
  49061. @param midiNoteNumber the note to find
  49062. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  49063. @param x the x position of the left-hand edge of the key (this method
  49064. always works in terms of a horizontal keyboard)
  49065. @param w the width of the key
  49066. */
  49067. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  49068. int& x, int& w) const;
  49069. private:
  49070. friend class MidiKeyboardUpDownButton;
  49071. MidiKeyboardState& state;
  49072. int xOffset, blackNoteLength;
  49073. float keyWidth;
  49074. Orientation orientation;
  49075. int midiChannel, midiInChannelMask;
  49076. float velocity;
  49077. int noteUnderMouse, mouseDownNote;
  49078. BigInteger keysPressed, keysCurrentlyDrawnDown;
  49079. int rangeStart, rangeEnd, firstKey;
  49080. bool canScroll, mouseDragging, useMousePositionForVelocity;
  49081. ScopedPointer<Button> scrollDown, scrollUp;
  49082. Array <KeyPress> keyPresses;
  49083. Array <int> keyPressNotes;
  49084. int keyMappingOctave;
  49085. int octaveNumForMiddleC;
  49086. static const uint8 whiteNotes[];
  49087. static const uint8 blackNotes[];
  49088. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  49089. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  49090. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  49091. void resetAnyKeysInUse();
  49092. void updateNoteUnderMouse (const Point<int>& pos);
  49093. void repaintNote (const int midiNoteNumber);
  49094. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardComponent);
  49095. };
  49096. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  49097. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  49098. #endif
  49099. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  49100. /*** Start of inlined file: juce_NSViewComponent.h ***/
  49101. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  49102. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  49103. #if ! DOXYGEN
  49104. class NSViewComponentInternal;
  49105. #endif
  49106. #if JUCE_MAC || DOXYGEN
  49107. /**
  49108. A Mac-specific class that can create and embed an NSView inside itself.
  49109. To use it, create one of these, put it in place and make sure it's visible in a
  49110. window, then use setView() to assign an NSView to it. The view will then be
  49111. moved and resized to follow the movements of this component.
  49112. Of course, since the view is a native object, it'll obliterate any
  49113. juce components that may overlap this component, but that's life.
  49114. */
  49115. class JUCE_API NSViewComponent : public Component
  49116. {
  49117. public:
  49118. /** Create an initially-empty container. */
  49119. NSViewComponent();
  49120. /** Destructor. */
  49121. ~NSViewComponent();
  49122. /** Assigns an NSView to this peer.
  49123. The view will be retained and released by this component for as long as
  49124. it is needed. To remove the current view, just call setView (nullptr).
  49125. Note: a void* is used here to avoid including the cocoa headers as
  49126. part of the juce.h, but the method expects an NSView*.
  49127. */
  49128. void setView (void* nsView);
  49129. /** Returns the current NSView.
  49130. Note: a void* is returned here to avoid including the cocoa headers as
  49131. a requirement of juce.h, so you should just cast the object to an NSView*.
  49132. */
  49133. void* getView() const;
  49134. /** Resizes this component to fit the view that it contains. */
  49135. void resizeToFitView();
  49136. /** @internal */
  49137. void paint (Graphics& g);
  49138. private:
  49139. friend class NSViewComponentInternal;
  49140. ScopedPointer <NSViewComponentInternal> info;
  49141. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponent);
  49142. };
  49143. #endif
  49144. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  49145. /*** End of inlined file: juce_NSViewComponent.h ***/
  49146. #endif
  49147. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  49148. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  49149. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  49150. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  49151. // this is used to disable OpenGL, and is defined in juce_Config.h
  49152. #if JUCE_OPENGL || DOXYGEN
  49153. /**
  49154. Represents the various properties of an OpenGL bitmap format.
  49155. @see OpenGLComponent::setPixelFormat
  49156. */
  49157. class JUCE_API OpenGLPixelFormat
  49158. {
  49159. public:
  49160. /** Creates an OpenGLPixelFormat.
  49161. The default constructor just initialises the object as a simple 8-bit
  49162. RGBA format.
  49163. */
  49164. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  49165. int alphaBits = 8,
  49166. int depthBufferBits = 16,
  49167. int stencilBufferBits = 0);
  49168. OpenGLPixelFormat (const OpenGLPixelFormat&);
  49169. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  49170. bool operator== (const OpenGLPixelFormat&) const;
  49171. int redBits; /**< The number of bits per pixel to use for the red channel. */
  49172. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  49173. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  49174. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  49175. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  49176. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  49177. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  49178. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  49179. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  49180. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  49181. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  49182. /** Returns a list of all the pixel formats that can be used in this system.
  49183. A reference component is needed in case there are multiple screens with different
  49184. capabilities - in which case, the one that the component is on will be used.
  49185. */
  49186. static void getAvailablePixelFormats (Component* component,
  49187. OwnedArray <OpenGLPixelFormat>& results);
  49188. private:
  49189. JUCE_LEAK_DETECTOR (OpenGLPixelFormat);
  49190. };
  49191. /**
  49192. A base class for types of OpenGL context.
  49193. An OpenGLComponent will supply its own context for drawing in its window.
  49194. */
  49195. class JUCE_API OpenGLContext
  49196. {
  49197. public:
  49198. /** Destructor. */
  49199. virtual ~OpenGLContext();
  49200. /** Makes this context the currently active one. */
  49201. virtual bool makeActive() const noexcept = 0;
  49202. /** If this context is currently active, it is disactivated. */
  49203. virtual bool makeInactive() const noexcept = 0;
  49204. /** Returns true if this context is currently active. */
  49205. virtual bool isActive() const noexcept = 0;
  49206. /** Swaps the buffers (if the context can do this). */
  49207. virtual void swapBuffers() = 0;
  49208. /** Sets whether the context checks the vertical sync before swapping.
  49209. The value is the number of frames to allow between buffer-swapping. This is
  49210. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  49211. and greater numbers indicate that it should swap less often.
  49212. Returns true if it sets the value successfully.
  49213. */
  49214. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  49215. /** Returns the current swap-sync interval.
  49216. See setSwapInterval() for info about the value returned.
  49217. */
  49218. virtual int getSwapInterval() const = 0;
  49219. /** Returns the pixel format being used by this context. */
  49220. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  49221. /** For windowed contexts, this moves the context within the bounds of
  49222. its parent window.
  49223. */
  49224. virtual void updateWindowPosition (const Rectangle<int>& bounds) = 0;
  49225. /** For windowed contexts, this triggers a repaint of the window.
  49226. (Not relevent on all platforms).
  49227. */
  49228. virtual void repaint() = 0;
  49229. /** Returns an OS-dependent handle to the raw GL context.
  49230. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  49231. a GLXContext.
  49232. */
  49233. virtual void* getRawContext() const noexcept = 0;
  49234. /** Deletes the context.
  49235. This must only be called on the message thread, or will deadlock.
  49236. On background threads, call getCurrentContext()->deleteContext(), but be careful not
  49237. to call any other OpenGL function afterwards.
  49238. This doesn't touch other resources, such as window handles, etc.
  49239. You'll probably never have to call this method directly.
  49240. */
  49241. virtual void deleteContext() = 0;
  49242. /** Returns the context that's currently in active use by the calling thread.
  49243. Returns 0 if there isn't an active context.
  49244. */
  49245. static OpenGLContext* getCurrentContext();
  49246. protected:
  49247. OpenGLContext() noexcept;
  49248. private:
  49249. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLContext);
  49250. };
  49251. /**
  49252. A component that contains an OpenGL canvas.
  49253. Override this, add it to whatever component you want to, and use the renderOpenGL()
  49254. method to draw its contents.
  49255. */
  49256. class JUCE_API OpenGLComponent : public Component
  49257. {
  49258. public:
  49259. /** Used to select the type of openGL API to use, if more than one choice is available
  49260. on a particular platform.
  49261. */
  49262. enum OpenGLType
  49263. {
  49264. openGLDefault = 0,
  49265. #if JUCE_IOS
  49266. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  49267. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  49268. #endif
  49269. };
  49270. /** Creates an OpenGLComponent.
  49271. If useBackgroundThread is true, the component will launch a background thread
  49272. to do the rendering. If false, then renderOpenGL() will be called as part of the
  49273. normal paint() method.
  49274. */
  49275. OpenGLComponent (OpenGLType type = openGLDefault,
  49276. bool useBackgroundThread = false);
  49277. /** Destructor. */
  49278. ~OpenGLComponent();
  49279. /** Changes the pixel format used by this component.
  49280. @see OpenGLPixelFormat::getAvailablePixelFormats()
  49281. */
  49282. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  49283. /** Returns the pixel format that this component is currently using. */
  49284. const OpenGLPixelFormat getPixelFormat() const;
  49285. /** Specifies an OpenGL context which should be shared with the one that this
  49286. component is using.
  49287. This is an OpenGL feature that lets two contexts share their texture data.
  49288. Note that this pointer is stored by the component, and when the component
  49289. needs to recreate its internal context for some reason, the same context
  49290. will be used again to share lists. So if you pass a context in here,
  49291. don't delete the context while this component is still using it! You can
  49292. call shareWith (nullptr) to stop this component from sharing with it.
  49293. */
  49294. void shareWith (OpenGLContext* contextToShareListsWith);
  49295. /** Returns the context that this component is sharing with.
  49296. @see shareWith
  49297. */
  49298. OpenGLContext* getShareContext() const noexcept { return contextToShareListsWith; }
  49299. /** Flips the openGL buffers over. */
  49300. void swapBuffers();
  49301. /** Returns true if the component is performing the rendering on a background thread.
  49302. This property is specified in the constructor.
  49303. */
  49304. bool isUsingDedicatedThread() const noexcept { return useThread; }
  49305. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  49306. When this is called, makeCurrentContextActive() will already have been called
  49307. for you, so you just need to draw.
  49308. */
  49309. virtual void renderOpenGL() = 0;
  49310. /** This method is called when the component creates a new OpenGL context.
  49311. A new context may be created when the component is first used, or when it
  49312. is moved to a different window, or when the window is hidden and re-shown,
  49313. etc.
  49314. You can use this callback as an opportunity to set up things like textures
  49315. that your context needs.
  49316. New contexts are created on-demand by the makeCurrentContextActive() method - so
  49317. if the context is deleted, e.g. by changing the pixel format or window, no context
  49318. will be created until the next call to makeCurrentContextActive(), which will
  49319. synchronously create one and call this method. This means that if you're using
  49320. a non-GUI thread for rendering, you can make sure this method is be called by
  49321. your renderer thread.
  49322. When this callback happens, the context will already have been made current
  49323. using the makeCurrentContextActive() method, so there's no need to call it
  49324. again in your code.
  49325. */
  49326. virtual void newOpenGLContextCreated() = 0;
  49327. /** This method is called when the component shuts down its OpenGL context.
  49328. You can use this callback to delete textures and any other OpenGL objects you
  49329. created in the component's context. Be aware: if you are using a render
  49330. thread, this may be called on the thread.
  49331. When this callback happens, the context will have been made current
  49332. using the makeCurrentContextActive() method, so there's no need to call it
  49333. again in your code.
  49334. */
  49335. virtual void releaseOpenGLContext() {}
  49336. /** Returns the context that will draw into this component.
  49337. This may return 0 if the component is currently invisible or hasn't currently
  49338. got a context. The context object can be deleted and a new one created during
  49339. the lifetime of this component, and there may be times when it doesn't have one.
  49340. @see newOpenGLContextCreated()
  49341. */
  49342. OpenGLContext* getCurrentContext() const noexcept { return context; }
  49343. /** Makes this component the current openGL context.
  49344. You might want to use this in things like your resize() method, before calling
  49345. GL commands.
  49346. If this returns false, then the context isn't active, so you should avoid
  49347. making any calls.
  49348. This call may actually create a context if one isn't currently initialised. If
  49349. it does this, it will also synchronously call the newOpenGLContextCreated()
  49350. method to let you initialise it as necessary.
  49351. @see OpenGLContext::makeActive
  49352. */
  49353. bool makeCurrentContextActive();
  49354. /** Stops the current component being the active OpenGL context.
  49355. This is the opposite of makeCurrentContextActive()
  49356. @see OpenGLContext::makeInactive
  49357. */
  49358. void makeCurrentContextInactive();
  49359. /** Returns true if this component's context is the active openGL context for the
  49360. current thread.
  49361. @see OpenGLContext::isActive
  49362. */
  49363. bool isActiveContext() const noexcept;
  49364. /** Calls the rendering callback, and swaps the buffers afterwards.
  49365. This is called automatically by paint() when the component needs to be rendered.
  49366. Returns true if the operation succeeded.
  49367. */
  49368. virtual bool renderAndSwapBuffers();
  49369. /** This returns a critical section that can be used to lock the current context.
  49370. Because the context that is used by this component can change, e.g. when the
  49371. component is shown or hidden, then if you're rendering to it on a background
  49372. thread, this allows you to lock the context for the duration of your rendering
  49373. routine.
  49374. */
  49375. CriticalSection& getContextLock() noexcept { return contextLock; }
  49376. /** Delete the context.
  49377. You should only need to call this if you've written a custom thread - if so, make
  49378. sure that your thread calls this before it terminates.
  49379. */
  49380. void deleteContext();
  49381. /** Returns the native handle of an embedded heavyweight window, if there is one.
  49382. E.g. On windows, this will return the HWND of the sub-window containing
  49383. the opengl context, on the mac it'll be the NSOpenGLView.
  49384. */
  49385. void* getNativeWindowHandle() const;
  49386. protected:
  49387. /** Kicks off a thread to start rendering.
  49388. The default implementation creates and manages an internal thread that tries
  49389. to render at around 50fps, but this can be overloaded to create a custom thread.
  49390. */
  49391. virtual void startRenderThread();
  49392. /** Cleans up the rendering thread.
  49393. Used to shut down the thread that was started by startRenderThread(). If you've
  49394. created a custom thread, then you should overload this to clean it up and delete it.
  49395. */
  49396. virtual void stopRenderThread();
  49397. /** @internal */
  49398. void paint (Graphics& g);
  49399. private:
  49400. const OpenGLType type;
  49401. class OpenGLComponentRenderThread;
  49402. friend class OpenGLComponentRenderThread;
  49403. friend class ScopedPointer <OpenGLComponentRenderThread>;
  49404. ScopedPointer <OpenGLComponentRenderThread> renderThread;
  49405. class OpenGLComponentWatcher;
  49406. friend class OpenGLComponentWatcher;
  49407. friend class ScopedPointer <OpenGLComponentWatcher>;
  49408. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  49409. ScopedPointer <OpenGLContext> context;
  49410. OpenGLContext* contextToShareListsWith;
  49411. CriticalSection contextLock;
  49412. OpenGLPixelFormat preferredPixelFormat;
  49413. bool needToUpdateViewport, needToDeleteContext, threadStarted;
  49414. const bool useThread;
  49415. OpenGLContext* createContext();
  49416. void updateContext();
  49417. void updateContextPosition();
  49418. void stopBackgroundThread();
  49419. void recreateContextAsync();
  49420. void internalRepaint (int x, int y, int w, int h);
  49421. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponent);
  49422. };
  49423. #endif
  49424. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  49425. /*** End of inlined file: juce_OpenGLComponent.h ***/
  49426. #endif
  49427. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  49428. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  49429. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  49430. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  49431. /**
  49432. A component with a set of buttons at the top for changing between pages of
  49433. preferences.
  49434. This is just a handy way of writing a Mac-style preferences panel where you
  49435. have a row of buttons along the top for the different preference categories,
  49436. each button having an icon above its name. Clicking these will show an
  49437. appropriate prefs page below it.
  49438. You can either put one of these inside your own component, or just use the
  49439. showInDialogBox() method to show it in a window and run it modally.
  49440. To use it, just add a set of named pages with the addSettingsPage() method,
  49441. and implement the createComponentForPage() method to create suitable components
  49442. for each of these pages.
  49443. */
  49444. class JUCE_API PreferencesPanel : public Component,
  49445. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  49446. {
  49447. public:
  49448. /** Creates an empty panel.
  49449. Use addSettingsPage() to add some pages to it in your constructor.
  49450. */
  49451. PreferencesPanel();
  49452. /** Destructor. */
  49453. ~PreferencesPanel();
  49454. /** Creates a page using a set of drawables to define the page's icon.
  49455. Note that the other version of this method is much easier if you're using
  49456. an image instead of a custom drawable.
  49457. @param pageTitle the name of this preferences page - you'll need to
  49458. make sure your createComponentForPage() method creates
  49459. a suitable component when it is passed this name
  49460. @param normalIcon the drawable to display in the page's button normally
  49461. @param overIcon the drawable to display in the page's button when the mouse is over
  49462. @param downIcon the drawable to display in the page's button when the button is down
  49463. @see DrawableButton
  49464. */
  49465. void addSettingsPage (const String& pageTitle,
  49466. const Drawable* normalIcon,
  49467. const Drawable* overIcon,
  49468. const Drawable* downIcon);
  49469. /** Creates a page using a set of drawables to define the page's icon.
  49470. The other version of this method gives you more control over the icon, but this
  49471. one is much easier if you're just loading it from a file.
  49472. @param pageTitle the name of this preferences page - you'll need to
  49473. make sure your createComponentForPage() method creates
  49474. a suitable component when it is passed this name
  49475. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  49476. For this to look good, you'll probably want to use a nice
  49477. transparent png file.
  49478. @param imageDataSize the size of the image data, in bytes
  49479. */
  49480. void addSettingsPage (const String& pageTitle,
  49481. const void* imageData,
  49482. int imageDataSize);
  49483. /** Utility method to display this panel in a DialogWindow.
  49484. Calling this will create a DialogWindow containing this panel with the
  49485. given size and title, and will run it modally, returning when the user
  49486. closes the dialog box.
  49487. */
  49488. void showInDialogBox (const String& dialogTitle,
  49489. int dialogWidth,
  49490. int dialogHeight,
  49491. const Colour& backgroundColour = Colours::white);
  49492. /** Subclasses must override this to return a component for each preferences page.
  49493. The subclass should return a pointer to a new component representing the named
  49494. page, which the panel will then display.
  49495. The panel will delete the component later when the user goes to another page
  49496. or deletes the panel.
  49497. */
  49498. virtual Component* createComponentForPage (const String& pageName) = 0;
  49499. /** Changes the current page being displayed. */
  49500. void setCurrentPage (const String& pageName);
  49501. /** Returns the size of the buttons shown along the top. */
  49502. int getButtonSize() const noexcept;
  49503. /** Changes the size of the buttons shown along the top. */
  49504. void setButtonSize (int newSize);
  49505. /** @internal */
  49506. void resized();
  49507. /** @internal */
  49508. void paint (Graphics& g);
  49509. /** @internal */
  49510. void buttonClicked (Button* button);
  49511. private:
  49512. String currentPageName;
  49513. ScopedPointer <Component> currentPage;
  49514. OwnedArray<DrawableButton> buttons;
  49515. int buttonSize;
  49516. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreferencesPanel);
  49517. };
  49518. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  49519. /*** End of inlined file: juce_PreferencesPanel.h ***/
  49520. #endif
  49521. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  49522. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  49523. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  49524. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  49525. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  49526. // amalgamated build)
  49527. #ifndef DOXYGEN
  49528. #if JUCE_WINDOWS
  49529. typedef ActiveXControlComponent QTCompBaseClass;
  49530. #elif JUCE_MAC
  49531. typedef NSViewComponent QTCompBaseClass;
  49532. #endif
  49533. #endif
  49534. // this is used to disable QuickTime, and is defined in juce_Config.h
  49535. #if JUCE_QUICKTIME || DOXYGEN
  49536. /**
  49537. A window that can play back a QuickTime movie.
  49538. */
  49539. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  49540. {
  49541. public:
  49542. /** Creates a QuickTimeMovieComponent, initially blank.
  49543. Use the loadMovie() method to load a movie once you've added the
  49544. component to a window, (or put it on the desktop as a heavyweight window).
  49545. Loading a movie when the component isn't visible can cause problems, as
  49546. QuickTime needs a window handle to initialise properly.
  49547. */
  49548. QuickTimeMovieComponent();
  49549. /** Destructor. */
  49550. ~QuickTimeMovieComponent();
  49551. /** Returns true if QT is installed and working on this machine.
  49552. */
  49553. static bool isQuickTimeAvailable() noexcept;
  49554. /** Tries to load a QuickTime movie from a file into the player.
  49555. It's best to call this function once you've added the component to a window,
  49556. (or put it on the desktop as a heavyweight window). Loading a movie when the
  49557. component isn't visible can cause problems, because QuickTime needs a window
  49558. handle to do its stuff.
  49559. @param movieFile the .mov file to open
  49560. @param isControllerVisible whether to show a controller bar at the bottom
  49561. @returns true if the movie opens successfully
  49562. */
  49563. bool loadMovie (const File& movieFile,
  49564. bool isControllerVisible);
  49565. /** Tries to load a QuickTime movie from a URL into the player.
  49566. It's best to call this function once you've added the component to a window,
  49567. (or put it on the desktop as a heavyweight window). Loading a movie when the
  49568. component isn't visible can cause problems, because QuickTime needs a window
  49569. handle to do its stuff.
  49570. @param movieURL the .mov file to open
  49571. @param isControllerVisible whether to show a controller bar at the bottom
  49572. @returns true if the movie opens successfully
  49573. */
  49574. bool loadMovie (const URL& movieURL,
  49575. bool isControllerVisible);
  49576. /** Tries to load a QuickTime movie from a stream into the player.
  49577. It's best to call this function once you've added the component to a window,
  49578. (or put it on the desktop as a heavyweight window). Loading a movie when the
  49579. component isn't visible can cause problems, because QuickTime needs a window
  49580. handle to do its stuff.
  49581. @param movieStream a stream containing a .mov file. The component may try
  49582. to read the whole stream before playing, rather than
  49583. streaming from it.
  49584. @param isControllerVisible whether to show a controller bar at the bottom
  49585. @returns true if the movie opens successfully
  49586. */
  49587. bool loadMovie (InputStream* movieStream,
  49588. bool isControllerVisible);
  49589. /** Closes the movie, if one is open. */
  49590. void closeMovie();
  49591. /** Returns the movie file that is currently open.
  49592. If there isn't one, this returns File::nonexistent
  49593. */
  49594. File getCurrentMovieFile() const;
  49595. /** Returns true if there's currently a movie open. */
  49596. bool isMovieOpen() const;
  49597. /** Returns the length of the movie, in seconds. */
  49598. double getMovieDuration() const;
  49599. /** Returns the movie's natural size, in pixels.
  49600. You can use this to resize the component to show the movie at its preferred
  49601. scale.
  49602. If no movie is loaded, the size returned will be 0 x 0.
  49603. */
  49604. void getMovieNormalSize (int& width, int& height) const;
  49605. /** This will position the component within a given area, keeping its aspect
  49606. ratio correct according to the movie's normal size.
  49607. The component will be made as large as it can go within the space, and will
  49608. be aligned according to the justification value if this means there are gaps at
  49609. the top or sides.
  49610. */
  49611. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  49612. const RectanglePlacement& placement);
  49613. /** Starts the movie playing. */
  49614. void play();
  49615. /** Stops the movie playing. */
  49616. void stop();
  49617. /** Returns true if the movie is currently playing. */
  49618. bool isPlaying() const;
  49619. /** Moves the movie's position back to the start. */
  49620. void goToStart();
  49621. /** Sets the movie's position to a given time. */
  49622. void setPosition (double seconds);
  49623. /** Returns the current play position of the movie. */
  49624. double getPosition() const;
  49625. /** Changes the movie playback rate.
  49626. A value of 1 is normal speed, greater values play it proportionately faster,
  49627. smaller values play it slower.
  49628. */
  49629. void setSpeed (float newSpeed);
  49630. /** Changes the movie's playback volume.
  49631. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  49632. */
  49633. void setMovieVolume (float newVolume);
  49634. /** Returns the movie's playback volume.
  49635. @returns the volume in the range 0 (silent) to 1.0 (full)
  49636. */
  49637. float getMovieVolume() const;
  49638. /** Tells the movie whether it should loop. */
  49639. void setLooping (bool shouldLoop);
  49640. /** Returns true if the movie is currently looping.
  49641. @see setLooping
  49642. */
  49643. bool isLooping() const;
  49644. /** True if the native QuickTime controller bar is shown in the window.
  49645. @see loadMovie
  49646. */
  49647. bool isControllerVisible() const;
  49648. /** @internal */
  49649. void paint (Graphics& g);
  49650. private:
  49651. File movieFile;
  49652. bool movieLoaded, controllerVisible, looping;
  49653. #if JUCE_WINDOWS
  49654. void parentHierarchyChanged();
  49655. void visibilityChanged();
  49656. void createControlIfNeeded();
  49657. bool isControlCreated() const;
  49658. class Pimpl;
  49659. friend class ScopedPointer <Pimpl>;
  49660. ScopedPointer <Pimpl> pimpl;
  49661. #else
  49662. void* movie;
  49663. #endif
  49664. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QuickTimeMovieComponent);
  49665. };
  49666. #endif
  49667. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  49668. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  49669. #endif
  49670. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  49671. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  49672. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  49673. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  49674. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  49675. /**
  49676. On Windows only, this component sits in the taskbar tray as a small icon.
  49677. To use it, just create one of these components, but don't attempt to make it
  49678. visible, add it to a parent, or put it on the desktop.
  49679. You can then call setIconImage() to create an icon for it in the taskbar.
  49680. To change the icon's tooltip, you can use setIconTooltip().
  49681. To respond to mouse-events, you can override the normal mouseDown(),
  49682. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  49683. position will not be valid, you can use this to respond to clicks. Traditionally
  49684. you'd use a left-click to show your application's window, and a right-click
  49685. to show a pop-up menu.
  49686. */
  49687. class JUCE_API SystemTrayIconComponent : public Component
  49688. {
  49689. public:
  49690. SystemTrayIconComponent();
  49691. /** Destructor. */
  49692. ~SystemTrayIconComponent();
  49693. /** Changes the image shown in the taskbar.
  49694. */
  49695. void setIconImage (const Image& newImage);
  49696. /** Changes the tooltip that Windows shows above the icon. */
  49697. void setIconTooltip (const String& tooltip);
  49698. #if JUCE_LINUX
  49699. /** @internal */
  49700. void paint (Graphics& g);
  49701. #endif
  49702. private:
  49703. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SystemTrayIconComponent);
  49704. };
  49705. #endif
  49706. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  49707. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  49708. #endif
  49709. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  49710. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  49711. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  49712. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  49713. #if JUCE_WEB_BROWSER || DOXYGEN
  49714. #if ! DOXYGEN
  49715. class WebBrowserComponentInternal;
  49716. #endif
  49717. /**
  49718. A component that displays an embedded web browser.
  49719. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  49720. Windows, probably IE.
  49721. */
  49722. class JUCE_API WebBrowserComponent : public Component
  49723. {
  49724. public:
  49725. /** Creates a WebBrowserComponent.
  49726. Once it's created and visible, send the browser to a URL using goToURL().
  49727. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  49728. component is taken offscreen, it'll clear the current page
  49729. and replace it with a blank page - this can be handy to stop
  49730. the browser using resources in the background when it's not
  49731. actually being used.
  49732. */
  49733. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  49734. /** Destructor. */
  49735. ~WebBrowserComponent();
  49736. /** Sends the browser to a particular URL.
  49737. @param url the URL to go to.
  49738. @param headers an optional set of parameters to put in the HTTP header. If
  49739. you supply this, it should be a set of string in the form
  49740. "HeaderKey: HeaderValue"
  49741. @param postData an optional block of data that will be attached to the HTTP
  49742. POST request
  49743. */
  49744. void goToURL (const String& url,
  49745. const StringArray* headers = nullptr,
  49746. const MemoryBlock* postData = nullptr);
  49747. /** Stops the current page loading.
  49748. */
  49749. void stop();
  49750. /** Sends the browser back one page.
  49751. */
  49752. void goBack();
  49753. /** Sends the browser forward one page.
  49754. */
  49755. void goForward();
  49756. /** Refreshes the browser.
  49757. */
  49758. void refresh();
  49759. /** This callback is called when the browser is about to navigate
  49760. to a new location.
  49761. You can override this method to perform some action when the user
  49762. tries to go to a particular URL. To allow the operation to carry on,
  49763. return true, or return false to stop the navigation happening.
  49764. */
  49765. virtual bool pageAboutToLoad (const String& newURL);
  49766. /** @internal */
  49767. void paint (Graphics& g);
  49768. /** @internal */
  49769. void resized();
  49770. /** @internal */
  49771. void parentHierarchyChanged();
  49772. /** @internal */
  49773. void visibilityChanged();
  49774. private:
  49775. WebBrowserComponentInternal* browser;
  49776. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  49777. String lastURL;
  49778. StringArray lastHeaders;
  49779. MemoryBlock lastPostData;
  49780. void reloadLastURL();
  49781. void checkWindowAssociation();
  49782. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponent);
  49783. };
  49784. #endif
  49785. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  49786. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  49787. #endif
  49788. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  49789. #endif
  49790. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  49791. /*** Start of inlined file: juce_CallOutBox.h ***/
  49792. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  49793. #define __JUCE_CALLOUTBOX_JUCEHEADER__
  49794. /**
  49795. A box with a small arrow that can be used as a temporary pop-up window to show
  49796. extra controls when a button or other component is clicked.
  49797. Using one of these is similar to having a popup menu attached to a button or
  49798. other component - but it looks fancier, and has an arrow that can indicate the
  49799. object that it applies to.
  49800. Normally, you'd create one of these on the stack and run it modally, e.g.
  49801. @code
  49802. void mouseUp (const MouseEvent& e)
  49803. {
  49804. MyContentComponent content;
  49805. content.setSize (300, 300);
  49806. CallOutBox callOut (content, *this, nullptr);
  49807. callOut.runModalLoop();
  49808. }
  49809. @endcode
  49810. The call-out will resize and position itself when the content changes size.
  49811. */
  49812. class JUCE_API CallOutBox : public Component
  49813. {
  49814. public:
  49815. /** Creates a CallOutBox.
  49816. @param contentComponent the component to display inside the call-out. This should
  49817. already have a size set (although the call-out will also
  49818. update itself when the component's size is changed later).
  49819. Obviously this component must not be deleted until the
  49820. call-out box has been deleted.
  49821. @param componentToPointTo the component that the call-out's arrow should point towards
  49822. @param parentComponent if non-zero, this is the component to add the call-out to. If
  49823. this is zero, the call-out will be added to the desktop.
  49824. */
  49825. CallOutBox (Component& contentComponent,
  49826. Component& componentToPointTo,
  49827. Component* parentComponent);
  49828. /** Destructor. */
  49829. ~CallOutBox();
  49830. /** Changes the length of the arrow. */
  49831. void setArrowSize (float newSize);
  49832. /** Updates the position and size of the box.
  49833. You shouldn't normally need to call this, unless you need more precise control over the
  49834. layout.
  49835. @param newAreaToPointTo the rectangle to make the box's arrow point to
  49836. @param newAreaToFitIn the area within which the box's position should be constrained
  49837. */
  49838. void updatePosition (const Rectangle<int>& newAreaToPointTo,
  49839. const Rectangle<int>& newAreaToFitIn);
  49840. /** @internal */
  49841. void paint (Graphics& g);
  49842. /** @internal */
  49843. void resized();
  49844. /** @internal */
  49845. void moved();
  49846. /** @internal */
  49847. void childBoundsChanged (Component*);
  49848. /** @internal */
  49849. bool hitTest (int x, int y);
  49850. /** @internal */
  49851. void inputAttemptWhenModal();
  49852. /** @internal */
  49853. bool keyPressed (const KeyPress& key);
  49854. /** @internal */
  49855. void handleCommandMessage (int commandId);
  49856. private:
  49857. int borderSpace;
  49858. float arrowSize;
  49859. Component& content;
  49860. Path outline;
  49861. Point<float> targetPoint;
  49862. Rectangle<int> availableArea, targetArea;
  49863. Image background;
  49864. void refreshPath();
  49865. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallOutBox);
  49866. };
  49867. #endif // __JUCE_CALLOUTBOX_JUCEHEADER__
  49868. /*** End of inlined file: juce_CallOutBox.h ***/
  49869. #endif
  49870. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  49871. /*** Start of inlined file: juce_ComponentPeer.h ***/
  49872. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  49873. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  49874. class ComponentBoundsConstrainer;
  49875. /**
  49876. The Component class uses a ComponentPeer internally to create and manage a real
  49877. operating-system window.
  49878. This is an abstract base class - the platform specific code contains implementations of
  49879. it for the various platforms.
  49880. User-code should very rarely need to have any involvement with this class.
  49881. @see Component::createNewPeer
  49882. */
  49883. class JUCE_API ComponentPeer
  49884. {
  49885. public:
  49886. /** A combination of these flags is passed to the ComponentPeer constructor. */
  49887. enum StyleFlags
  49888. {
  49889. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  49890. entry on the taskbar (ignored on MacOSX) */
  49891. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  49892. tooltip, etc. */
  49893. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  49894. through it (may not be possible on some platforms). */
  49895. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  49896. title bar and frame\. if not specified, the window will be
  49897. borderless. */
  49898. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  49899. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  49900. minimise button on it. */
  49901. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  49902. maximise button on it. */
  49903. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  49904. close button on it. */
  49905. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  49906. not be possible on all platforms). */
  49907. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  49908. do its own repainting, but only to repaint when the
  49909. performAnyPendingRepaintsNow() method is called. */
  49910. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  49911. be used for things like plugin windows, to stop them interfering
  49912. with the host's shortcut keys */
  49913. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  49914. };
  49915. /** Creates a peer.
  49916. The component is the one that we intend to represent, and the style flags are
  49917. a combination of the values in the StyleFlags enum
  49918. */
  49919. ComponentPeer (Component* component, int styleFlags);
  49920. /** Destructor. */
  49921. virtual ~ComponentPeer();
  49922. /** Returns the component being represented by this peer. */
  49923. Component* getComponent() const noexcept { return component; }
  49924. /** Returns the set of style flags that were set when the window was created.
  49925. @see Component::addToDesktop
  49926. */
  49927. int getStyleFlags() const noexcept { return styleFlags; }
  49928. /** Returns a unique ID for this peer.
  49929. Each peer that is created is given a different ID.
  49930. */
  49931. uint32 getUniqueID() const noexcept { return uniqueID; }
  49932. /** Returns the raw handle to whatever kind of window is being used.
  49933. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  49934. but rememeber there's no guarantees what you'll get back.
  49935. */
  49936. virtual void* getNativeHandle() const = 0;
  49937. /** Shows or hides the window. */
  49938. virtual void setVisible (bool shouldBeVisible) = 0;
  49939. /** Changes the title of the window. */
  49940. virtual void setTitle (const String& title) = 0;
  49941. /** Moves the window without changing its size.
  49942. If the native window is contained in another window, then the co-ordinates are
  49943. relative to the parent window's origin, not the screen origin.
  49944. This should result in a callback to handleMovedOrResized().
  49945. */
  49946. virtual void setPosition (int x, int y) = 0;
  49947. /** Resizes the window without changing its position.
  49948. This should result in a callback to handleMovedOrResized().
  49949. */
  49950. virtual void setSize (int w, int h) = 0;
  49951. /** Moves and resizes the window.
  49952. If the native window is contained in another window, then the co-ordinates are
  49953. relative to the parent window's origin, not the screen origin.
  49954. This should result in a callback to handleMovedOrResized().
  49955. */
  49956. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  49957. /** Returns the current position and size of the window.
  49958. If the native window is contained in another window, then the co-ordinates are
  49959. relative to the parent window's origin, not the screen origin.
  49960. */
  49961. virtual const Rectangle<int> getBounds() const = 0;
  49962. /** Returns the x-position of this window, relative to the screen's origin. */
  49963. virtual const Point<int> getScreenPosition() const = 0;
  49964. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  49965. virtual const Point<int> localToGlobal (const Point<int>& relativePosition) = 0;
  49966. /** Converts a rectangle relative to the top-left of this component to screen co-ordinates. */
  49967. virtual const Rectangle<int> localToGlobal (const Rectangle<int>& relativePosition);
  49968. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  49969. virtual const Point<int> globalToLocal (const Point<int>& screenPosition) = 0;
  49970. /** Converts a screen area to a position relative to the top-left of this component. */
  49971. virtual const Rectangle<int> globalToLocal (const Rectangle<int>& screenPosition);
  49972. /** Minimises the window. */
  49973. virtual void setMinimised (bool shouldBeMinimised) = 0;
  49974. /** True if the window is currently minimised. */
  49975. virtual bool isMinimised() const = 0;
  49976. /** Enable/disable fullscreen mode for the window. */
  49977. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  49978. /** True if the window is currently full-screen. */
  49979. virtual bool isFullScreen() const = 0;
  49980. /** Sets the size to restore to if fullscreen mode is turned off. */
  49981. void setNonFullScreenBounds (const Rectangle<int>& newBounds) noexcept;
  49982. /** Returns the size to restore to if fullscreen mode is turned off. */
  49983. const Rectangle<int>& getNonFullScreenBounds() const noexcept;
  49984. /** Attempts to change the icon associated with this window.
  49985. */
  49986. virtual void setIcon (const Image& newIcon) = 0;
  49987. /** Sets a constrainer to use if the peer can resize itself.
  49988. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  49989. */
  49990. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) noexcept;
  49991. /** Returns the current constrainer, if one has been set. */
  49992. ComponentBoundsConstrainer* getConstrainer() const noexcept { return constrainer; }
  49993. /** Checks if a point is in the window.
  49994. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  49995. is false, then this returns false if the point is actually inside a child of this
  49996. window.
  49997. */
  49998. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  49999. /** Returns the size of the window frame that's around this window.
  50000. Whether or not the window has a normal window frame depends on the flags
  50001. that were set when the window was created by Component::addToDesktop()
  50002. */
  50003. virtual const BorderSize<int> getFrameSize() const = 0;
  50004. /** This is called when the window's bounds change.
  50005. A peer implementation must call this when the window is moved and resized, so that
  50006. this method can pass the message on to the component.
  50007. */
  50008. void handleMovedOrResized();
  50009. /** This is called if the screen resolution changes.
  50010. A peer implementation must call this if the monitor arrangement changes or the available
  50011. screen size changes.
  50012. */
  50013. void handleScreenSizeChange();
  50014. /** This is called to repaint the component into the given context. */
  50015. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  50016. /** Sets this window to either be always-on-top or normal.
  50017. Some kinds of window might not be able to do this, so should return false.
  50018. */
  50019. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  50020. /** Brings the window to the top, optionally also giving it focus. */
  50021. virtual void toFront (bool makeActive) = 0;
  50022. /** Moves the window to be just behind another one. */
  50023. virtual void toBehind (ComponentPeer* other) = 0;
  50024. /** Called when the window is brought to the front, either by the OS or by a call
  50025. to toFront().
  50026. */
  50027. void handleBroughtToFront();
  50028. /** True if the window has the keyboard focus. */
  50029. virtual bool isFocused() const = 0;
  50030. /** Tries to give the window keyboard focus. */
  50031. virtual void grabFocus() = 0;
  50032. /** Called when the window gains keyboard focus. */
  50033. void handleFocusGain();
  50034. /** Called when the window loses keyboard focus. */
  50035. void handleFocusLoss();
  50036. Component* getLastFocusedSubcomponent() const noexcept;
  50037. /** Called when a key is pressed.
  50038. For keycode info, see the KeyPress class.
  50039. Returns true if the keystroke was used.
  50040. */
  50041. bool handleKeyPress (int keyCode, juce_wchar textCharacter);
  50042. /** Called whenever a key is pressed or released.
  50043. Returns true if the keystroke was used.
  50044. */
  50045. bool handleKeyUpOrDown (bool isKeyDown);
  50046. /** Called whenever a modifier key is pressed or released. */
  50047. void handleModifierKeysChange();
  50048. /** Tells the window that text input may be required at the given position.
  50049. This may cause things like a virtual on-screen keyboard to appear, depending
  50050. on the OS.
  50051. */
  50052. virtual void textInputRequired (const Point<int>& position) = 0;
  50053. /** If there's some kind of OS input-method in progress, this should dismiss it. */
  50054. virtual void dismissPendingTextInput();
  50055. /** Returns the currently focused TextInputTarget, or null if none is found. */
  50056. TextInputTarget* findCurrentTextInputTarget();
  50057. /** Invalidates a region of the window to be repainted asynchronously. */
  50058. virtual void repaint (const Rectangle<int>& area) = 0;
  50059. /** This can be called (from the message thread) to cause the immediate redrawing
  50060. of any areas of this window that need repainting.
  50061. You shouldn't ever really need to use this, it's mainly for special purposes
  50062. like supporting audio plugins where the host's event loop is out of our control.
  50063. */
  50064. virtual void performAnyPendingRepaintsNow() = 0;
  50065. /** Changes the window's transparency. */
  50066. virtual void setAlpha (float newAlpha) = 0;
  50067. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  50068. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  50069. void handleUserClosingWindow();
  50070. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  50071. void handleFileDragExit (const StringArray& files);
  50072. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  50073. /** Resets the masking region.
  50074. The subclass should call this every time it's about to call the handlePaint
  50075. method.
  50076. @see addMaskedRegion
  50077. */
  50078. void clearMaskedRegion();
  50079. /** Adds a rectangle to the set of areas not to paint over.
  50080. A component can call this on its peer during its paint() method, to signal
  50081. that the painting code should ignore a given region. The reason
  50082. for this is to stop embedded windows (such as OpenGL) getting painted over.
  50083. The masked region is cleared each time before a paint happens, so a component
  50084. will have to make sure it calls this every time it's painted.
  50085. */
  50086. void addMaskedRegion (int x, int y, int w, int h);
  50087. /** Returns the number of currently-active peers.
  50088. @see getPeer
  50089. */
  50090. static int getNumPeers() noexcept;
  50091. /** Returns one of the currently-active peers.
  50092. @see getNumPeers
  50093. */
  50094. static ComponentPeer* getPeer (int index) noexcept;
  50095. /** Checks if this peer object is valid.
  50096. @see getNumPeers
  50097. */
  50098. static bool isValidPeer (const ComponentPeer* peer) noexcept;
  50099. virtual StringArray getAvailableRenderingEngines();
  50100. virtual int getCurrentRenderingEngine() const;
  50101. virtual void setCurrentRenderingEngine (int index);
  50102. protected:
  50103. Component* const component;
  50104. const int styleFlags;
  50105. RectangleList maskedRegion;
  50106. Rectangle<int> lastNonFullscreenBounds;
  50107. uint32 lastPaintTime;
  50108. ComponentBoundsConstrainer* constrainer;
  50109. static void updateCurrentModifiers() noexcept;
  50110. private:
  50111. WeakReference<Component> lastFocusedComponent, dragAndDropTargetComponent;
  50112. Component* lastDragAndDropCompUnderMouse;
  50113. const uint32 uniqueID;
  50114. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  50115. friend class Component;
  50116. friend class Desktop;
  50117. static ComponentPeer* getPeerFor (const Component* component) noexcept;
  50118. void setLastDragDropTarget (Component* comp);
  50119. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentPeer);
  50120. };
  50121. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  50122. /*** End of inlined file: juce_ComponentPeer.h ***/
  50123. #endif
  50124. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  50125. /*** Start of inlined file: juce_DialogWindow.h ***/
  50126. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  50127. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  50128. /**
  50129. A dialog-box style window.
  50130. This class is a convenient way of creating a DocumentWindow with a close button
  50131. that can be triggered by pressing the escape key.
  50132. Any of the methods available to a DocumentWindow or ResizableWindow are also
  50133. available to this, so it can be made resizable, have a menu bar, etc.
  50134. To add items to the box, see the ResizableWindow::setContentOwned() or
  50135. ResizableWindow::setContentNonOwned() methods. Don't add components directly to this
  50136. class - always put them in a content component!
  50137. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  50138. the user clicking the close button - for more info, see the DocumentWindow
  50139. help.
  50140. @see DocumentWindow, ResizableWindow
  50141. */
  50142. class JUCE_API DialogWindow : public DocumentWindow
  50143. {
  50144. public:
  50145. /** Creates a DialogWindow.
  50146. @param name the name to give the component - this is also
  50147. the title shown at the top of the window. To change
  50148. this later, use setName()
  50149. @param backgroundColour the colour to use for filling the window's background.
  50150. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  50151. close button to be triggered
  50152. @param addToDesktop if true, the window will be automatically added to the
  50153. desktop; if false, you can use it as a child component
  50154. */
  50155. DialogWindow (const String& name,
  50156. const Colour& backgroundColour,
  50157. bool escapeKeyTriggersCloseButton,
  50158. bool addToDesktop = true);
  50159. /** Destructor.
  50160. If a content component has been set with setContentOwned(), it will be deleted.
  50161. */
  50162. ~DialogWindow();
  50163. /** Easy way of quickly showing a dialog box containing a given component.
  50164. This will open and display a DialogWindow containing a given component, making it
  50165. modal, but returning immediately to allow the dialog to finish in its own time. If
  50166. you want to block and run a modal loop until the dialog is dismissed, use showModalDialog()
  50167. instead.
  50168. To close the dialog programatically, you should call exitModalState (returnValue) on
  50169. the DialogWindow that is created. To find a pointer to this window from your
  50170. contentComponent, you can do something like this:
  50171. @code
  50172. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) nullptr);
  50173. if (dw != nullptr)
  50174. dw->exitModalState (1234);
  50175. @endcode
  50176. @param dialogTitle the dialog box's title
  50177. @param contentComponent the content component for the dialog box. Make sure
  50178. that this has been set to the size you want it to
  50179. be before calling this method. The component won't
  50180. be deleted by this call, so you can re-use it or delete
  50181. it afterwards
  50182. @param componentToCentreAround if this is non-zero, it indicates a component that
  50183. you'd like to show this dialog box in front of. See the
  50184. DocumentWindow::centreAroundComponent() method for more
  50185. info on this parameter
  50186. @param backgroundColour a colour to use for the dialog box's background colour
  50187. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  50188. close button to be triggered
  50189. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  50190. a corner resizer
  50191. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  50192. to use a border or corner resizer component. See ResizableWindow::setResizable()
  50193. */
  50194. static void showDialog (const String& dialogTitle,
  50195. Component* contentComponent,
  50196. Component* componentToCentreAround,
  50197. const Colour& backgroundColour,
  50198. bool escapeKeyTriggersCloseButton,
  50199. bool shouldBeResizable = false,
  50200. bool useBottomRightCornerResizer = false);
  50201. /** Easy way of quickly showing a dialog box containing a given component.
  50202. This will open and display a DialogWindow containing a given component, returning
  50203. when the user clicks its close button.
  50204. It returns the value that was returned by the dialog box's runModalLoop() call.
  50205. To close the dialog programatically, you should call exitModalState (returnValue) on
  50206. the DialogWindow that is created. To find a pointer to this window from your
  50207. contentComponent, you can do something like this:
  50208. @code
  50209. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) nullptr);
  50210. if (dw != nullptr)
  50211. dw->exitModalState (1234);
  50212. @endcode
  50213. @param dialogTitle the dialog box's title
  50214. @param contentComponent the content component for the dialog box. Make sure
  50215. that this has been set to the size you want it to
  50216. be before calling this method. The component won't
  50217. be deleted by this call, so you can re-use it or delete
  50218. it afterwards
  50219. @param componentToCentreAround if this is non-zero, it indicates a component that
  50220. you'd like to show this dialog box in front of. See the
  50221. DocumentWindow::centreAroundComponent() method for more
  50222. info on this parameter
  50223. @param backgroundColour a colour to use for the dialog box's background colour
  50224. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  50225. close button to be triggered
  50226. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  50227. a corner resizer
  50228. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  50229. to use a border or corner resizer component. See ResizableWindow::setResizable()
  50230. */
  50231. #if JUCE_MODAL_LOOPS_PERMITTED || DOXYGEN
  50232. static int showModalDialog (const String& dialogTitle,
  50233. Component* contentComponent,
  50234. Component* componentToCentreAround,
  50235. const Colour& backgroundColour,
  50236. bool escapeKeyTriggersCloseButton,
  50237. bool shouldBeResizable = false,
  50238. bool useBottomRightCornerResizer = false);
  50239. #endif
  50240. protected:
  50241. /** @internal */
  50242. void resized();
  50243. private:
  50244. bool escapeKeyTriggersCloseButton;
  50245. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DialogWindow);
  50246. };
  50247. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  50248. /*** End of inlined file: juce_DialogWindow.h ***/
  50249. #endif
  50250. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  50251. #endif
  50252. #ifndef __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  50253. /*** Start of inlined file: juce_NativeMessageBox.h ***/
  50254. #ifndef __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  50255. #define __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  50256. class NativeMessageBox
  50257. {
  50258. public:
  50259. /** Shows a dialog box that just has a message and a single 'ok' button to close it.
  50260. If the callback parameter is null, the box is shown modally, and the method will
  50261. block until the user has clicked the button (or pressed the escape or return keys).
  50262. If the callback parameter is non-null, the box will be displayed and placed into a
  50263. modal state, but this method will return immediately, and the callback will be invoked
  50264. later when the user dismisses the box.
  50265. @param iconType the type of icon to show
  50266. @param title the headline to show at the top of the box
  50267. @param message a longer, more descriptive message to show underneath the title
  50268. @param associatedComponent if this is non-null, it specifies the component that the
  50269. alert window should be associated with. Depending on the look
  50270. and feel, this might be used for positioning of the alert window.
  50271. */
  50272. #if JUCE_MODAL_LOOPS_PERMITTED
  50273. static void JUCE_CALLTYPE showMessageBox (AlertWindow::AlertIconType iconType,
  50274. const String& title,
  50275. const String& message,
  50276. Component* associatedComponent = nullptr);
  50277. #endif
  50278. /** Shows a dialog box that just has a message and a single 'ok' button to close it.
  50279. If the callback parameter is null, the box is shown modally, and the method will
  50280. block until the user has clicked the button (or pressed the escape or return keys).
  50281. If the callback parameter is non-null, the box will be displayed and placed into a
  50282. modal state, but this method will return immediately, and the callback will be invoked
  50283. later when the user dismisses the box.
  50284. @param iconType the type of icon to show
  50285. @param title the headline to show at the top of the box
  50286. @param message a longer, more descriptive message to show underneath the title
  50287. @param associatedComponent if this is non-null, it specifies the component that the
  50288. alert window should be associated with. Depending on the look
  50289. and feel, this might be used for positioning of the alert window.
  50290. */
  50291. static void JUCE_CALLTYPE showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  50292. const String& title,
  50293. const String& message,
  50294. Component* associatedComponent = nullptr);
  50295. /** Shows a dialog box with two buttons.
  50296. Ideal for ok/cancel or yes/no choices. The return key can also be used
  50297. to trigger the first button, and the escape key for the second button.
  50298. If the callback parameter is null, the box is shown modally, and the method will
  50299. block until the user has clicked the button (or pressed the escape or return keys).
  50300. If the callback parameter is non-null, the box will be displayed and placed into a
  50301. modal state, but this method will return immediately, and the callback will be invoked
  50302. later when the user dismisses the box.
  50303. @param iconType the type of icon to show
  50304. @param title the headline to show at the top of the box
  50305. @param message a longer, more descriptive message to show underneath the title
  50306. @param associatedComponent if this is non-null, it specifies the component that the
  50307. alert window should be associated with. Depending on the look
  50308. and feel, this might be used for positioning of the alert window.
  50309. @param callback if this is non-null, the menu will be launched asynchronously,
  50310. returning immediately, and the callback will receive a call to its
  50311. modalStateFinished() when the box is dismissed, with its parameter
  50312. being 1 if the ok button was pressed, or 0 for cancel, The callback object
  50313. will be owned and deleted by the system, so make sure that it works
  50314. safely and doesn't keep any references to objects that might be deleted
  50315. before it gets called.
  50316. @returns true if button 1 was clicked, false if it was button 2. If the callback parameter
  50317. is not null, the method always returns false, and the user's choice is delivered
  50318. later by the callback.
  50319. */
  50320. static bool JUCE_CALLTYPE showOkCancelBox (AlertWindow::AlertIconType iconType,
  50321. const String& title,
  50322. const String& message,
  50323. #if JUCE_MODAL_LOOPS_PERMITTED
  50324. Component* associatedComponent = nullptr,
  50325. ModalComponentManager::Callback* callback = nullptr);
  50326. #else
  50327. Component* associatedComponent,
  50328. ModalComponentManager::Callback* callback);
  50329. #endif
  50330. /** Shows a dialog box with three buttons.
  50331. Ideal for yes/no/cancel boxes.
  50332. The escape key can be used to trigger the third button.
  50333. If the callback parameter is null, the box is shown modally, and the method will
  50334. block until the user has clicked the button (or pressed the escape or return keys).
  50335. If the callback parameter is non-null, the box will be displayed and placed into a
  50336. modal state, but this method will return immediately, and the callback will be invoked
  50337. later when the user dismisses the box.
  50338. @param iconType the type of icon to show
  50339. @param title the headline to show at the top of the box
  50340. @param message a longer, more descriptive message to show underneath the title
  50341. @param associatedComponent if this is non-null, it specifies the component that the
  50342. alert window should be associated with. Depending on the look
  50343. and feel, this might be used for positioning of the alert window.
  50344. @param callback if this is non-null, the menu will be launched asynchronously,
  50345. returning immediately, and the callback will receive a call to its
  50346. modalStateFinished() when the box is dismissed, with its parameter
  50347. being 1 if the "yes" button was pressed, 2 for the "no" button, or 0
  50348. if it was cancelled, The callback object will be owned and deleted by the
  50349. system, so make sure that it works safely and doesn't keep any references
  50350. to objects that might be deleted before it gets called.
  50351. @returns If the callback parameter has been set, this returns 0. Otherwise, it returns one
  50352. of the following values:
  50353. - 0 if 'cancel' was pressed
  50354. - 1 if 'yes' was pressed
  50355. - 2 if 'no' was pressed
  50356. */
  50357. static int JUCE_CALLTYPE showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  50358. const String& title,
  50359. const String& message,
  50360. #if JUCE_MODAL_LOOPS_PERMITTED
  50361. Component* associatedComponent = nullptr,
  50362. ModalComponentManager::Callback* callback = nullptr);
  50363. #else
  50364. Component* associatedComponent,
  50365. ModalComponentManager::Callback* callback);
  50366. #endif
  50367. };
  50368. #endif // __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  50369. /*** End of inlined file: juce_NativeMessageBox.h ***/
  50370. #endif
  50371. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  50372. #endif
  50373. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  50374. /*** Start of inlined file: juce_SplashScreen.h ***/
  50375. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  50376. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  50377. /** A component for showing a splash screen while your app starts up.
  50378. This will automatically position itself, and delete itself when the app has
  50379. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  50380. this).
  50381. To use it, just create one of these in your JUCEApplication::initialise() method,
  50382. call its show() method and let the object delete itself later.
  50383. E.g. @code
  50384. void MyApp::initialise (const String& commandLine)
  50385. {
  50386. SplashScreen* splash = new SplashScreen();
  50387. splash->show ("welcome to my app",
  50388. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  50389. 4000, false);
  50390. .. no need to delete the splash screen - it'll do that itself.
  50391. }
  50392. @endcode
  50393. */
  50394. class JUCE_API SplashScreen : public Component,
  50395. public Timer,
  50396. private DeletedAtShutdown
  50397. {
  50398. public:
  50399. /** Creates a SplashScreen object.
  50400. After creating one of these (or your subclass of it), call one of the show()
  50401. methods to display it.
  50402. */
  50403. SplashScreen();
  50404. /** Destructor. */
  50405. ~SplashScreen();
  50406. /** Creates a SplashScreen object that will display an image.
  50407. As soon as this is called, the SplashScreen will be displayed in the centre of the
  50408. screen. This method will also dispatch any pending messages to make sure that when
  50409. it returns, the splash screen has been completely drawn, and your initialisation
  50410. code can carry on.
  50411. @param title the name to give the component
  50412. @param backgroundImage an image to draw on the component. The component's size
  50413. will be set to the size of this image, and if the image is
  50414. semi-transparent, the component will be made semi-transparent
  50415. too. This image will be deleted (or released from the ImageCache
  50416. if that's how it was created) by the splash screen object when
  50417. it is itself deleted.
  50418. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  50419. should stay visible for. If the initialisation takes longer than
  50420. this time, the splash screen will wait for it to finish before
  50421. disappearing, but if initialisation is very quick, this lets
  50422. you make sure that people get a good look at your splash.
  50423. @param useDropShadow if true, the window will have a drop shadow
  50424. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  50425. the mouse (anywhere)
  50426. */
  50427. void show (const String& title,
  50428. const Image& backgroundImage,
  50429. int minimumTimeToDisplayFor,
  50430. bool useDropShadow,
  50431. bool removeOnMouseClick = true);
  50432. /** Creates a SplashScreen object with a specified size.
  50433. For a custom splash screen, you can use this method to display it at a certain size
  50434. and then override the paint() method yourself to do whatever's necessary.
  50435. As soon as this is called, the SplashScreen will be displayed in the centre of the
  50436. screen. This method will also dispatch any pending messages to make sure that when
  50437. it returns, the splash screen has been completely drawn, and your initialisation
  50438. code can carry on.
  50439. @param title the name to give the component
  50440. @param width the width to use
  50441. @param height the height to use
  50442. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  50443. should stay visible for. If the initialisation takes longer than
  50444. this time, the splash screen will wait for it to finish before
  50445. disappearing, but if initialisation is very quick, this lets
  50446. you make sure that people get a good look at your splash.
  50447. @param useDropShadow if true, the window will have a drop shadow
  50448. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  50449. the mouse (anywhere)
  50450. */
  50451. void show (const String& title,
  50452. int width,
  50453. int height,
  50454. int minimumTimeToDisplayFor,
  50455. bool useDropShadow,
  50456. bool removeOnMouseClick = true);
  50457. /** @internal */
  50458. void paint (Graphics& g);
  50459. /** @internal */
  50460. void timerCallback();
  50461. private:
  50462. Image backgroundImage;
  50463. Time earliestTimeToDelete;
  50464. int originalClickCounter;
  50465. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SplashScreen);
  50466. };
  50467. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  50468. /*** End of inlined file: juce_SplashScreen.h ***/
  50469. #endif
  50470. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  50471. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  50472. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  50473. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  50474. /**
  50475. A thread that automatically pops up a modal dialog box with a progress bar
  50476. and cancel button while it's busy running.
  50477. These are handy for performing some sort of task while giving the user feedback
  50478. about how long there is to go, etc.
  50479. E.g. @code
  50480. class MyTask : public ThreadWithProgressWindow
  50481. {
  50482. public:
  50483. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  50484. {
  50485. }
  50486. ~MyTask()
  50487. {
  50488. }
  50489. void run()
  50490. {
  50491. for (int i = 0; i < thingsToDo; ++i)
  50492. {
  50493. // must check this as often as possible, because this is
  50494. // how we know if the user's pressed 'cancel'
  50495. if (threadShouldExit())
  50496. break;
  50497. // this will update the progress bar on the dialog box
  50498. setProgress (i / (double) thingsToDo);
  50499. // ... do the business here...
  50500. }
  50501. }
  50502. };
  50503. void doTheTask()
  50504. {
  50505. MyTask m;
  50506. if (m.runThread())
  50507. {
  50508. // thread finished normally..
  50509. }
  50510. else
  50511. {
  50512. // user pressed the cancel button..
  50513. }
  50514. }
  50515. @endcode
  50516. @see Thread, AlertWindow
  50517. */
  50518. class JUCE_API ThreadWithProgressWindow : public Thread,
  50519. private Timer
  50520. {
  50521. public:
  50522. /** Creates the thread.
  50523. Initially, the dialog box won't be visible, it'll only appear when the
  50524. runThread() method is called.
  50525. @param windowTitle the title to go at the top of the dialog box
  50526. @param hasProgressBar whether the dialog box should have a progress bar (see
  50527. setProgress() )
  50528. @param hasCancelButton whether the dialog box should have a cancel button
  50529. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  50530. the thread to stop before killing it forcibly (see
  50531. Thread::stopThread() )
  50532. @param cancelButtonText the text that should be shown in the cancel button
  50533. (if it has one)
  50534. */
  50535. ThreadWithProgressWindow (const String& windowTitle,
  50536. bool hasProgressBar,
  50537. bool hasCancelButton,
  50538. int timeOutMsWhenCancelling = 10000,
  50539. const String& cancelButtonText = "Cancel");
  50540. /** Destructor. */
  50541. ~ThreadWithProgressWindow();
  50542. /** Starts the thread and waits for it to finish.
  50543. This will start the thread, make the dialog box appear, and wait until either
  50544. the thread finishes normally, or until the cancel button is pressed.
  50545. Before returning, the dialog box will be hidden.
  50546. @param threadPriority the priority to use when starting the thread - see
  50547. Thread::startThread() for values
  50548. @returns true if the thread finished normally; false if the user pressed cancel
  50549. */
  50550. bool runThread (int threadPriority = 5);
  50551. /** The thread should call this periodically to update the position of the progress bar.
  50552. @param newProgress the progress, from 0.0 to 1.0
  50553. @see setStatusMessage
  50554. */
  50555. void setProgress (double newProgress);
  50556. /** The thread can call this to change the message that's displayed in the dialog box.
  50557. */
  50558. void setStatusMessage (const String& newStatusMessage);
  50559. /** Returns the AlertWindow that is being used.
  50560. */
  50561. AlertWindow* getAlertWindow() const noexcept { return alertWindow; }
  50562. private:
  50563. void timerCallback();
  50564. double progress;
  50565. ScopedPointer <AlertWindow> alertWindow;
  50566. String message;
  50567. CriticalSection messageLock;
  50568. const int timeOutMsWhenCancelling;
  50569. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadWithProgressWindow);
  50570. };
  50571. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  50572. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  50573. #endif
  50574. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  50575. #endif
  50576. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  50577. #endif
  50578. #ifndef __JUCE_COLOUR_JUCEHEADER__
  50579. #endif
  50580. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  50581. #endif
  50582. #ifndef __JUCE_COLOURS_JUCEHEADER__
  50583. #endif
  50584. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  50585. #endif
  50586. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  50587. /*** Start of inlined file: juce_EdgeTable.h ***/
  50588. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  50589. #define __JUCE_EDGETABLE_JUCEHEADER__
  50590. class Path;
  50591. class Image;
  50592. /**
  50593. A table of horizontal scan-line segments - used for rasterising Paths.
  50594. @see Path, Graphics
  50595. */
  50596. class JUCE_API EdgeTable
  50597. {
  50598. public:
  50599. /** Creates an edge table containing a path.
  50600. A table is created with a fixed vertical range, and only sections of the path
  50601. which lie within this range will be added to the table.
  50602. @param clipLimits only the region of the path that lies within this area will be added
  50603. @param pathToAdd the path to add to the table
  50604. @param transform a transform to apply to the path being added
  50605. */
  50606. EdgeTable (const Rectangle<int>& clipLimits,
  50607. const Path& pathToAdd,
  50608. const AffineTransform& transform);
  50609. /** Creates an edge table containing a rectangle. */
  50610. EdgeTable (const Rectangle<int>& rectangleToAdd);
  50611. /** Creates an edge table containing a rectangle list. */
  50612. EdgeTable (const RectangleList& rectanglesToAdd);
  50613. /** Creates an edge table containing a rectangle. */
  50614. EdgeTable (const Rectangle<float>& rectangleToAdd);
  50615. /** Creates a copy of another edge table. */
  50616. EdgeTable (const EdgeTable& other);
  50617. /** Copies from another edge table. */
  50618. EdgeTable& operator= (const EdgeTable& other);
  50619. /** Destructor. */
  50620. ~EdgeTable();
  50621. void clipToRectangle (const Rectangle<int>& r);
  50622. void excludeRectangle (const Rectangle<int>& r);
  50623. void clipToEdgeTable (const EdgeTable& other);
  50624. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels);
  50625. bool isEmpty() noexcept;
  50626. const Rectangle<int>& getMaximumBounds() const noexcept { return bounds; }
  50627. void translate (float dx, int dy) noexcept;
  50628. /** Reduces the amount of space the table has allocated.
  50629. This will shrink the table down to use as little memory as possible - useful for
  50630. read-only tables that get stored and re-used for rendering.
  50631. */
  50632. void optimiseTable();
  50633. /** Iterates the lines in the table, for rendering.
  50634. This function will iterate each line in the table, and call a user-defined class
  50635. to render each pixel or continuous line of pixels that the table contains.
  50636. @param iterationCallback this templated class must contain the following methods:
  50637. @code
  50638. inline void setEdgeTableYPos (int y);
  50639. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  50640. inline void handleEdgeTablePixelFull (int x) const;
  50641. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  50642. inline void handleEdgeTableLineFull (int x, int width) const;
  50643. @endcode
  50644. (these don't necessarily have to be 'const', but it might help it go faster)
  50645. */
  50646. template <class EdgeTableIterationCallback>
  50647. void iterate (EdgeTableIterationCallback& iterationCallback) const noexcept
  50648. {
  50649. const int* lineStart = table;
  50650. for (int y = 0; y < bounds.getHeight(); ++y)
  50651. {
  50652. const int* line = lineStart;
  50653. lineStart += lineStrideElements;
  50654. int numPoints = line[0];
  50655. if (--numPoints > 0)
  50656. {
  50657. int x = *++line;
  50658. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  50659. int levelAccumulator = 0;
  50660. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  50661. while (--numPoints >= 0)
  50662. {
  50663. const int level = *++line;
  50664. jassert (isPositiveAndBelow (level, (int) 256));
  50665. const int endX = *++line;
  50666. jassert (endX >= x);
  50667. const int endOfRun = (endX >> 8);
  50668. if (endOfRun == (x >> 8))
  50669. {
  50670. // small segment within the same pixel, so just save it for the next
  50671. // time round..
  50672. levelAccumulator += (endX - x) * level;
  50673. }
  50674. else
  50675. {
  50676. // plot the fist pixel of this segment, including any accumulated
  50677. // levels from smaller segments that haven't been drawn yet
  50678. levelAccumulator += (0x100 - (x & 0xff)) * level;
  50679. levelAccumulator >>= 8;
  50680. x >>= 8;
  50681. if (levelAccumulator > 0)
  50682. {
  50683. if (levelAccumulator >= 255)
  50684. iterationCallback.handleEdgeTablePixelFull (x);
  50685. else
  50686. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  50687. }
  50688. // if there's a run of similar pixels, do it all in one go..
  50689. if (level > 0)
  50690. {
  50691. jassert (endOfRun <= bounds.getRight());
  50692. const int numPix = endOfRun - ++x;
  50693. if (numPix > 0)
  50694. iterationCallback.handleEdgeTableLine (x, numPix, level);
  50695. }
  50696. // save the bit at the end to be drawn next time round the loop.
  50697. levelAccumulator = (endX & 0xff) * level;
  50698. }
  50699. x = endX;
  50700. }
  50701. levelAccumulator >>= 8;
  50702. if (levelAccumulator > 0)
  50703. {
  50704. x >>= 8;
  50705. jassert (x >= bounds.getX() && x < bounds.getRight());
  50706. if (levelAccumulator >= 255)
  50707. iterationCallback.handleEdgeTablePixelFull (x);
  50708. else
  50709. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  50710. }
  50711. }
  50712. }
  50713. }
  50714. private:
  50715. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  50716. HeapBlock<int> table;
  50717. Rectangle<int> bounds;
  50718. int maxEdgesPerLine, lineStrideElements;
  50719. bool needToCheckEmptinesss;
  50720. void addEdgePoint (int x, int y, int winding);
  50721. void remapTableForNumEdges (int newNumEdgesPerLine);
  50722. void intersectWithEdgeTableLine (int y, const int* otherLine);
  50723. void clipEdgeTableLineToRange (int* line, int x1, int x2) noexcept;
  50724. void sanitiseLevels (bool useNonZeroWinding) noexcept;
  50725. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) noexcept;
  50726. JUCE_LEAK_DETECTOR (EdgeTable);
  50727. };
  50728. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  50729. /*** End of inlined file: juce_EdgeTable.h ***/
  50730. #endif
  50731. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  50732. /*** Start of inlined file: juce_FillType.h ***/
  50733. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  50734. #define __JUCE_FILLTYPE_JUCEHEADER__
  50735. /**
  50736. Represents a colour or fill pattern to use for rendering paths.
  50737. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  50738. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  50739. @see Graphics::setFillType, DrawablePath::setFill
  50740. */
  50741. class JUCE_API FillType
  50742. {
  50743. public:
  50744. /** Creates a default fill type, of solid black. */
  50745. FillType() noexcept;
  50746. /** Creates a fill type of a solid colour.
  50747. @see setColour
  50748. */
  50749. FillType (const Colour& colour) noexcept;
  50750. /** Creates a gradient fill type.
  50751. @see setGradient
  50752. */
  50753. FillType (const ColourGradient& gradient);
  50754. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  50755. and rotation of the pattern.
  50756. @see setTiledImage
  50757. */
  50758. FillType (const Image& image, const AffineTransform& transform) noexcept;
  50759. /** Creates a copy of another FillType. */
  50760. FillType (const FillType& other);
  50761. /** Makes a copy of another FillType. */
  50762. FillType& operator= (const FillType& other);
  50763. /** Destructor. */
  50764. ~FillType() noexcept;
  50765. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  50766. bool isColour() const noexcept { return gradient == nullptr && image.isNull(); }
  50767. /** Returns true if this is a gradient fill. */
  50768. bool isGradient() const noexcept { return gradient != nullptr; }
  50769. /** Returns true if this is a tiled image pattern fill. */
  50770. bool isTiledImage() const noexcept { return image.isValid(); }
  50771. /** Turns this object into a solid colour fill.
  50772. If the object was an image or gradient, those fields will no longer be valid. */
  50773. void setColour (const Colour& newColour) noexcept;
  50774. /** Turns this object into a gradient fill. */
  50775. void setGradient (const ColourGradient& newGradient);
  50776. /** Turns this object into a tiled image fill type. The transform allows you to set
  50777. the scaling, offset and rotation of the pattern.
  50778. */
  50779. void setTiledImage (const Image& image, const AffineTransform& transform) noexcept;
  50780. /** Changes the opacity that should be used.
  50781. If the fill is a solid colour, this just changes the opacity of that colour. For
  50782. gradients and image tiles, it changes the opacity that will be used for them.
  50783. */
  50784. void setOpacity (float newOpacity) noexcept;
  50785. /** Returns the current opacity to be applied to the colour, gradient, or image.
  50786. @see setOpacity
  50787. */
  50788. float getOpacity() const noexcept { return colour.getFloatAlpha(); }
  50789. /** Returns true if this fill type is completely transparent. */
  50790. bool isInvisible() const noexcept;
  50791. /** The solid colour being used.
  50792. If the fill type is not a solid colour, the alpha channel of this colour indicates
  50793. the opacity that should be used for the fill, and the RGB channels are ignored.
  50794. */
  50795. Colour colour;
  50796. /** Returns the gradient that should be used for filling.
  50797. This will be zero if the object is some other type of fill.
  50798. If a gradient is active, the overall opacity with which it should be applied
  50799. is indicated by the alpha channel of the colour variable.
  50800. */
  50801. ScopedPointer <ColourGradient> gradient;
  50802. /** The image that should be used for tiling.
  50803. If an image fill is active, the overall opacity with which it should be applied
  50804. is indicated by the alpha channel of the colour variable.
  50805. */
  50806. Image image;
  50807. /** The transform that should be applied to the image or gradient that's being drawn. */
  50808. AffineTransform transform;
  50809. bool operator== (const FillType& other) const;
  50810. bool operator!= (const FillType& other) const;
  50811. private:
  50812. JUCE_LEAK_DETECTOR (FillType);
  50813. };
  50814. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  50815. /*** End of inlined file: juce_FillType.h ***/
  50816. #endif
  50817. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  50818. #endif
  50819. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  50820. #endif
  50821. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  50822. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  50823. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  50824. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  50825. /**
  50826. Interface class for graphics context objects, used internally by the Graphics class.
  50827. Users are not supposed to create instances of this class directly - do your drawing
  50828. via the Graphics object instead.
  50829. It's a base class for different types of graphics context, that may perform software-based
  50830. or OS-accelerated rendering.
  50831. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  50832. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  50833. context.
  50834. */
  50835. class JUCE_API LowLevelGraphicsContext
  50836. {
  50837. protected:
  50838. LowLevelGraphicsContext();
  50839. public:
  50840. virtual ~LowLevelGraphicsContext();
  50841. /** Returns true if this device is vector-based, e.g. a printer. */
  50842. virtual bool isVectorDevice() const = 0;
  50843. /** Moves the origin to a new position.
  50844. The co-ords are relative to the current origin, and indicate the new position
  50845. of (0, 0).
  50846. */
  50847. virtual void setOrigin (int x, int y) = 0;
  50848. virtual void addTransform (const AffineTransform& transform) = 0;
  50849. virtual float getScaleFactor() = 0;
  50850. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  50851. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  50852. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  50853. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  50854. virtual void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform) = 0;
  50855. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  50856. virtual const Rectangle<int> getClipBounds() const = 0;
  50857. virtual bool isClipEmpty() const = 0;
  50858. virtual void saveState() = 0;
  50859. virtual void restoreState() = 0;
  50860. virtual void beginTransparencyLayer (float opacity) = 0;
  50861. virtual void endTransparencyLayer() = 0;
  50862. virtual void setFill (const FillType& fillType) = 0;
  50863. virtual void setOpacity (float newOpacity) = 0;
  50864. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  50865. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  50866. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  50867. virtual void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  50868. virtual void drawLine (const Line <float>& line) = 0;
  50869. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  50870. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  50871. virtual void setFont (const Font& newFont) = 0;
  50872. virtual Font getFont() = 0;
  50873. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  50874. };
  50875. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  50876. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  50877. #endif
  50878. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50879. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  50880. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50881. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50882. /**
  50883. An implementation of LowLevelGraphicsContext that turns the drawing operations
  50884. into a PostScript document.
  50885. */
  50886. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  50887. {
  50888. public:
  50889. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  50890. const String& documentTitle,
  50891. int totalWidth,
  50892. int totalHeight);
  50893. ~LowLevelGraphicsPostScriptRenderer();
  50894. bool isVectorDevice() const;
  50895. void setOrigin (int x, int y);
  50896. void addTransform (const AffineTransform& transform);
  50897. float getScaleFactor();
  50898. bool clipToRectangle (const Rectangle<int>& r);
  50899. bool clipToRectangleList (const RectangleList& clipRegion);
  50900. void excludeClipRectangle (const Rectangle<int>& r);
  50901. void clipToPath (const Path& path, const AffineTransform& transform);
  50902. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  50903. void saveState();
  50904. void restoreState();
  50905. void beginTransparencyLayer (float opacity);
  50906. void endTransparencyLayer();
  50907. bool clipRegionIntersects (const Rectangle<int>& r);
  50908. const Rectangle<int> getClipBounds() const;
  50909. bool isClipEmpty() const;
  50910. void setFill (const FillType& fillType);
  50911. void setOpacity (float opacity);
  50912. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  50913. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  50914. void fillPath (const Path& path, const AffineTransform& transform);
  50915. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  50916. void drawLine (const Line <float>& line);
  50917. void drawVerticalLine (int x, float top, float bottom);
  50918. void drawHorizontalLine (int x, float top, float bottom);
  50919. Font getFont();
  50920. void setFont (const Font& newFont);
  50921. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  50922. protected:
  50923. OutputStream& out;
  50924. int totalWidth, totalHeight;
  50925. bool needToClip;
  50926. Colour lastColour;
  50927. struct SavedState
  50928. {
  50929. SavedState();
  50930. ~SavedState();
  50931. RectangleList clip;
  50932. int xOffset, yOffset;
  50933. FillType fillType;
  50934. Font font;
  50935. private:
  50936. SavedState& operator= (const SavedState&);
  50937. };
  50938. OwnedArray <SavedState> stateStack;
  50939. void writeClip();
  50940. void writeColour (const Colour& colour);
  50941. void writePath (const Path& path) const;
  50942. void writeXY (float x, float y) const;
  50943. void writeTransform (const AffineTransform& trans) const;
  50944. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  50945. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsPostScriptRenderer);
  50946. };
  50947. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  50948. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  50949. #endif
  50950. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50951. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  50952. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50953. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  50954. /**
  50955. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  50956. its rendering in memory.
  50957. User code is not supposed to create instances of this class directly - do all your
  50958. rendering via the Graphics class instead.
  50959. */
  50960. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  50961. {
  50962. public:
  50963. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  50964. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  50965. ~LowLevelGraphicsSoftwareRenderer();
  50966. bool isVectorDevice() const;
  50967. void setOrigin (int x, int y);
  50968. void addTransform (const AffineTransform& transform);
  50969. float getScaleFactor();
  50970. bool clipToRectangle (const Rectangle<int>& r);
  50971. bool clipToRectangleList (const RectangleList& clipRegion);
  50972. void excludeClipRectangle (const Rectangle<int>& r);
  50973. void clipToPath (const Path& path, const AffineTransform& transform);
  50974. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  50975. bool clipRegionIntersects (const Rectangle<int>& r);
  50976. const Rectangle<int> getClipBounds() const;
  50977. bool isClipEmpty() const;
  50978. void saveState();
  50979. void restoreState();
  50980. void beginTransparencyLayer (float opacity);
  50981. void endTransparencyLayer();
  50982. void setFill (const FillType& fillType);
  50983. void setOpacity (float opacity);
  50984. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  50985. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  50986. void fillPath (const Path& path, const AffineTransform& transform);
  50987. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  50988. void drawLine (const Line <float>& line);
  50989. void drawVerticalLine (int x, float top, float bottom);
  50990. void drawHorizontalLine (int x, float top, float bottom);
  50991. void setFont (const Font& newFont);
  50992. Font getFont();
  50993. void drawGlyph (int glyphNumber, float x, float y);
  50994. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  50995. protected:
  50996. Image image;
  50997. class GlyphCache;
  50998. class CachedGlyph;
  50999. class SavedState;
  51000. friend class ScopedPointer <SavedState>;
  51001. friend class OwnedArray <SavedState>;
  51002. friend class OwnedArray <CachedGlyph>;
  51003. ScopedPointer <SavedState> currentState;
  51004. OwnedArray <SavedState> stateStack;
  51005. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsSoftwareRenderer);
  51006. };
  51007. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  51008. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  51009. #endif
  51010. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  51011. #endif
  51012. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  51013. #endif
  51014. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  51015. /*** Start of inlined file: juce_DrawableComposite.h ***/
  51016. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  51017. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  51018. /**
  51019. A drawable object which acts as a container for a set of other Drawables.
  51020. @see Drawable
  51021. */
  51022. class JUCE_API DrawableComposite : public Drawable
  51023. {
  51024. public:
  51025. /** Creates a composite Drawable. */
  51026. DrawableComposite();
  51027. /** Creates a copy of a DrawableComposite. */
  51028. DrawableComposite (const DrawableComposite& other);
  51029. /** Destructor. */
  51030. ~DrawableComposite();
  51031. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  51032. @see setContentArea
  51033. */
  51034. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  51035. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  51036. @see setBoundingBox
  51037. */
  51038. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  51039. /** Changes the bounding box transform to match the content area, so that any sub-items will
  51040. be drawn at their untransformed positions.
  51041. */
  51042. void resetBoundingBoxToContentArea();
  51043. /** Returns the main content rectangle.
  51044. The content area is actually defined by the markers named "left", "right", "top" and
  51045. "bottom", but this method is a shortcut that returns them all at once.
  51046. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  51047. */
  51048. RelativeRectangle getContentArea() const;
  51049. /** Changes the main content area.
  51050. The content area is actually defined by the markers named "left", "right", "top" and
  51051. "bottom", but this method is a shortcut that sets them all at once.
  51052. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  51053. */
  51054. void setContentArea (const RelativeRectangle& newArea);
  51055. /** Resets the content area and the bounding transform to fit around the area occupied
  51056. by the child components (ignoring any markers).
  51057. */
  51058. void resetContentAreaAndBoundingBoxToFitChildren();
  51059. /** The name of the marker that defines the left edge of the content area. */
  51060. static const char* const contentLeftMarkerName;
  51061. /** The name of the marker that defines the right edge of the content area. */
  51062. static const char* const contentRightMarkerName;
  51063. /** The name of the marker that defines the top edge of the content area. */
  51064. static const char* const contentTopMarkerName;
  51065. /** The name of the marker that defines the bottom edge of the content area. */
  51066. static const char* const contentBottomMarkerName;
  51067. /** @internal */
  51068. Drawable* createCopy() const;
  51069. /** @internal */
  51070. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  51071. /** @internal */
  51072. ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  51073. /** @internal */
  51074. static const Identifier valueTreeType;
  51075. /** @internal */
  51076. Rectangle<float> getDrawableBounds() const;
  51077. /** @internal */
  51078. void childBoundsChanged (Component*);
  51079. /** @internal */
  51080. void childrenChanged();
  51081. /** @internal */
  51082. void parentHierarchyChanged();
  51083. /** @internal */
  51084. MarkerList* getMarkers (bool xAxis);
  51085. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  51086. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  51087. {
  51088. public:
  51089. ValueTreeWrapper (const ValueTree& state);
  51090. ValueTree getChildList() const;
  51091. ValueTree getChildListCreating (UndoManager* undoManager);
  51092. RelativeParallelogram getBoundingBox() const;
  51093. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  51094. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  51095. RelativeRectangle getContentArea() const;
  51096. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  51097. MarkerList::ValueTreeWrapper getMarkerList (bool xAxis) const;
  51098. MarkerList::ValueTreeWrapper getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  51099. static const Identifier topLeft, topRight, bottomLeft;
  51100. private:
  51101. static const Identifier childGroupTag, markerGroupTagX, markerGroupTagY;
  51102. };
  51103. private:
  51104. RelativeParallelogram bounds;
  51105. MarkerList markersX, markersY;
  51106. bool updateBoundsReentrant;
  51107. friend class Drawable::Positioner<DrawableComposite>;
  51108. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  51109. void recalculateCoordinates (Expression::Scope*);
  51110. void updateBoundsToFitChildren();
  51111. DrawableComposite& operator= (const DrawableComposite&);
  51112. JUCE_LEAK_DETECTOR (DrawableComposite);
  51113. };
  51114. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  51115. /*** End of inlined file: juce_DrawableComposite.h ***/
  51116. #endif
  51117. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  51118. /*** Start of inlined file: juce_DrawableImage.h ***/
  51119. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  51120. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  51121. /**
  51122. A drawable object which is a bitmap image.
  51123. @see Drawable
  51124. */
  51125. class JUCE_API DrawableImage : public Drawable
  51126. {
  51127. public:
  51128. DrawableImage();
  51129. DrawableImage (const DrawableImage& other);
  51130. /** Destructor. */
  51131. ~DrawableImage();
  51132. /** Sets the image that this drawable will render. */
  51133. void setImage (const Image& imageToUse);
  51134. /** Returns the current image. */
  51135. const Image& getImage() const noexcept { return image; }
  51136. /** Sets the opacity to use when drawing the image. */
  51137. void setOpacity (float newOpacity);
  51138. /** Returns the image's opacity. */
  51139. float getOpacity() const noexcept { return opacity; }
  51140. /** Sets a colour to draw over the image's alpha channel.
  51141. By default this is transparent so isn't drawn, but if you set a non-transparent
  51142. colour here, then it will be overlaid on the image, using the image's alpha
  51143. channel as a mask.
  51144. This is handy for doing things like darkening or lightening an image by overlaying
  51145. it with semi-transparent black or white.
  51146. */
  51147. void setOverlayColour (const Colour& newOverlayColour);
  51148. /** Returns the overlay colour. */
  51149. const Colour& getOverlayColour() const noexcept { return overlayColour; }
  51150. /** Sets the bounding box within which the image should be displayed. */
  51151. void setBoundingBox (const RelativeParallelogram& newBounds);
  51152. /** Returns the position to which the image's top-left corner should be remapped in the target
  51153. coordinate space when rendering this object.
  51154. @see setTransform
  51155. */
  51156. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  51157. /** @internal */
  51158. void paint (Graphics& g);
  51159. /** @internal */
  51160. bool hitTest (int x, int y);
  51161. /** @internal */
  51162. Drawable* createCopy() const;
  51163. /** @internal */
  51164. Rectangle<float> getDrawableBounds() const;
  51165. /** @internal */
  51166. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  51167. /** @internal */
  51168. ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  51169. /** @internal */
  51170. static const Identifier valueTreeType;
  51171. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  51172. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  51173. {
  51174. public:
  51175. ValueTreeWrapper (const ValueTree& state);
  51176. var getImageIdentifier() const;
  51177. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  51178. Value getImageIdentifierValue (UndoManager* undoManager);
  51179. float getOpacity() const;
  51180. void setOpacity (float newOpacity, UndoManager* undoManager);
  51181. Value getOpacityValue (UndoManager* undoManager);
  51182. const Colour getOverlayColour() const;
  51183. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  51184. Value getOverlayColourValue (UndoManager* undoManager);
  51185. RelativeParallelogram getBoundingBox() const;
  51186. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  51187. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  51188. };
  51189. private:
  51190. Image image;
  51191. float opacity;
  51192. Colour overlayColour;
  51193. RelativeParallelogram bounds;
  51194. friend class Drawable::Positioner<DrawableImage>;
  51195. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  51196. void recalculateCoordinates (Expression::Scope*);
  51197. DrawableImage& operator= (const DrawableImage&);
  51198. JUCE_LEAK_DETECTOR (DrawableImage);
  51199. };
  51200. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  51201. /*** End of inlined file: juce_DrawableImage.h ***/
  51202. #endif
  51203. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  51204. /*** Start of inlined file: juce_DrawablePath.h ***/
  51205. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  51206. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  51207. /*** Start of inlined file: juce_DrawableShape.h ***/
  51208. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  51209. #define __JUCE_DRAWABLESHAPE_JUCEHEADER__
  51210. /**
  51211. A base class implementing common functionality for Drawable classes which
  51212. consist of some kind of filled and stroked outline.
  51213. @see DrawablePath, DrawableRectangle
  51214. */
  51215. class JUCE_API DrawableShape : public Drawable
  51216. {
  51217. protected:
  51218. DrawableShape();
  51219. DrawableShape (const DrawableShape&);
  51220. public:
  51221. /** Destructor. */
  51222. ~DrawableShape();
  51223. /** A FillType wrapper that allows the gradient coordinates to be implemented using RelativePoint.
  51224. */
  51225. class RelativeFillType
  51226. {
  51227. public:
  51228. RelativeFillType();
  51229. RelativeFillType (const FillType& fill);
  51230. RelativeFillType (const RelativeFillType&);
  51231. RelativeFillType& operator= (const RelativeFillType&);
  51232. bool operator== (const RelativeFillType&) const;
  51233. bool operator!= (const RelativeFillType&) const;
  51234. bool isDynamic() const;
  51235. bool recalculateCoords (Expression::Scope* scope);
  51236. void writeTo (ValueTree& v, ComponentBuilder::ImageProvider*, UndoManager*) const;
  51237. bool readFrom (const ValueTree& v, ComponentBuilder::ImageProvider*);
  51238. FillType fill;
  51239. RelativePoint gradientPoint1, gradientPoint2, gradientPoint3;
  51240. };
  51241. /** Sets a fill type for the path.
  51242. This colour is used to fill the path - if you don't want the path to be
  51243. filled (e.g. if you're just drawing an outline), set this to a transparent
  51244. colour.
  51245. @see setPath, setStrokeFill
  51246. */
  51247. void setFill (const FillType& newFill);
  51248. /** Sets a fill type for the path.
  51249. This colour is used to fill the path - if you don't want the path to be
  51250. filled (e.g. if you're just drawing an outline), set this to a transparent
  51251. colour.
  51252. @see setPath, setStrokeFill
  51253. */
  51254. void setFill (const RelativeFillType& newFill);
  51255. /** Returns the current fill type.
  51256. @see setFill
  51257. */
  51258. const RelativeFillType& getFill() const noexcept { return mainFill; }
  51259. /** Sets the fill type with which the outline will be drawn.
  51260. @see setFill
  51261. */
  51262. void setStrokeFill (const FillType& newStrokeFill);
  51263. /** Sets the fill type with which the outline will be drawn.
  51264. @see setFill
  51265. */
  51266. void setStrokeFill (const RelativeFillType& newStrokeFill);
  51267. /** Returns the current stroke fill.
  51268. @see setStrokeFill
  51269. */
  51270. const RelativeFillType& getStrokeFill() const noexcept { return strokeFill; }
  51271. /** Changes the properties of the outline that will be drawn around the path.
  51272. If the stroke has 0 thickness, no stroke will be drawn.
  51273. @see setStrokeThickness, setStrokeColour
  51274. */
  51275. void setStrokeType (const PathStrokeType& newStrokeType);
  51276. /** Changes the stroke thickness.
  51277. This is a shortcut for calling setStrokeType.
  51278. */
  51279. void setStrokeThickness (float newThickness);
  51280. /** Returns the current outline style. */
  51281. const PathStrokeType& getStrokeType() const noexcept { return strokeType; }
  51282. /** @internal */
  51283. class FillAndStrokeState : public Drawable::ValueTreeWrapperBase
  51284. {
  51285. public:
  51286. FillAndStrokeState (const ValueTree& state);
  51287. ValueTree getFillState (const Identifier& fillOrStrokeType);
  51288. RelativeFillType getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider*) const;
  51289. void setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  51290. ComponentBuilder::ImageProvider*, UndoManager*);
  51291. PathStrokeType getStrokeType() const;
  51292. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager*);
  51293. static const Identifier type, colour, colours, fill, stroke, path, jointStyle, capStyle, strokeWidth,
  51294. gradientPoint1, gradientPoint2, gradientPoint3, radial, imageId, imageOpacity;
  51295. };
  51296. /** @internal */
  51297. Rectangle<float> getDrawableBounds() const;
  51298. /** @internal */
  51299. void paint (Graphics& g);
  51300. /** @internal */
  51301. bool hitTest (int x, int y);
  51302. protected:
  51303. /** Called when the cached path should be updated. */
  51304. void pathChanged();
  51305. /** Called when the cached stroke should be updated. */
  51306. void strokeChanged();
  51307. /** True if there's a stroke with a non-zero thickness and non-transparent colour. */
  51308. bool isStrokeVisible() const noexcept;
  51309. /** Updates the details from a FillAndStrokeState object, returning true if something changed. */
  51310. void refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider*);
  51311. /** Writes the stroke and fill details to a FillAndStrokeState object. */
  51312. void writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider*, UndoManager*) const;
  51313. PathStrokeType strokeType;
  51314. Path path, strokePath;
  51315. private:
  51316. class RelativePositioner;
  51317. RelativeFillType mainFill, strokeFill;
  51318. ScopedPointer<RelativeCoordinatePositionerBase> mainFillPositioner, strokeFillPositioner;
  51319. void setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  51320. ScopedPointer<RelativeCoordinatePositionerBase>& positioner);
  51321. DrawableShape& operator= (const DrawableShape&);
  51322. };
  51323. #endif // __JUCE_DRAWABLESHAPE_JUCEHEADER__
  51324. /*** End of inlined file: juce_DrawableShape.h ***/
  51325. /**
  51326. A drawable object which renders a filled or outlined shape.
  51327. For details on how to change the fill and stroke, see the DrawableShape class.
  51328. @see Drawable, DrawableShape
  51329. */
  51330. class JUCE_API DrawablePath : public DrawableShape
  51331. {
  51332. public:
  51333. /** Creates a DrawablePath. */
  51334. DrawablePath();
  51335. DrawablePath (const DrawablePath& other);
  51336. /** Destructor. */
  51337. ~DrawablePath();
  51338. /** Changes the path that will be drawn.
  51339. @see setFillColour, setStrokeType
  51340. */
  51341. void setPath (const Path& newPath);
  51342. /** Sets the path using a RelativePointPath.
  51343. Calling this will set up a Component::Positioner to automatically update the path
  51344. if any of the points in the source path are dynamic.
  51345. */
  51346. void setPath (const RelativePointPath& newPath);
  51347. /** Returns the current path. */
  51348. const Path& getPath() const;
  51349. /** Returns the current path for the outline. */
  51350. const Path& getStrokePath() const;
  51351. /** @internal */
  51352. Drawable* createCopy() const;
  51353. /** @internal */
  51354. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  51355. /** @internal */
  51356. ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  51357. /** @internal */
  51358. static const Identifier valueTreeType;
  51359. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  51360. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  51361. {
  51362. public:
  51363. ValueTreeWrapper (const ValueTree& state);
  51364. bool usesNonZeroWinding() const;
  51365. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  51366. class Element
  51367. {
  51368. public:
  51369. explicit Element (const ValueTree& state);
  51370. ~Element();
  51371. const Identifier getType() const noexcept { return state.getType(); }
  51372. int getNumControlPoints() const noexcept;
  51373. RelativePoint getControlPoint (int index) const;
  51374. Value getControlPointValue (int index, UndoManager*) const;
  51375. RelativePoint getStartPoint() const;
  51376. RelativePoint getEndPoint() const;
  51377. void setControlPoint (int index, const RelativePoint& point, UndoManager*);
  51378. float getLength (Expression::Scope*) const;
  51379. ValueTreeWrapper getParent() const;
  51380. Element getPreviousElement() const;
  51381. String getModeOfEndPoint() const;
  51382. void setModeOfEndPoint (const String& newMode, UndoManager*);
  51383. void convertToLine (UndoManager*);
  51384. void convertToCubic (Expression::Scope*, UndoManager*);
  51385. void convertToPathBreak (UndoManager* undoManager);
  51386. ValueTree insertPoint (const Point<float>& targetPoint, Expression::Scope*, UndoManager*);
  51387. void removePoint (UndoManager* undoManager);
  51388. float findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope*) const;
  51389. static const Identifier mode, startSubPathElement, closeSubPathElement,
  51390. lineToElement, quadraticToElement, cubicToElement;
  51391. static const char* cornerMode;
  51392. static const char* roundedMode;
  51393. static const char* symmetricMode;
  51394. ValueTree state;
  51395. };
  51396. ValueTree getPathState();
  51397. void readFrom (const RelativePointPath& path, UndoManager* undoManager);
  51398. void writeTo (RelativePointPath& path) const;
  51399. static const Identifier nonZeroWinding, point1, point2, point3;
  51400. };
  51401. private:
  51402. ScopedPointer<RelativePointPath> relativePath;
  51403. class RelativePositioner;
  51404. friend class RelativePositioner;
  51405. void applyRelativePath (const RelativePointPath&, Expression::Scope*);
  51406. DrawablePath& operator= (const DrawablePath&);
  51407. JUCE_LEAK_DETECTOR (DrawablePath);
  51408. };
  51409. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  51410. /*** End of inlined file: juce_DrawablePath.h ***/
  51411. #endif
  51412. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  51413. /*** Start of inlined file: juce_DrawableRectangle.h ***/
  51414. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  51415. #define __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  51416. /**
  51417. A Drawable object which draws a rectangle.
  51418. For details on how to change the fill and stroke, see the DrawableShape class.
  51419. @see Drawable, DrawableShape
  51420. */
  51421. class JUCE_API DrawableRectangle : public DrawableShape
  51422. {
  51423. public:
  51424. DrawableRectangle();
  51425. DrawableRectangle (const DrawableRectangle& other);
  51426. /** Destructor. */
  51427. ~DrawableRectangle();
  51428. /** Sets the rectangle's bounds. */
  51429. void setRectangle (const RelativeParallelogram& newBounds);
  51430. /** Returns the rectangle's bounds. */
  51431. const RelativeParallelogram& getRectangle() const noexcept { return bounds; }
  51432. /** Returns the corner size to be used. */
  51433. const RelativePoint& getCornerSize() const noexcept { return cornerSize; }
  51434. /** Sets a new corner size for the rectangle */
  51435. void setCornerSize (const RelativePoint& newSize);
  51436. /** @internal */
  51437. Drawable* createCopy() const;
  51438. /** @internal */
  51439. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  51440. /** @internal */
  51441. ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  51442. /** @internal */
  51443. static const Identifier valueTreeType;
  51444. /** Internally-used class for wrapping a DrawableRectangle's state into a ValueTree. */
  51445. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  51446. {
  51447. public:
  51448. ValueTreeWrapper (const ValueTree& state);
  51449. RelativeParallelogram getRectangle() const;
  51450. void setRectangle (const RelativeParallelogram& newBounds, UndoManager*);
  51451. void setCornerSize (const RelativePoint& cornerSize, UndoManager*);
  51452. RelativePoint getCornerSize() const;
  51453. Value getCornerSizeValue (UndoManager*) const;
  51454. static const Identifier topLeft, topRight, bottomLeft, cornerSize;
  51455. };
  51456. private:
  51457. friend class Drawable::Positioner<DrawableRectangle>;
  51458. RelativeParallelogram bounds;
  51459. RelativePoint cornerSize;
  51460. void rebuildPath();
  51461. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  51462. void recalculateCoordinates (Expression::Scope*);
  51463. DrawableRectangle& operator= (const DrawableRectangle&);
  51464. JUCE_LEAK_DETECTOR (DrawableRectangle);
  51465. };
  51466. #endif // __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  51467. /*** End of inlined file: juce_DrawableRectangle.h ***/
  51468. #endif
  51469. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  51470. #endif
  51471. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  51472. /*** Start of inlined file: juce_DrawableText.h ***/
  51473. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  51474. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  51475. /**
  51476. A drawable object which renders a line of text.
  51477. @see Drawable
  51478. */
  51479. class JUCE_API DrawableText : public Drawable
  51480. {
  51481. public:
  51482. /** Creates a DrawableText object. */
  51483. DrawableText();
  51484. DrawableText (const DrawableText& other);
  51485. /** Destructor. */
  51486. ~DrawableText();
  51487. /** Sets the text to display.*/
  51488. void setText (const String& newText);
  51489. /** Sets the colour of the text. */
  51490. void setColour (const Colour& newColour);
  51491. /** Returns the current text colour. */
  51492. const Colour& getColour() const noexcept { return colour; }
  51493. /** Sets the font to use.
  51494. Note that the font height and horizontal scale are actually based upon the position
  51495. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  51496. the height and scale control point will be moved to match the dimensions of the font supplied;
  51497. if it is false, then the new font's height and scale are ignored.
  51498. */
  51499. void setFont (const Font& newFont, bool applySizeAndScale);
  51500. /** Changes the justification of the text within the bounding box. */
  51501. void setJustification (const Justification& newJustification);
  51502. /** Returns the parallelogram that defines the text bounding box. */
  51503. const RelativeParallelogram& getBoundingBox() const noexcept { return bounds; }
  51504. /** Sets the bounding box that contains the text. */
  51505. void setBoundingBox (const RelativeParallelogram& newBounds);
  51506. /** Returns the point within the bounds that defines the font's size and scale. */
  51507. const RelativePoint& getFontSizeControlPoint() const noexcept { return fontSizeControlPoint; }
  51508. /** Sets the control point that defines the font's height and horizontal scale.
  51509. This position is a point within the bounding box parallelogram, whose Y position (relative
  51510. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  51511. and its X defines the font's horizontal scale.
  51512. */
  51513. void setFontSizeControlPoint (const RelativePoint& newPoint);
  51514. /** @internal */
  51515. void paint (Graphics& g);
  51516. /** @internal */
  51517. Drawable* createCopy() const;
  51518. /** @internal */
  51519. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  51520. /** @internal */
  51521. ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  51522. /** @internal */
  51523. static const Identifier valueTreeType;
  51524. /** @internal */
  51525. Rectangle<float> getDrawableBounds() const;
  51526. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  51527. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  51528. {
  51529. public:
  51530. ValueTreeWrapper (const ValueTree& state);
  51531. String getText() const;
  51532. void setText (const String& newText, UndoManager* undoManager);
  51533. Value getTextValue (UndoManager* undoManager);
  51534. Colour getColour() const;
  51535. void setColour (const Colour& newColour, UndoManager* undoManager);
  51536. Justification getJustification() const;
  51537. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  51538. Font getFont() const;
  51539. void setFont (const Font& newFont, UndoManager* undoManager);
  51540. Value getFontValue (UndoManager* undoManager);
  51541. RelativeParallelogram getBoundingBox() const;
  51542. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  51543. RelativePoint getFontSizeControlPoint() const;
  51544. void setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager);
  51545. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  51546. };
  51547. private:
  51548. RelativeParallelogram bounds;
  51549. RelativePoint fontSizeControlPoint;
  51550. Point<float> resolvedPoints[3];
  51551. Font font, scaledFont;
  51552. String text;
  51553. Colour colour;
  51554. Justification justification;
  51555. friend class Drawable::Positioner<DrawableText>;
  51556. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  51557. void recalculateCoordinates (Expression::Scope*);
  51558. void refreshBounds();
  51559. const AffineTransform getArrangementAndTransform (GlyphArrangement& glyphs) const;
  51560. DrawableText& operator= (const DrawableText&);
  51561. JUCE_LEAK_DETECTOR (DrawableText);
  51562. };
  51563. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  51564. /*** End of inlined file: juce_DrawableText.h ***/
  51565. #endif
  51566. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  51567. #endif
  51568. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  51569. /*** Start of inlined file: juce_GlowEffect.h ***/
  51570. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  51571. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  51572. /**
  51573. A component effect that adds a coloured blur around the component's contents.
  51574. (This will only work on non-opaque components).
  51575. @see Component::setComponentEffect, DropShadowEffect
  51576. */
  51577. class JUCE_API GlowEffect : public ImageEffectFilter
  51578. {
  51579. public:
  51580. /** Creates a default 'glow' effect.
  51581. To customise its appearance, use the setGlowProperties() method.
  51582. */
  51583. GlowEffect();
  51584. /** Destructor. */
  51585. ~GlowEffect();
  51586. /** Sets the glow's radius and colour.
  51587. The radius is how large the blur should be, and the colour is
  51588. used to render it (for a less intense glow, lower the colour's
  51589. opacity).
  51590. */
  51591. void setGlowProperties (float newRadius,
  51592. const Colour& newColour);
  51593. /** @internal */
  51594. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  51595. private:
  51596. float radius;
  51597. Colour colour;
  51598. JUCE_LEAK_DETECTOR (GlowEffect);
  51599. };
  51600. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  51601. /*** End of inlined file: juce_GlowEffect.h ***/
  51602. #endif
  51603. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  51604. #endif
  51605. #ifndef __JUCE_CUSTOMTYPEFACE_JUCEHEADER__
  51606. /*** Start of inlined file: juce_CustomTypeface.h ***/
  51607. #ifndef __JUCE_CUSTOMTYPEFACE_JUCEHEADER__
  51608. #define __JUCE_CUSTOMTYPEFACE_JUCEHEADER__
  51609. class InputStream;
  51610. class OutputStream;
  51611. /**
  51612. A typeface that can be populated with custom glyphs.
  51613. You can create a CustomTypeface if you need one that contains your own glyphs,
  51614. or if you need to load a typeface from a Juce-formatted binary stream.
  51615. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  51616. to copy glyphs into this face.
  51617. @see Typeface, Font
  51618. */
  51619. class JUCE_API CustomTypeface : public Typeface
  51620. {
  51621. public:
  51622. /** Creates a new, empty typeface. */
  51623. CustomTypeface();
  51624. /** Loads a typeface from a previously saved stream.
  51625. The stream must have been created by writeToStream().
  51626. @see writeToStream
  51627. */
  51628. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  51629. /** Destructor. */
  51630. ~CustomTypeface();
  51631. /** Resets this typeface, deleting all its glyphs and settings. */
  51632. void clear();
  51633. /** Sets the vital statistics for the typeface.
  51634. @param name the typeface's name
  51635. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  51636. the value that will be returned by Typeface::getAscent(). The
  51637. descent is assumed to be (1.0 - ascent)
  51638. @param isBold should be true if the typeface is bold
  51639. @param isItalic should be true if the typeface is italic
  51640. @param defaultCharacter the character to be used as a replacement if there's
  51641. no glyph available for the character that's being drawn
  51642. */
  51643. void setCharacteristics (const String& name, float ascent,
  51644. bool isBold, bool isItalic,
  51645. juce_wchar defaultCharacter) noexcept;
  51646. /** Adds a glyph to the typeface.
  51647. The path that is passed in is normalised so that the font height is 1.0, and its
  51648. origin is the anchor point of the character on its baseline.
  51649. The width is the nominal width of the character, and any extra kerning values that
  51650. are specified will be added to this width.
  51651. */
  51652. void addGlyph (juce_wchar character, const Path& path, float width) noexcept;
  51653. /** Specifies an extra kerning amount to be used between a pair of characters.
  51654. The amount will be added to the nominal width of the first character when laying out a string.
  51655. */
  51656. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) noexcept;
  51657. /** Adds a range of glyphs from another typeface.
  51658. This will attempt to pull in the paths and kerning information from another typeface and
  51659. add it to this one.
  51660. */
  51661. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) noexcept;
  51662. /** Saves this typeface as a Juce-formatted font file.
  51663. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  51664. constructor.
  51665. */
  51666. bool writeToStream (OutputStream& outputStream);
  51667. // The following methods implement the basic Typeface behaviour.
  51668. float getAscent() const;
  51669. float getDescent() const;
  51670. float getStringWidth (const String& text);
  51671. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  51672. bool getOutlineForGlyph (int glyphNumber, Path& path);
  51673. EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform);
  51674. protected:
  51675. juce_wchar defaultCharacter;
  51676. float ascent;
  51677. bool isBold, isItalic;
  51678. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  51679. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  51680. particular character and there's no corresponding glyph, they'll call this
  51681. method so that a subclass can try to add that glyph, returning true if it
  51682. manages to do so.
  51683. */
  51684. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  51685. private:
  51686. class GlyphInfo;
  51687. friend class OwnedArray<GlyphInfo>;
  51688. OwnedArray <GlyphInfo> glyphs;
  51689. short lookupTable [128];
  51690. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) noexcept;
  51691. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomTypeface);
  51692. };
  51693. #endif // __JUCE_CUSTOMTYPEFACE_JUCEHEADER__
  51694. /*** End of inlined file: juce_CustomTypeface.h ***/
  51695. #endif
  51696. #ifndef __JUCE_FONT_JUCEHEADER__
  51697. #endif
  51698. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  51699. #endif
  51700. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  51701. #endif
  51702. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  51703. #endif
  51704. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  51705. #endif
  51706. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  51707. #endif
  51708. #ifndef __JUCE_LINE_JUCEHEADER__
  51709. #endif
  51710. #ifndef __JUCE_PATH_JUCEHEADER__
  51711. #endif
  51712. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  51713. /*** Start of inlined file: juce_PathIterator.h ***/
  51714. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  51715. #define __JUCE_PATHITERATOR_JUCEHEADER__
  51716. /**
  51717. Flattens a Path object into a series of straight-line sections.
  51718. Use one of these to iterate through a Path object, and it will convert
  51719. all the curves into line sections so it's easy to render or perform
  51720. geometric operations on.
  51721. @see Path
  51722. */
  51723. class JUCE_API PathFlatteningIterator
  51724. {
  51725. public:
  51726. /** Creates a PathFlatteningIterator.
  51727. After creation, use the next() method to initialise the fields in the
  51728. object with the first line's position.
  51729. @param path the path to iterate along
  51730. @param transform a transform to apply to each point in the path being iterated
  51731. @param tolerance the amount by which the curves are allowed to deviate from the lines
  51732. into which they are being broken down - a higher tolerance contains
  51733. less lines, so can be generated faster, but will be less smooth.
  51734. */
  51735. PathFlatteningIterator (const Path& path,
  51736. const AffineTransform& transform = AffineTransform::identity,
  51737. float tolerance = defaultTolerance);
  51738. /** Destructor. */
  51739. ~PathFlatteningIterator();
  51740. /** Fetches the next line segment from the path.
  51741. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  51742. so that they describe the new line segment.
  51743. @returns false when there are no more lines to fetch.
  51744. */
  51745. bool next();
  51746. float x1; /**< The x position of the start of the current line segment. */
  51747. float y1; /**< The y position of the start of the current line segment. */
  51748. float x2; /**< The x position of the end of the current line segment. */
  51749. float y2; /**< The y position of the end of the current line segment. */
  51750. /** Indicates whether the current line segment is closing a sub-path.
  51751. If the current line is the one that connects the end of a sub-path
  51752. back to the start again, this will be true.
  51753. */
  51754. bool closesSubPath;
  51755. /** The index of the current line within the current sub-path.
  51756. E.g. you can use this to see whether the line is the first one in the
  51757. subpath by seeing if it's 0.
  51758. */
  51759. int subPathIndex;
  51760. /** Returns true if the current segment is the last in the current sub-path. */
  51761. bool isLastInSubpath() const noexcept;
  51762. /** This is the default value that should be used for the tolerance value (see the constructor parameters). */
  51763. static const float defaultTolerance;
  51764. private:
  51765. const Path& path;
  51766. const AffineTransform transform;
  51767. float* points;
  51768. const float toleranceSquared;
  51769. float subPathCloseX, subPathCloseY;
  51770. const bool isIdentityTransform;
  51771. HeapBlock <float> stackBase;
  51772. float* stackPos;
  51773. size_t index, stackSize;
  51774. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PathFlatteningIterator);
  51775. };
  51776. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  51777. /*** End of inlined file: juce_PathIterator.h ***/
  51778. #endif
  51779. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  51780. #endif
  51781. #ifndef __JUCE_POINT_JUCEHEADER__
  51782. #endif
  51783. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  51784. #endif
  51785. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  51786. #endif
  51787. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  51788. /*** Start of inlined file: juce_CameraDevice.h ***/
  51789. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  51790. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  51791. #if JUCE_USE_CAMERA || DOXYGEN
  51792. /**
  51793. Controls any video capture devices that might be available.
  51794. Use getAvailableDevices() to list the devices that are attached to the
  51795. system, then call openDevice to open one for use. Once you have a CameraDevice
  51796. object, you can get a viewer component from it, and use its methods to
  51797. stream to a file or capture still-frames.
  51798. */
  51799. class JUCE_API CameraDevice
  51800. {
  51801. public:
  51802. /** Destructor. */
  51803. virtual ~CameraDevice();
  51804. /** Returns a list of the available cameras on this machine.
  51805. You can open one of these devices by calling openDevice().
  51806. */
  51807. static StringArray getAvailableDevices();
  51808. /** Opens a camera device.
  51809. The index parameter indicates which of the items returned by getAvailableDevices()
  51810. to open.
  51811. The size constraints allow the method to choose between different resolutions if
  51812. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  51813. then these will be ignored.
  51814. */
  51815. static CameraDevice* openDevice (int deviceIndex,
  51816. int minWidth = 128, int minHeight = 64,
  51817. int maxWidth = 1024, int maxHeight = 768);
  51818. /** Returns the name of this device */
  51819. String getName() const { return name; }
  51820. /** Creates a component that can be used to display a preview of the
  51821. video from this camera.
  51822. */
  51823. Component* createViewerComponent();
  51824. /** Starts recording video to the specified file.
  51825. You should use getFileExtension() to find out the correct extension to
  51826. use for your filename.
  51827. If the file exists, it will be deleted before the recording starts.
  51828. This method may not start recording instantly, so if you need to know the
  51829. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  51830. after the recording has finished.
  51831. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  51832. or may not be used, depending on the driver.
  51833. */
  51834. void startRecordingToFile (const File& file, int quality = 2);
  51835. /** Stops recording, after a call to startRecordingToFile().
  51836. */
  51837. void stopRecording();
  51838. /** Returns the file extension that should be used for the files
  51839. that you pass to startRecordingToFile().
  51840. This may be platform-specific, e.g. ".mov" or ".avi".
  51841. */
  51842. static String getFileExtension();
  51843. /** After calling stopRecording(), this method can be called to return the timestamp
  51844. of the first frame that was written to the file.
  51845. */
  51846. Time getTimeOfFirstRecordedFrame() const;
  51847. /**
  51848. Receives callbacks with images from a CameraDevice.
  51849. @see CameraDevice::addListener
  51850. */
  51851. class JUCE_API Listener
  51852. {
  51853. public:
  51854. Listener() {}
  51855. virtual ~Listener() {}
  51856. /** This method is called when a new image arrives.
  51857. This may be called by any thread, so be careful about thread-safety,
  51858. and make sure that you process the data as quickly as possible to
  51859. avoid glitching!
  51860. */
  51861. virtual void imageReceived (const Image& image) = 0;
  51862. };
  51863. /** Adds a listener to receive images from the camera.
  51864. Be very careful not to delete the listener without first removing it by calling
  51865. removeListener().
  51866. */
  51867. void addListener (Listener* listenerToAdd);
  51868. /** Removes a listener that was previously added with addListener().
  51869. */
  51870. void removeListener (Listener* listenerToRemove);
  51871. protected:
  51872. #ifndef DOXYGEN
  51873. CameraDevice (const String& name, int index);
  51874. #endif
  51875. private:
  51876. void* internal;
  51877. bool isRecording;
  51878. String name;
  51879. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CameraDevice);
  51880. };
  51881. /** This typedef is just for compatibility with old code - newer code should use the CameraDevice::Listener class directly. */
  51882. typedef CameraDevice::Listener CameraImageListener;
  51883. #endif
  51884. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  51885. /*** End of inlined file: juce_CameraDevice.h ***/
  51886. #endif
  51887. #ifndef __JUCE_IMAGE_JUCEHEADER__
  51888. #endif
  51889. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  51890. /*** Start of inlined file: juce_ImageCache.h ***/
  51891. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  51892. #define __JUCE_IMAGECACHE_JUCEHEADER__
  51893. /**
  51894. A global cache of images that have been loaded from files or memory.
  51895. If you're loading an image and may need to use the image in more than one
  51896. place, this is used to allow the same image to be shared rather than loading
  51897. multiple copies into memory.
  51898. Another advantage is that after images are released, they will be kept in
  51899. memory for a few seconds before it is actually deleted, so if you're repeatedly
  51900. loading/deleting the same image, it'll reduce the chances of having to reload it
  51901. each time.
  51902. @see Image, ImageFileFormat
  51903. */
  51904. class JUCE_API ImageCache
  51905. {
  51906. public:
  51907. /** Loads an image from a file, (or just returns the image if it's already cached).
  51908. If the cache already contains an image that was loaded from this file,
  51909. that image will be returned. Otherwise, this method will try to load the
  51910. file, add it to the cache, and return it.
  51911. Remember that the image returned is shared, so drawing into it might
  51912. affect other things that are using it! If you want to draw on it, first
  51913. call Image::duplicateIfShared()
  51914. @param file the file to try to load
  51915. @returns the image, or null if it there was an error loading it
  51916. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  51917. */
  51918. static Image getFromFile (const File& file);
  51919. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  51920. If the cache already contains an image that was loaded from this block of memory,
  51921. that image will be returned. Otherwise, this method will try to load the
  51922. file, add it to the cache, and return it.
  51923. Remember that the image returned is shared, so drawing into it might
  51924. affect other things that are using it! If you want to draw on it, first
  51925. call Image::duplicateIfShared()
  51926. @param imageData the block of memory containing the image data
  51927. @param dataSize the data size in bytes
  51928. @returns the image, or an invalid image if it there was an error loading it
  51929. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  51930. */
  51931. static Image getFromMemory (const void* imageData, int dataSize);
  51932. /** Checks the cache for an image with a particular hashcode.
  51933. If there's an image in the cache with this hashcode, it will be returned,
  51934. otherwise it will return an invalid image.
  51935. @param hashCode the hash code that was associated with the image by addImageToCache()
  51936. @see addImageToCache
  51937. */
  51938. static Image getFromHashCode (int64 hashCode);
  51939. /** Adds an image to the cache with a user-defined hash-code.
  51940. The image passed-in will be referenced (not copied) by the cache, so it's probably
  51941. a good idea not to draw into it after adding it, otherwise this will affect all
  51942. instances of it that may be in use.
  51943. @param image the image to add
  51944. @param hashCode the hash-code to associate with it
  51945. @see getFromHashCode
  51946. */
  51947. static void addImageToCache (const Image& image, int64 hashCode);
  51948. /** Changes the amount of time before an unused image will be removed from the cache.
  51949. By default this is about 5 seconds.
  51950. */
  51951. static void setCacheTimeout (int millisecs);
  51952. private:
  51953. class Pimpl;
  51954. friend class Pimpl;
  51955. ImageCache();
  51956. ~ImageCache();
  51957. JUCE_DECLARE_NON_COPYABLE (ImageCache);
  51958. };
  51959. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  51960. /*** End of inlined file: juce_ImageCache.h ***/
  51961. #endif
  51962. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  51963. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  51964. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  51965. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  51966. /**
  51967. Represents a filter kernel to use in convoluting an image.
  51968. @see Image::applyConvolution
  51969. */
  51970. class JUCE_API ImageConvolutionKernel
  51971. {
  51972. public:
  51973. /** Creates an empty convulution kernel.
  51974. @param size the length of each dimension of the kernel, so e.g. if the size
  51975. is 5, it will create a 5x5 kernel
  51976. */
  51977. ImageConvolutionKernel (int size);
  51978. /** Destructor. */
  51979. ~ImageConvolutionKernel();
  51980. /** Resets all values in the kernel to zero. */
  51981. void clear();
  51982. /** Returns one of the kernel values. */
  51983. float getKernelValue (int x, int y) const noexcept;
  51984. /** Sets the value of a specific cell in the kernel.
  51985. The x and y parameters must be in the range 0 < x < getKernelSize().
  51986. @see setOverallSum
  51987. */
  51988. void setKernelValue (int x, int y, float value) noexcept;
  51989. /** Rescales all values in the kernel to make the total add up to a fixed value.
  51990. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  51991. */
  51992. void setOverallSum (float desiredTotalSum);
  51993. /** Multiplies all values in the kernel by a value. */
  51994. void rescaleAllValues (float multiplier);
  51995. /** Intialises the kernel for a gaussian blur.
  51996. @param blurRadius this may be larger or smaller than the kernel's actual
  51997. size but this will obviously be wasteful or clip at the
  51998. edges. Ideally the kernel should be just larger than
  51999. (blurRadius * 2).
  52000. */
  52001. void createGaussianBlur (float blurRadius);
  52002. /** Returns the size of the kernel.
  52003. E.g. if it's a 3x3 kernel, this returns 3.
  52004. */
  52005. int getKernelSize() const { return size; }
  52006. /** Applies the kernel to an image.
  52007. @param destImage the image that will receive the resultant convoluted pixels.
  52008. @param sourceImage the source image to read from - this can be the same image as
  52009. the destination, but if different, it must be exactly the same
  52010. size and format.
  52011. @param destinationArea the region of the image to apply the filter to
  52012. */
  52013. void applyToImage (Image& destImage,
  52014. const Image& sourceImage,
  52015. const Rectangle<int>& destinationArea) const;
  52016. private:
  52017. HeapBlock <float> values;
  52018. const int size;
  52019. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageConvolutionKernel);
  52020. };
  52021. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  52022. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  52023. #endif
  52024. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  52025. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  52026. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  52027. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  52028. /**
  52029. Base-class for codecs that can read and write image file formats such
  52030. as PNG, JPEG, etc.
  52031. This class also contains static methods to make it easy to load images
  52032. from files, streams or from memory.
  52033. @see Image, ImageCache
  52034. */
  52035. class JUCE_API ImageFileFormat
  52036. {
  52037. protected:
  52038. /** Creates an ImageFormat. */
  52039. ImageFileFormat() {}
  52040. public:
  52041. /** Destructor. */
  52042. virtual ~ImageFileFormat() {}
  52043. /** Returns a description of this file format.
  52044. E.g. "JPEG", "PNG"
  52045. */
  52046. virtual String getFormatName() = 0;
  52047. /** Returns true if the given stream seems to contain data that this format
  52048. understands.
  52049. The format class should only read the first few bytes of the stream and sniff
  52050. for header bytes that it understands.
  52051. @see decodeImage
  52052. */
  52053. virtual bool canUnderstand (InputStream& input) = 0;
  52054. /** Tries to decode and return an image from the given stream.
  52055. This will be called for an image format after calling its canUnderStand() method
  52056. to see if it can handle the stream.
  52057. @param input the stream to read the data from. The stream will be positioned
  52058. at the start of the image data (but this may not necessarily
  52059. be position 0)
  52060. @returns the image that was decoded, or an invalid image if it fails.
  52061. @see loadFrom
  52062. */
  52063. virtual Image decodeImage (InputStream& input) = 0;
  52064. /** Attempts to write an image to a stream.
  52065. To specify extra information like encoding quality, there will be appropriate parameters
  52066. in the subclasses of the specific file types.
  52067. @returns true if it nothing went wrong.
  52068. */
  52069. virtual bool writeImageToStream (const Image& sourceImage,
  52070. OutputStream& destStream) = 0;
  52071. /** Tries the built-in decoders to see if it can find one to read this stream.
  52072. There are currently built-in decoders for PNG, JPEG and GIF formats.
  52073. The object that is returned should not be deleted by the caller.
  52074. @see canUnderstand, decodeImage, loadFrom
  52075. */
  52076. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  52077. /** Tries to load an image from a stream.
  52078. This will use the findImageFormatForStream() method to locate a suitable
  52079. codec, and use that to load the image.
  52080. @returns the image that was decoded, or an invalid image if it fails.
  52081. */
  52082. static Image loadFrom (InputStream& input);
  52083. /** Tries to load an image from a file.
  52084. This will use the findImageFormatForStream() method to locate a suitable
  52085. codec, and use that to load the image.
  52086. @returns the image that was decoded, or an invalid image if it fails.
  52087. */
  52088. static Image loadFrom (const File& file);
  52089. /** Tries to load an image from a block of raw image data.
  52090. This will use the findImageFormatForStream() method to locate a suitable
  52091. codec, and use that to load the image.
  52092. @returns the image that was decoded, or an invalid image if it fails.
  52093. */
  52094. static Image loadFrom (const void* rawData,
  52095. const int numBytesOfData);
  52096. };
  52097. /**
  52098. A subclass of ImageFileFormat for reading and writing PNG files.
  52099. @see ImageFileFormat, JPEGImageFormat
  52100. */
  52101. class JUCE_API PNGImageFormat : public ImageFileFormat
  52102. {
  52103. public:
  52104. PNGImageFormat();
  52105. ~PNGImageFormat();
  52106. String getFormatName();
  52107. bool canUnderstand (InputStream& input);
  52108. Image decodeImage (InputStream& input);
  52109. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  52110. };
  52111. /**
  52112. A subclass of ImageFileFormat for reading and writing JPEG files.
  52113. @see ImageFileFormat, PNGImageFormat
  52114. */
  52115. class JUCE_API JPEGImageFormat : public ImageFileFormat
  52116. {
  52117. public:
  52118. JPEGImageFormat();
  52119. ~JPEGImageFormat();
  52120. /** Specifies the quality to be used when writing a JPEG file.
  52121. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  52122. any negative value is "default" quality
  52123. */
  52124. void setQuality (float newQuality);
  52125. String getFormatName();
  52126. bool canUnderstand (InputStream& input);
  52127. Image decodeImage (InputStream& input);
  52128. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  52129. private:
  52130. float quality;
  52131. };
  52132. /**
  52133. A subclass of ImageFileFormat for reading GIF files.
  52134. @see ImageFileFormat, PNGImageFormat, JPEGImageFormat
  52135. */
  52136. class JUCE_API GIFImageFormat : public ImageFileFormat
  52137. {
  52138. public:
  52139. GIFImageFormat();
  52140. ~GIFImageFormat();
  52141. String getFormatName();
  52142. bool canUnderstand (InputStream& input);
  52143. Image decodeImage (InputStream& input);
  52144. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  52145. };
  52146. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  52147. /*** End of inlined file: juce_ImageFileFormat.h ***/
  52148. #endif
  52149. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  52150. #endif
  52151. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  52152. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  52153. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  52154. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  52155. /**
  52156. A class to take care of the logic involved with the loading/saving of some kind
  52157. of document.
  52158. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  52159. functions you need for documents that get saved to a file, so this class attempts
  52160. to abstract most of the boring stuff.
  52161. Your subclass should just implement all the pure virtual methods, and you can
  52162. then use the higher-level public methods to do the load/save dialogs, to warn the user
  52163. about overwriting files, etc.
  52164. The document object keeps track of whether it has changed since it was last saved or
  52165. loaded, so when you change something, call its changed() method. This will set a
  52166. flag so it knows it needs saving, and will also broadcast a change message using the
  52167. ChangeBroadcaster base class.
  52168. @see ChangeBroadcaster
  52169. */
  52170. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  52171. {
  52172. public:
  52173. /** Creates a FileBasedDocument.
  52174. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  52175. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  52176. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  52177. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  52178. */
  52179. FileBasedDocument (const String& fileExtension,
  52180. const String& fileWildCard,
  52181. const String& openFileDialogTitle,
  52182. const String& saveFileDialogTitle);
  52183. /** Destructor. */
  52184. virtual ~FileBasedDocument();
  52185. /** Returns true if the changed() method has been called since the file was
  52186. last saved or loaded.
  52187. @see resetChangedFlag, changed
  52188. */
  52189. bool hasChangedSinceSaved() const { return changedSinceSave; }
  52190. /** Called to indicate that the document has changed and needs saving.
  52191. This method will also trigger a change message to be sent out using the
  52192. ChangeBroadcaster base class.
  52193. After calling the method, the hasChangedSinceSaved() method will return true, until
  52194. it is reset either by saving to a file or using the resetChangedFlag() method.
  52195. @see hasChangedSinceSaved, resetChangedFlag
  52196. */
  52197. virtual void changed();
  52198. /** Sets the state of the 'changed' flag.
  52199. The 'changed' flag is set to true when the changed() method is called - use this method
  52200. to reset it or to set it without also broadcasting a change message.
  52201. @see changed, hasChangedSinceSaved
  52202. */
  52203. void setChangedFlag (bool hasChanged);
  52204. /** Tries to open a file.
  52205. If the file opens correctly, the document's file (see the getFile() method) is set
  52206. to this new one; if it fails, the document's file is left unchanged, and optionally
  52207. a message box is shown telling the user there was an error.
  52208. @returns true if the new file loaded successfully
  52209. @see loadDocument, loadFromUserSpecifiedFile
  52210. */
  52211. bool loadFrom (const File& fileToLoadFrom,
  52212. bool showMessageOnFailure);
  52213. /** Asks the user for a file and tries to load it.
  52214. This will pop up a dialog box using the title, file extension and
  52215. wildcard specified in the document's constructor, and asks the user
  52216. for a file. If they pick one, the loadFrom() method is used to
  52217. try to load it, optionally showing a message if it fails.
  52218. @returns true if a file was loaded; false if the user cancelled or if they
  52219. picked a file which failed to load correctly
  52220. @see loadFrom
  52221. */
  52222. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  52223. /** A set of possible outcomes of one of the save() methods
  52224. */
  52225. enum SaveResult
  52226. {
  52227. savedOk = 0, /**< indicates that a file was saved successfully. */
  52228. userCancelledSave, /**< indicates that the user aborted the save operation. */
  52229. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  52230. };
  52231. /** Tries to save the document to the last file it was saved or loaded from.
  52232. This will always try to write to the file, even if the document isn't flagged as
  52233. having changed.
  52234. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  52235. true, it will prompt the user to pick a file, as if
  52236. saveAsInteractive() was called.
  52237. @param showMessageOnFailure if true it will show a warning message when if the
  52238. save operation fails
  52239. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  52240. */
  52241. SaveResult save (bool askUserForFileIfNotSpecified,
  52242. bool showMessageOnFailure);
  52243. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  52244. it if they say yes.
  52245. If you've got a document open and want to close it (e.g. to quit the app), this is the
  52246. method to call.
  52247. If the document doesn't need saving it'll return the value savedOk so
  52248. you can go ahead and delete the document.
  52249. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  52250. return savedOk, so again, you can safely delete the document.
  52251. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  52252. close-document operation.
  52253. And if they click "save changes", it'll try to save and either return savedOk, or
  52254. failedToWriteToFile if there was a problem.
  52255. @see save, saveAs, saveAsInteractive
  52256. */
  52257. SaveResult saveIfNeededAndUserAgrees();
  52258. /** Tries to save the document to a specified file.
  52259. If this succeeds, it'll also change the document's internal file (as returned by
  52260. the getFile() method). If it fails, the file will be left unchanged.
  52261. @param newFile the file to try to write to
  52262. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  52263. the user first if they want to overwrite it
  52264. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  52265. use the saveAsInteractive() method to ask the user for a
  52266. filename
  52267. @param showMessageOnFailure if true and the write operation fails, it'll show
  52268. a message box to warn the user
  52269. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  52270. */
  52271. SaveResult saveAs (const File& newFile,
  52272. bool warnAboutOverwritingExistingFiles,
  52273. bool askUserForFileIfNotSpecified,
  52274. bool showMessageOnFailure);
  52275. /** Prompts the user for a filename and tries to save to it.
  52276. This will pop up a dialog box using the title, file extension and
  52277. wildcard specified in the document's constructor, and asks the user
  52278. for a file. If they pick one, the saveAs() method is used to try to save
  52279. to this file.
  52280. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  52281. the user first if they want to overwrite it
  52282. @see saveIfNeededAndUserAgrees, save, saveAs
  52283. */
  52284. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  52285. /** Returns the file that this document was last successfully saved or loaded from.
  52286. When the document object is created, this will be set to File::nonexistent.
  52287. It is changed when one of the load or save methods is used, or when setFile()
  52288. is used to explicitly set it.
  52289. */
  52290. const File& getFile() const { return documentFile; }
  52291. /** Sets the file that this document thinks it was loaded from.
  52292. This won't actually load anything - it just changes the file stored internally.
  52293. @see getFile
  52294. */
  52295. void setFile (const File& newFile);
  52296. protected:
  52297. /** Overload this to return the title of the document.
  52298. This is used in message boxes, filenames and file choosers, so it should be
  52299. something sensible.
  52300. */
  52301. virtual const String getDocumentTitle() = 0;
  52302. /** This method should try to load your document from the given file.
  52303. If it fails, it should return an error message. If it succeeds, it should return
  52304. an empty string.
  52305. */
  52306. virtual const String loadDocument (const File& file) = 0;
  52307. /** This method should try to write your document to the given file.
  52308. If it fails, it should return an error message. If it succeeds, it should return
  52309. an empty string.
  52310. */
  52311. virtual const String saveDocument (const File& file) = 0;
  52312. /** This is used for dialog boxes to make them open at the last folder you
  52313. were using.
  52314. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  52315. the last document that was used - you might want to store this value
  52316. in a static variable, or even in your application's properties. It should
  52317. be a global setting rather than a property of this object.
  52318. This method works very well in conjunction with a RecentlyOpenedFilesList
  52319. object to manage your recent-files list.
  52320. As a default value, it's ok to return File::nonexistent, and the document
  52321. object will use a sensible one instead.
  52322. @see RecentlyOpenedFilesList
  52323. */
  52324. virtual const File getLastDocumentOpened() = 0;
  52325. /** This is used for dialog boxes to make them open at the last folder you
  52326. were using.
  52327. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  52328. the last document that was used - you might want to store this value
  52329. in a static variable, or even in your application's properties. It should
  52330. be a global setting rather than a property of this object.
  52331. This method works very well in conjunction with a RecentlyOpenedFilesList
  52332. object to manage your recent-files list.
  52333. @see RecentlyOpenedFilesList
  52334. */
  52335. virtual void setLastDocumentOpened (const File& file) = 0;
  52336. private:
  52337. File documentFile;
  52338. bool changedSinceSave;
  52339. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  52340. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBasedDocument);
  52341. };
  52342. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  52343. /*** End of inlined file: juce_FileBasedDocument.h ***/
  52344. #endif
  52345. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  52346. #endif
  52347. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  52348. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  52349. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  52350. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  52351. /**
  52352. Manages a set of files for use as a list of recently-opened documents.
  52353. This is a handy class for holding your list of recently-opened documents, with
  52354. helpful methods for things like purging any non-existent files, automatically
  52355. adding them to a menu, and making persistence easy.
  52356. @see File, FileBasedDocument
  52357. */
  52358. class JUCE_API RecentlyOpenedFilesList
  52359. {
  52360. public:
  52361. /** Creates an empty list.
  52362. */
  52363. RecentlyOpenedFilesList();
  52364. /** Destructor. */
  52365. ~RecentlyOpenedFilesList();
  52366. /** Sets a limit for the number of files that will be stored in the list.
  52367. When addFile() is called, then if there is no more space in the list, the
  52368. least-recently added file will be dropped.
  52369. @see getMaxNumberOfItems
  52370. */
  52371. void setMaxNumberOfItems (int newMaxNumber);
  52372. /** Returns the number of items that this list will store.
  52373. @see setMaxNumberOfItems
  52374. */
  52375. int getMaxNumberOfItems() const noexcept { return maxNumberOfItems; }
  52376. /** Returns the number of files in the list.
  52377. The most recently added file is always at index 0.
  52378. */
  52379. int getNumFiles() const;
  52380. /** Returns one of the files in the list.
  52381. The most recently added file is always at index 0.
  52382. */
  52383. File getFile (int index) const;
  52384. /** Returns an array of all the absolute pathnames in the list.
  52385. */
  52386. const StringArray& getAllFilenames() const noexcept { return files; }
  52387. /** Clears all the files from the list. */
  52388. void clear();
  52389. /** Adds a file to the list.
  52390. The file will be added at index 0. If this file is already in the list, it will
  52391. be moved up to index 0, but a file can only appear once in the list.
  52392. If the list already contains the maximum number of items that is permitted, the
  52393. least-recently added file will be dropped from the end.
  52394. */
  52395. void addFile (const File& file);
  52396. /** Removes a file from the list. */
  52397. void removeFile (const File& file);
  52398. /** Checks each of the files in the list, removing any that don't exist.
  52399. You might want to call this after reloading a list of files, or before putting them
  52400. on a menu.
  52401. */
  52402. void removeNonExistentFiles();
  52403. /** Adds entries to a menu, representing each of the files in the list.
  52404. This is handy for creating an "open recent file..." menu in your app. The
  52405. menu items are numbered consecutively starting with the baseItemId value,
  52406. and can either be added as complete pathnames, or just the last part of the
  52407. filename.
  52408. If dontAddNonExistentFiles is true, then each file will be checked and only those
  52409. that exist will be added.
  52410. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  52411. pointers to file objects. Any files that appear in this list will not be added to the
  52412. menu - the reason for this is that you might have a number of files already open, so
  52413. might not want these to be shown in the menu.
  52414. It returns the number of items that were added.
  52415. */
  52416. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  52417. int baseItemId,
  52418. bool showFullPaths,
  52419. bool dontAddNonExistentFiles,
  52420. const File** filesToAvoid = nullptr);
  52421. /** Returns a string that encapsulates all the files in the list.
  52422. The string that is returned can later be passed into restoreFromString() in
  52423. order to recreate the list. This is handy for persisting your list, e.g. in
  52424. a PropertiesFile object.
  52425. @see restoreFromString
  52426. */
  52427. String toString() const;
  52428. /** Restores the list from a previously stringified version of the list.
  52429. Pass in a stringified version created with toString() in order to persist/restore
  52430. your list.
  52431. @see toString
  52432. */
  52433. void restoreFromString (const String& stringifiedVersion);
  52434. private:
  52435. StringArray files;
  52436. int maxNumberOfItems;
  52437. JUCE_LEAK_DETECTOR (RecentlyOpenedFilesList);
  52438. };
  52439. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  52440. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  52441. #endif
  52442. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  52443. #endif
  52444. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  52445. /*** Start of inlined file: juce_SystemClipboard.h ***/
  52446. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  52447. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  52448. /**
  52449. Handles reading/writing to the system's clipboard.
  52450. */
  52451. class JUCE_API SystemClipboard
  52452. {
  52453. public:
  52454. /** Copies a string of text onto the clipboard */
  52455. static void copyTextToClipboard (const String& text);
  52456. /** Gets the current clipboard's contents.
  52457. Obviously this might have come from another app, so could contain
  52458. anything..
  52459. */
  52460. static String getTextFromClipboard();
  52461. };
  52462. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  52463. /*** End of inlined file: juce_SystemClipboard.h ***/
  52464. #endif
  52465. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  52466. #endif
  52467. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  52468. #endif
  52469. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  52470. /*** Start of inlined file: juce_UnitTest.h ***/
  52471. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  52472. #define __JUCE_UNITTEST_JUCEHEADER__
  52473. class UnitTestRunner;
  52474. /**
  52475. This is a base class for classes that perform a unit test.
  52476. To write a test using this class, your code should look something like this:
  52477. @code
  52478. class MyTest : public UnitTest
  52479. {
  52480. public:
  52481. MyTest() : UnitTest ("Foobar testing") {}
  52482. void runTest()
  52483. {
  52484. beginTest ("Part 1");
  52485. expect (myFoobar.doesSomething());
  52486. expect (myFoobar.doesSomethingElse());
  52487. beginTest ("Part 2");
  52488. expect (myOtherFoobar.doesSomething());
  52489. expect (myOtherFoobar.doesSomethingElse());
  52490. ...etc..
  52491. }
  52492. };
  52493. // Creating a static instance will automatically add the instance to the array
  52494. // returned by UnitTest::getAllTests(), so the test will be included when you call
  52495. // UnitTestRunner::runAllTests()
  52496. static MyTest test;
  52497. @endcode
  52498. To run a test, use the UnitTestRunner class.
  52499. @see UnitTestRunner
  52500. */
  52501. class JUCE_API UnitTest
  52502. {
  52503. public:
  52504. /** Creates a test with the given name. */
  52505. explicit UnitTest (const String& name);
  52506. /** Destructor. */
  52507. virtual ~UnitTest();
  52508. /** Returns the name of the test. */
  52509. const String& getName() const noexcept { return name; }
  52510. /** Runs the test, using the specified UnitTestRunner.
  52511. You shouldn't need to call this method directly - use
  52512. UnitTestRunner::runTests() instead.
  52513. */
  52514. void performTest (UnitTestRunner* runner);
  52515. /** Returns the set of all UnitTest objects that currently exist. */
  52516. static Array<UnitTest*>& getAllTests();
  52517. /** You can optionally implement this method to set up your test.
  52518. This method will be called before runTest().
  52519. */
  52520. virtual void initialise();
  52521. /** You can optionally implement this method to clear up after your test has been run.
  52522. This method will be called after runTest() has returned.
  52523. */
  52524. virtual void shutdown();
  52525. /** Implement this method in your subclass to actually run your tests.
  52526. The content of your implementation should call beginTest() and expect()
  52527. to perform the tests.
  52528. */
  52529. virtual void runTest() = 0;
  52530. /** Tells the system that a new subsection of tests is beginning.
  52531. This should be called from your runTest() method, and may be called
  52532. as many times as you like, to demarcate different sets of tests.
  52533. */
  52534. void beginTest (const String& testName);
  52535. /** Checks that the result of a test is true, and logs this result.
  52536. In your runTest() method, you should call this method for each condition that
  52537. you want to check, e.g.
  52538. @code
  52539. void runTest()
  52540. {
  52541. beginTest ("basic tests");
  52542. expect (x + y == 2);
  52543. expect (getThing() == someThing);
  52544. ...etc...
  52545. }
  52546. @endcode
  52547. If testResult is true, a pass is logged; if it's false, a failure is logged.
  52548. If the failure message is specified, it will be written to the log if the test fails.
  52549. */
  52550. void expect (bool testResult, const String& failureMessage = String::empty);
  52551. /** Compares two values, and if they don't match, prints out a message containing the
  52552. expected and actual result values.
  52553. */
  52554. template <class ValueType>
  52555. void expectEquals (ValueType actual, ValueType expected, String failureMessage = String::empty)
  52556. {
  52557. const bool result = (actual == expected);
  52558. if (! result)
  52559. {
  52560. if (failureMessage.isNotEmpty())
  52561. failureMessage << " -- ";
  52562. failureMessage << "Expected value: " << expected << ", Actual value: " << actual;
  52563. }
  52564. expect (result, failureMessage);
  52565. }
  52566. /** Writes a message to the test log.
  52567. This can only be called from within your runTest() method.
  52568. */
  52569. void logMessage (const String& message);
  52570. private:
  52571. const String name;
  52572. UnitTestRunner* runner;
  52573. JUCE_DECLARE_NON_COPYABLE (UnitTest);
  52574. };
  52575. /**
  52576. Runs a set of unit tests.
  52577. You can instantiate one of these objects and use it to invoke tests on a set of
  52578. UnitTest objects.
  52579. By using a subclass of UnitTestRunner, you can intercept logging messages and
  52580. perform custom behaviour when each test completes.
  52581. @see UnitTest
  52582. */
  52583. class JUCE_API UnitTestRunner
  52584. {
  52585. public:
  52586. /** */
  52587. UnitTestRunner();
  52588. /** Destructor. */
  52589. virtual ~UnitTestRunner();
  52590. /** Runs a set of tests.
  52591. The tests are performed in order, and the results are logged. To run all the
  52592. registered UnitTest objects that exist, use runAllTests().
  52593. */
  52594. void runTests (const Array<UnitTest*>& tests, bool assertOnFailure);
  52595. /** Runs all the UnitTest objects that currently exist.
  52596. This calls runTests() for all the objects listed in UnitTest::getAllTests().
  52597. */
  52598. void runAllTests (bool assertOnFailure);
  52599. /** Contains the results of a test.
  52600. One of these objects is instantiated each time UnitTest::beginTest() is called, and
  52601. it contains details of the number of subsequent UnitTest::expect() calls that are
  52602. made.
  52603. */
  52604. struct TestResult
  52605. {
  52606. /** The main name of this test (i.e. the name of the UnitTest object being run). */
  52607. String unitTestName;
  52608. /** The name of the current subcategory (i.e. the name that was set when UnitTest::beginTest() was called). */
  52609. String subcategoryName;
  52610. /** The number of UnitTest::expect() calls that succeeded. */
  52611. int passes;
  52612. /** The number of UnitTest::expect() calls that failed. */
  52613. int failures;
  52614. /** A list of messages describing the failed tests. */
  52615. StringArray messages;
  52616. };
  52617. /** Returns the number of TestResult objects that have been performed.
  52618. @see getResult
  52619. */
  52620. int getNumResults() const noexcept;
  52621. /** Returns one of the TestResult objects that describes a test that has been run.
  52622. @see getNumResults
  52623. */
  52624. const TestResult* getResult (int index) const noexcept;
  52625. protected:
  52626. /** Called when the list of results changes.
  52627. You can override this to perform some sort of behaviour when results are added.
  52628. */
  52629. virtual void resultsUpdated();
  52630. /** Logs a message about the current test progress.
  52631. By default this just writes the message to the Logger class, but you could override
  52632. this to do something else with the data.
  52633. */
  52634. virtual void logMessage (const String& message);
  52635. private:
  52636. friend class UnitTest;
  52637. UnitTest* currentTest;
  52638. String currentSubCategory;
  52639. OwnedArray <TestResult, CriticalSection> results;
  52640. bool assertOnFailure;
  52641. void beginNewTest (UnitTest* test, const String& subCategory);
  52642. void endTest();
  52643. void addPass();
  52644. void addFail (const String& failureMessage);
  52645. JUCE_DECLARE_NON_COPYABLE (UnitTestRunner);
  52646. };
  52647. #endif // __JUCE_UNITTEST_JUCEHEADER__
  52648. /*** End of inlined file: juce_UnitTest.h ***/
  52649. #endif
  52650. #endif
  52651. /*** End of inlined file: juce_app_includes.h ***/
  52652. #endif
  52653. #if JUCE_MSVC
  52654. #pragma warning (pop)
  52655. #pragma pack (pop)
  52656. #endif
  52657. END_JUCE_NAMESPACE
  52658. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  52659. #ifdef JUCE_NAMESPACE
  52660. // this will obviously save a lot of typing, but can be disabled by
  52661. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  52662. using namespace JUCE_NAMESPACE;
  52663. /* On the Mac, these symbols are defined in the Mac libraries, so
  52664. these macros make it easier to reference them without writing out
  52665. the namespace every time.
  52666. If you run into difficulties where these macros interfere with the contents
  52667. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  52668. the comments in that file for more information.
  52669. */
  52670. #if (JUCE_MAC || JUCE_IOS) && ! JUCE_DONT_DEFINE_MACROS
  52671. #define Component JUCE_NAMESPACE::Component
  52672. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  52673. #define Point JUCE_NAMESPACE::Point
  52674. #define Button JUCE_NAMESPACE::Button
  52675. #endif
  52676. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  52677. it easier to use the juce version explicitly.
  52678. If you run into difficulties where this macro interferes with other 3rd party header
  52679. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  52680. file for more information.
  52681. */
  52682. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  52683. #define Rectangle JUCE_NAMESPACE::Rectangle
  52684. #endif
  52685. #endif
  52686. #endif
  52687. /* Easy autolinking to the right JUCE libraries under win32.
  52688. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  52689. including this header file.
  52690. */
  52691. #if JUCE_MSVC
  52692. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  52693. /** If you want your application to link to Juce as a DLL instead of
  52694. a static library (on win32), just define the JUCE_DLL macro before
  52695. including juce.h
  52696. */
  52697. #ifdef JUCE_DLL
  52698. #if JUCE_DEBUG
  52699. #define AUTOLINKEDLIB "JUCE_debug.lib"
  52700. #else
  52701. #define AUTOLINKEDLIB "JUCE.lib"
  52702. #endif
  52703. #else
  52704. #if JUCE_DEBUG
  52705. #ifdef _WIN64
  52706. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  52707. #else
  52708. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  52709. #endif
  52710. #else
  52711. #ifdef _WIN64
  52712. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  52713. #else
  52714. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  52715. #endif
  52716. #endif
  52717. #endif
  52718. #pragma comment(lib, AUTOLINKEDLIB)
  52719. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  52720. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  52721. #endif
  52722. // Auto-link the other win32 libs that are needed by library calls..
  52723. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  52724. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  52725. // Auto-links to various win32 libs that are needed by library calls..
  52726. #pragma comment(lib, "kernel32.lib")
  52727. #pragma comment(lib, "user32.lib")
  52728. #pragma comment(lib, "shell32.lib")
  52729. #pragma comment(lib, "gdi32.lib")
  52730. #pragma comment(lib, "vfw32.lib")
  52731. #pragma comment(lib, "comdlg32.lib")
  52732. #pragma comment(lib, "winmm.lib")
  52733. #pragma comment(lib, "wininet.lib")
  52734. #pragma comment(lib, "ole32.lib")
  52735. #pragma comment(lib, "oleaut32.lib")
  52736. #pragma comment(lib, "advapi32.lib")
  52737. #pragma comment(lib, "ws2_32.lib")
  52738. #pragma comment(lib, "version.lib")
  52739. #pragma comment(lib, "shlwapi.lib")
  52740. #pragma comment(lib, "imm32.lib")
  52741. #ifdef _NATIVE_WCHAR_T_DEFINED
  52742. #ifdef _DEBUG
  52743. #pragma comment(lib, "comsuppwd.lib")
  52744. #else
  52745. #pragma comment(lib, "comsuppw.lib")
  52746. #endif
  52747. #else
  52748. #ifdef _DEBUG
  52749. #pragma comment(lib, "comsuppd.lib")
  52750. #else
  52751. #pragma comment(lib, "comsupp.lib")
  52752. #endif
  52753. #endif
  52754. #if JUCE_OPENGL
  52755. #pragma comment(lib, "OpenGL32.Lib")
  52756. #pragma comment(lib, "GlU32.Lib")
  52757. #endif
  52758. #if JUCE_QUICKTIME
  52759. #pragma comment (lib, "QTMLClient.lib")
  52760. #endif
  52761. #if JUCE_USE_CAMERA
  52762. #pragma comment (lib, "Strmiids.lib")
  52763. #pragma comment (lib, "wmvcore.lib")
  52764. #endif
  52765. #if JUCE_DIRECT2D
  52766. #pragma comment (lib, "Dwrite.lib")
  52767. #pragma comment (lib, "D2d1.lib")
  52768. #endif
  52769. #if JUCE_DIRECTSHOW
  52770. #pragma comment (lib, "strmiids.lib")
  52771. #endif
  52772. #if JUCE_MEDIAFOUNDATION
  52773. #pragma comment (lib, "mfuuid.lib")
  52774. #endif
  52775. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  52776. #endif
  52777. #endif
  52778. #endif
  52779. #endif // __JUCE_JUCEHEADER__
  52780. /*** End of inlined file: juce.h ***/
  52781. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__